<?php
/**
 * api/sports.php — GET /api/sports?days=N
 *
 * Devuelve la configuración de deportes, el catálogo de ligas y los eventos
 * filtrados a los próximos N días (por defecto el valor de Ajustes, máx. 365).
 *
 * Response:
 * {
 *   "config":  { "enabled": bool, "header": "...", "border": "...",
 *                "background": "...", "text": "...", "days": N },
 *   "leagues": [ { "name": "...", "league_id": "..." }, ... ],
 *   "events":  [ { "league": "...", "home": "...", "away": "...",
 *                  "date": "YYYY-MM-DD", "time": "HH:MM",
 *                  "channels": ["...", ...] }, ... ]
 * }
 */

declare(strict_types=1);

require_once __DIR__ . '/../lib/helpers.php';
require_once __DIR__ . '/../lib/settings.php';
require_once __DIR__ . '/../lib/device.php';

// Solo GET (lectura).
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
    json_out(['error' => 'method_not_allowed'], 405);
}

try {
    $config = sport_block();

    // days: query param opcional; por defecto el de Ajustes. Acotado a 1..365.
    $days = $config['days'];
    if (isset($_GET['days']) && is_numeric($_GET['days'])) {
        $days = (int) $_GET['days'];
    }
    if ($days < 1)   { $days = 1; }
    if ($days > 365) { $days = 365; }
    $config['days'] = $days;

    json_out([
        'config'  => $config,
        'leagues' => leagues_list(),
        'events'  => sport_events_window($days),
    ], 200);
} catch (Throwable $ex) {
    error_log('[api/sports] ' . $ex->getMessage());
    json_out(['error' => 'server_error'], 500);
}
