<?php
/**
 * =====================================================================
 * Nadi Player — /api/sports/fixtures_wc2026.php
 * =====================================================================
 * World Cup 2026 proxy with a 24-HOUR cache, as requested.
 *
 *   • If the admin has synced/uploaded data into the DB, this serves
 *     that (so manual score edits + Locks always win).
 *   • Otherwise it fetches the openfootball 2026 raw JSON directly,
 *     caches it on disk for 24h, transforms it on the fly, and serves
 *     it — zero-config bootstrap.
 *
 * Output: {"configured": true, "matches": [...]}  (the exact shape the
 * React useWorldCupFixtures hook expects).
 *
 * NOTE: `fixtures.php` (DB-only, manual-priority) remains the primary
 * endpoint the app points at. This file is the cached GitHub variant.
 *
 * Drop at: public_html/api/sports/fixtures_wc2026.php
 * =====================================================================
 */

ini_set('display_errors', '0');
error_reporting(E_ALL);
ini_set('log_errors', '1');

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../lib/util.php';
require_once __DIR__ . '/../lib/db.php';
require_once __DIR__ . '/lib_worldcup.php';

if (function_exists('send_cors_headers')) {
    send_cors_headers();
} else {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
}
header('Content-Type: application/json; charset=utf-8');
// Let CDNs/browsers cache for 1h too (server file cache is 24h).
header('Cache-Control: public, max-age=3600');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

register_shutdown_function(function () {
    $e = error_get_last();
    if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        if (!headers_sent()) {
            http_response_code(200);
            header('Content-Type: application/json; charset=utf-8');
        }
        echo json_encode(['configured' => false, 'matches' => [], 'error' => $e['message']]);
    }
});

try {
    echo json_encode(wc_payload_with_fallback(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(200);
    echo json_encode(['configured' => false, 'matches' => [], 'error' => $e->getMessage()]);
}
