<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/sport_api_lib.php';

mocker_admin_require_permission('special-odds');

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

$date = trim((string) ($_GET['date'] ?? ''));
if ($date === '') {
    $date = gmdate('Y-m-d');
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    echo json_encode(['ok' => false, 'error' => 'bad_date'], JSON_UNESCAPED_UNICODE);
    exit;
}

$key = defined('SPORT_RAPIDAPI_KEY') ? (string) SPORT_RAPIDAPI_KEY : '';
if ($key === '') {
    echo json_encode(['ok' => false, 'error' => 'no_api_key'], JSON_UNESCAPED_UNICODE);
    exit;
}

$tpl = defined('SPORT_SCHEDULE_PATH_TEMPLATE') ? (string) SPORT_SCHEDULE_PATH_TEMPLATE : '/api/v1/sport/football/scheduled-events/{date}';
$path = str_replace('{date}', rawurlencode($date), $tpl);
if (!str_starts_with($path, '/')) {
    $path = '/' . $path;
}

$raw = mocker_sport_rapidapi_get($path);
if ($raw === null) {
    echo json_encode(['ok' => false, 'error' => 'api_fetch_failed', 'path' => $path], JSON_UNESCAPED_UNICODE);
    exit;
}

$events = mocker_sport_parse_events_list($raw);

echo json_encode(
    [
        'ok' => true,
        'date' => $date,
        'path' => $path,
        'events' => $events,
        'count' => count($events),
    ],
    JSON_UNESCAPED_UNICODE
);
