<?php
/**
 * =====================================================================
 * Nadi Player — /api/sports/fixtures.php   (JSON edition)
 * =====================================================================
 * Public endpoint the mobile app calls. Serves World Cup fixtures from
 * the JSON-backed `worldcup_matches` table (openfootball data uploaded
 * / auto-synced via the Admin Panel) in the exact shape the React
 * `useWorldCupFixtures` hook expects:
 *
 *   { "configured": true, "matches": [
 *       { id, home:{name,code}, away:{name,code},
 *         homeScore, awayScore, status, kickoff, group, venue } ] }
 *
 * NO api-football. NO paid API. NO server-side API key.
 *
 * Drop at: public_html/api/sports/fixtures.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';

// CORS (matches the rest of the API).
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');

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

// Never return a blank 500 — convert any fatal into a clean JSON
// `configured:false` so the app's mock-data fallback kicks in.
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_app_payload(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(200);
    echo json_encode(['configured' => false, 'matches' => [], 'error' => $e->getMessage()]);
}
