<?php
/**
 * import_espn.php — 2da fuente: API pública de ESPN (sin key).
 *
 * Aporta lo que TheSportsDB free no da: CANALES de TV (broadcasts), MARCADOR en
 * vivo + estado, y cobertura sólida de deportes de USA + ligas top internacionales,
 * con logos. Corre EN EL SERVIDOR y guarda en sport_events con source='espn'.
 *
 * Dedup: ESPN "es dueño" de sus ligas -> borra en su ventana lo suyo (espn) y lo de
 * TheSportsDB (auto) con el mismo nombre de liga. El importador de TheSportsDB, a su
 * vez, saltea las ligas que ya trajo ESPN. Por eso el cron de ESPN corre ANTES.
 *
 * Un request por liga usando ?dates=YYYYMMDD-YYYYMMDD (rango). ~18 requests, rápido.
 * Uso: GET import_espn.php[?token=XXX][&days=N]
 */

declare(strict_types=1);
require __DIR__ . '/lib/ibo.php';

ignore_user_abort(true);
@set_time_limit(0);
header('Content-Type: application/json; charset=utf-8');
ibo_nocache();

$need = trim((string) settings_get('sport_import_token', ''));
if ($need !== '' && (string) ($_GET['token'] ?? '') !== $need) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden']);
    exit;
}

$days = (int) ($_GET['days'] ?? settings_get('sport_days', '7'));
$days = max(1, min(14, $days));

// Ligas ESPN: [sport canónico, path ESPN, nombre override|null].
// null = usa el nombre que da ESPN. El override se usa donde solapa con TheSportsDB
// (para que el dedup por nombre funcione) o para un nombre más lindo.
// ESPN es dueño de TODO el fútbol, golf, tenis, motor (F1/NASCAR/IndyCar) y MMA.
$LEAGUES = [
    // USA majors
    ['baseball',   'baseball/mlb', 'MLB'],
    ['basketball', 'basketball/nba', 'NBA'],
    ['basketball', 'basketball/wnba', 'WNBA'],
    ['basketball', 'basketball/mens-college-basketball', 'NCAA Basketball'],
    ['amfootball', 'football/nfl', 'NFL'],
    ['amfootball', 'football/college-football', 'NCAA Football'],
    ['icehockey',  'hockey/nhl', 'NHL'],
    // MMA
    ['fighting', 'mma/ufc', 'UFC'],
    ['fighting', 'mma/pfl', 'PFL'],
    ['fighting', 'mma/bellator', 'Bellator'],
    // Golf / Tenis / Motor (ESPN)
    ['golf',       'golf/pga', 'PGA Tour'],
    ['golf',       'golf/lpga', 'LPGA'],
    ['golf',       'golf/eur', 'DP World Tour'],
    ['tennis',     'tennis/atp', 'ATP World Tour'],
    ['tennis',     'tennis/wta', 'WTA Tour'],
    ['motorsport', 'racing/f1', 'Formula 1'],
    ['motorsport', 'racing/nascar-premier', 'NASCAR Cup Series'],
    ['motorsport', 'racing/irl', 'IndyCar Series'],
    // Fútbol (nombre de ESPN salvo overrides)
    ['soccer', 'soccer/usa.1', 'American Major League Soccer'],
    ['soccer', 'soccer/usa.nwsl', null],
    ['soccer', 'soccer/mex.1', 'Mexican Primera League'],
    ['soccer', 'soccer/mex.2', null],
    ['soccer', 'soccer/eng.1', null], ['soccer', 'soccer/eng.2', null], ['soccer', 'soccer/eng.3', null],
    ['soccer', 'soccer/eng.fa', null], ['soccer', 'soccer/eng.league_cup', null],
    ['soccer', 'soccer/sco.1', null], ['soccer', 'soccer/ger.1', null], ['soccer', 'soccer/ger.2', null],
    ['soccer', 'soccer/ita.1', null], ['soccer', 'soccer/ita.2', null],
    ['soccer', 'soccer/esp.1', null], ['soccer', 'soccer/esp.2', null],
    ['soccer', 'soccer/fra.1', null], ['soccer', 'soccer/fra.2', null],
    ['soccer', 'soccer/ned.1', null], ['soccer', 'soccer/por.1', null], ['soccer', 'soccer/bel.1', null],
    ['soccer', 'soccer/tur.1', null], ['soccer', 'soccer/gre.1', null], ['soccer', 'soccer/den.1', null],
    ['soccer', 'soccer/aut.1', null], ['soccer', 'soccer/sui.1', null], ['soccer', 'soccer/nor.1', null],
    ['soccer', 'soccer/swe.1', 'Swedish Allsvenskan'], ['soccer', 'soccer/rus.1', null],
    ['soccer', 'soccer/arg.1', null], ['soccer', 'soccer/bra.1', null], ['soccer', 'soccer/chi.1', null],
    ['soccer', 'soccer/col.1', null], ['soccer', 'soccer/uru.1', null], ['soccer', 'soccer/chn.1', null],
    ['soccer', 'soccer/jpn.1', null], ['soccer', 'soccer/aus.1', null], ['soccer', 'soccer/ksa.1', null],
    ['soccer', 'soccer/uefa.champions', null], ['soccer', 'soccer/uefa.europa', null],
    ['soccer', 'soccer/uefa.europa.conf', null], ['soccer', 'soccer/uefa.nations', null],
    ['soccer', 'soccer/conmebol.libertadores', null], ['soccer', 'soccer/conmebol.sudamericana', null],
    ['soccer', 'soccer/concacaf.league', null], ['soccer', 'soccer/fifa.friendly', null],
    ['soccer', 'soccer/club.friendly', null],
];

// Migración: columnas status + score (además de las de import_sport.php).
$cols = array_column(db()->query('PRAGMA table_info(sport_events)')->fetchAll(), 'name');
foreach (['source' => "'manual'", 'ext_id' => "''", 'category' => "''", 'home_badge' => "''",
          'away_badge' => "''", 'league_badge' => "''", 'status' => "''", 'score' => "''"] as $col => $def) {
    if (!in_array($col, $cols, true)) {
        db()->exec("ALTER TABLE sport_events ADD COLUMN $col TEXT NOT NULL DEFAULT $def");
    }
}

function espn_json(string $url): ?array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 14, CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_USERAGENT => 'Mozilla/5.0',
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    if (!is_string($raw) || $raw === '') {
        return null;
    }
    $j = json_decode($raw, true);
    return is_array($j) ? $j : null;
}

$beg      = gmdate('Ymd');
$end      = gmdate('Ymd', strtotime('+' . ($days - 1) . ' day') ?: time());
$rangeBeg = gmdate('Y-m-d');
$rangeEnd = gmdate('Y-m-d', strtotime('+' . ($days - 1) . ' day') ?: time());

$rows      = [];
$attempts  = 0;
$hits      = 0;
$perLeague = [];
$leagueNames = [];
foreach ($LEAGUES as [$sport, $path, $ovr]) {
    $attempts++;
    $j = espn_json("https://site.api.espn.com/apis/site/v2/sports/$path/scoreboard?dates=$beg-$end");
    if ($j === null) { continue; }
    $hits++;
    $name = ($ovr !== null && $ovr !== '') ? $ovr : (string) ($j['leagues'][0]['name'] ?? $path);
    $leagueNames[$name] = true;
    $lb = $j['leagues'][0]['logos'][0]['href'] ?? '';
    $n  = 0;
    foreach (($j['events'] ?? []) ?: [] as $e) {
        $comp = $e['competitions'][0] ?? [];
        $home = null; $away = null;
        foreach (($comp['competitors'] ?? []) as $x) {
            if (($x['homeAway'] ?? '') === 'home') { $home = $x; }
            elseif (($x['homeAway'] ?? '') === 'away') { $away = $x; }
        }
        $iso  = (string) ($e['date'] ?? '');
        $date = substr($iso, 0, 10);
        $time = substr($iso, 11, 5);
        if ($date < $rangeBeg || $date > $rangeEnd) { continue; }

        $ch = [];
        foreach (($comp['broadcasts'] ?? []) as $b) {
            foreach (($b['names'] ?? []) as $nm) { $ch[] = $nm; }
        }
        if ($ch === []) {
            foreach (($comp['geoBroadcasts'] ?? []) as $b) {
                $nm = $b['media']['shortName'] ?? '';
                if ($nm !== '') { $ch[] = $nm; }
            }
        }
        $ch = array_values(array_unique(array_filter($ch)));

        $state  = $comp['status']['type']['state'] ?? '';
        $status = $state === 'in' ? 'live' : ($state === 'post' ? 'final' : '');

        if ($home !== null) {
            // Partido normal (2 equipos).
            $score = '';
            if ($state === 'in' || $state === 'post') {
                $hs = (string) ($home['score'] ?? '');
                $as = (string) ($away['score'] ?? '');
                if ($hs !== '' || $as !== '') { $score = $hs . '-' . $as; }
            }
            $rows[] = [
                'category' => $sport, 'league' => $name,
                'home' => trim((string) ($home['team']['displayName'] ?? '')),
                'away' => $away ? trim((string) ($away['team']['displayName'] ?? '')) : '',
                'date' => $date, 'time' => $time, 'channels' => implode(', ', $ch),
                'ext_id' => (string) ($e['id'] ?? ''),
                'home_badge' => (string) ($home['team']['logo'] ?? ''),
                'away_badge' => $away ? (string) ($away['team']['logo'] ?? '') : '',
                'league_badge' => (string) $lb, 'status' => $status, 'score' => $score,
            ];
        } else {
            // Individual/torneo (tenis, golf, F1…): el evento es el nombre (sin home/away).
            $title = trim((string) ($e['name'] ?? $e['shortName'] ?? ''));
            if ($title === '') { continue; }
            $rows[] = [
                'category' => $sport, 'league' => $name, 'home' => $title, 'away' => '',
                'date' => $date, 'time' => $time, 'channels' => implode(', ', $ch),
                'ext_id' => (string) ($e['id'] ?? ''),
                'home_badge' => '', 'away_badge' => '', 'league_badge' => (string) $lb,
                'status' => $status, 'score' => '',
            ];
        }
        $n++;
    }
    $perLeague[$name] = $n;
}

// Guard: si casi todo falló, no toques la BD.
if ($attempts > 0 && ($hits / $attempts) < 0.5) {
    echo json_encode(['ok' => true, 'replaced' => false, 'reason' => 'source_down', 'requests' => $hits, 'attempts' => $attempts]);
    exit;
}

// Reemplazar: borra ESPN de la ventana + los 'auto' (TheSportsDB) de las MISMAS ligas.
$names = array_keys($leagueNames);
$ph = implode(',', array_fill(0, count($names), '?'));
db()->beginTransaction();
db()->prepare("DELETE FROM sport_events WHERE source='espn' AND event_date>=? AND event_date<=?")
    ->execute([$rangeBeg, $rangeEnd]);
db()->prepare("DELETE FROM sport_events WHERE source='auto' AND event_date>=? AND event_date<=? AND league IN ($ph)")
    ->execute(array_merge([$rangeBeg, $rangeEnd], $names));
$ins = db()->prepare(
    "INSERT INTO sport_events(league,home,away,event_date,event_time,channels,sort,created_at,source,ext_id,category,home_badge,away_badge,league_badge,status,score)
     VALUES(?,?,?,?,?,?,?,?, 'espn', ?, ?, ?, ?, ?, ?, ?)"
);
$k = 0;
foreach ($rows as $r) {
    $ins->execute([$r['league'], $r['home'], $r['away'], $r['date'], $r['time'], $r['channels'], $k, gmdate('c'),
        $r['ext_id'], $r['category'], $r['home_badge'], $r['away_badge'], $r['league_badge'], $r['status'], $r['score']]);
    $k++;
}
db()->commit();

settings_set('sport_last_import_espn', gmdate('c'));
settings_set('sport_enabled', '1');

echo json_encode([
    'ok'       => true,
    'replaced' => true,
    'source'   => 'espn',
    'imported' => $k,
    'leagues'  => array_filter($perLeague),
    'requests' => $hits,
    'attempts' => $attempts,
    'at'       => gmdate('c'),
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
