<?php
/**
 * api/sports.php — GET /api/sports?days=N&type=sport_type
 *
 * Devuelve la configuración de deportes, el catálogo de ligas y los eventos
 * filtrados a los próximos N días y opcionalmente por tipo de deporte.
 *
 * Response:
 * {
 *   "config":  { "enabled": bool, "header": "...", "border": "...",
 *                "background": "...", "text": "...", "days": N },
 *   "leagues": [ { "name": "...", "league_id": "...", "sport_type": "..." }, ... ],
 *   "events":  [ { "league": "...", "sport_type": "football", "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';
require_once __DIR__ . '/../lib/sport.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;

    // Filtro opcional por tipo de deporte (?type=football / ?type=basketball)
    $sportType = isset($_GET['type']) ? trim((string)$_GET['type']) : null;

    $leagues = function_exists('leagues_list') ? leagues_list() : [];
    $events  = function_exists('sport_events_window') ? sport_events_window($days, $sportType) : [];

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