<?php
/** JSON helpers + request body parser + CORS. */

function send_json($data, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function json_error(int $status, string $detail): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['detail' => $detail]);
    exit;
}

function read_json_body(): array {
    $raw = file_get_contents('php://input');
    if ($raw === '' || $raw === false) return [];
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        json_error(400, 'Invalid JSON body');
    }
    return $data;
}

function send_cors_headers(): void {
    // Allow browser requests from your own domain. Replace with the
    // exact origin if you want to lock this down.
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: content-type, authorization, x-upstream-ua, range');
    header('Access-Control-Allow-Credentials: true');
    // Never let Cloudflare / proxies cache API responses. Without this
    // a stale HTML SPA response (from before /api/ was deployed) can
    // be served to mobile clients and break login / data calls.
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
    header('CDN-Cache-Control: no-store');
    header('Cloudflare-CDN-Cache-Control: no-store');
}

function require_field(array $body, string $name): string {
    if (!isset($body[$name]) || $body[$name] === '') {
        json_error(400, "Missing field: $name");
    }
    return (string)$body[$name];
}
