<?php
require_once __DIR__ . '/functions.php';

function api_json(bool $success, string $message, array $extra = []): void {
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $extra));
    exit;
}

function api_require_post(): void {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        api_json(false, 'Method not allowed.');
    }
}

/** Honeypot check — bots tend to fill every field including hidden ones. */
function api_is_spam(): bool {
    return !empty($_POST['website']);
}

function api_str(string $key, int $maxLen = 255): string {
    return mb_substr(trim($_POST[$key] ?? ''), 0, $maxLen);
}

function api_valid_email(string $email): bool {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
