<?php
// =============================================================================
// SportsProvider — TheSportsDB premium.
//
// Premium key works in BOTH:
//   v1 path:  https://www.thesportsdb.com/api/v1/json/{KEY}/...
//             (full v1 method surface — higher rate limit than free key "3")
//   v2 header: https://www.thesportsdb.com/api/v2/json/...   X-API-KEY: {KEY}
//             (premium-only methods — livescore/soccer, livescore/all)
//
// Strategy: use v1 paths for the catalog (leagues + per-league + by-day events)
// and v2 livescore for the LIVE bucket.
// =============================================================================

require_once __DIR__ . '/provider_interface.php';

class SportsDbPaidProvider implements SportsProvider
{
    private const V1 = 'https://www.thesportsdb.com/api/v1/json';
    private const V2 = 'https://www.thesportsdb.com/api/v2/json';

    private string $key;

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    public function name(): string { return 'thesportsdb_paid'; }

    // -----------------------------------------------------------------------
    // Leagues — v1 /all_leagues.php (premium key → no 30-req/min cap)
    // -----------------------------------------------------------------------
    public function fetch_leagues(): array
    {
        $endpoint = '/all_leagues.php';
        $cached = sports_cache_get($this->name(), $endpoint, 43200); // 12h
        if ($cached !== null) return $this->map_leagues($cached);

        $raw = sports_http_get(self::V1 . '/' . rawurlencode($this->key) . $endpoint);
        if ($raw === null) return [];
        $payload = json_decode($raw, true);
        if (!is_array($payload)) return [];
        sports_cache_set($this->name(), $endpoint, $payload);
        return $this->map_leagues($payload);
    }

    private function map_leagues(array $payload): array
    {
        $rows = $payload['leagues'] ?? [];
        $out  = [];
        foreach ($rows as $r) {
            $sport = (string)($r['strSport'] ?? '');
            if ($sport !== '' && stripos($sport, 'Soccer') === false) continue;
            $out[] = [
                'source_league_id' => (string)($r['idLeague'] ?? ''),
                'name'             => (string)($r['strLeague'] ?? ''),
                'country'          => '',
                'logo_url'         => '',
            ];
        }
        return $out;
    }

    // -----------------------------------------------------------------------
    // Events — combine three sources so we always have content:
    //   1. v2 livescore/all       (LIVE right now, any sport — filter to enabled)
    //   2. v1 eventsnextleague    (UPCOMING for each enabled league)
    //   3. v1 eventspastleague    (recent FT for each enabled league, ~14 days back)
    // -----------------------------------------------------------------------
    public function fetch_events(array $league_ids, int $from_ts, int $to_ts): array
    {
        $events = [];

        // 1. Premium livescore — X-API-KEY header
        $live_endpoint = '/livescore/all';
        $cached = sports_cache_get($this->name(), $live_endpoint, 60); // 1 min
        $payload = $cached;
        if ($payload === null) {
            $raw = sports_http_get(self::V2 . $live_endpoint, ['X-API-KEY: ' . $this->key]);
            if ($raw !== null) {
                $payload = json_decode($raw, true);
                if (is_array($payload)) sports_cache_set($this->name(), $live_endpoint, $payload);
            }
        }
        if (is_array($payload)) {
            foreach (($payload['livescore'] ?? []) as $r) {
                if (!empty($league_ids) && !in_array((string)($r['idLeague'] ?? ''), $league_ids, true)) continue;
                $events[] = $this->normalize_event($r);
            }
        }

        // 2 + 3. Per-league upcoming AND past, fill the kickoff window
        foreach ($league_ids as $lid) {
            foreach (['eventsnextleague.php', 'eventspastleague.php'] as $script) {
                $endpoint = '/' . $script . '?id=' . urlencode($lid);
                $cached = sports_cache_get($this->name(), $endpoint, 600); // 10 min
                $p = $cached;
                if ($p === null) {
                    $raw = sports_http_get(self::V1 . '/' . rawurlencode($this->key) . $endpoint);
                    if ($raw === null) continue;
                    $p = json_decode($raw, true);
                    if (is_array($p)) sports_cache_set($this->name(), $endpoint, $p);
                }
                if (!is_array($p) || empty($p['events']) || !is_array($p['events'])) continue;
                foreach ($p['events'] as $r) {
                    $kickoff_ts = isset($r['strTimestamp']) ? strtotime((string)$r['strTimestamp']) : null;
                    if ($kickoff_ts !== null && ($kickoff_ts < $from_ts || $kickoff_ts > $to_ts)) continue;
                    $events[] = $this->normalize_event($r);
                }
            }
        }

        // De-dupe by source_event_id — keep the LIVE row when both LIVE + UPCOMING land
        $byId = [];
        foreach ($events as $e) {
            if ($e['source_event_id'] === '') continue;
            if (!isset($byId[$e['source_event_id']]) || $e['status'] === 'LIVE') {
                $byId[$e['source_event_id']] = $e;
            }
        }
        return array_values($byId);
    }

    private function normalize_event(array $r): array
    {
        $kickoff_ts = isset($r['strTimestamp']) ? strtotime((string)$r['strTimestamp']) : null;
        $status_raw = strtolower((string)($r['strStatus'] ?? ''));
        if (in_array($status_raw, ['ft', 'aet', 'pen', 'finished', 'match finished'], true)) $st = 'FT';
        elseif (in_array($status_raw, ['1h', '2h', 'ht', 'in play', 'live'], true) || isset($r['idLiveScore'])) $st = 'LIVE';
        elseif ($status_raw === 'tba' || $status_raw === 'tbd') $st = 'TBA';
        else $st = 'UPCOMING';

        return [
            'source_event_id'  => (string)($r['idEvent'] ?? ''),
            'source_league_id' => (string)($r['idLeague'] ?? ''),
            'home_team'        => (string)($r['strHomeTeam'] ?? ''),
            'away_team'        => (string)($r['strAwayTeam'] ?? ''),
            'home_badge_url'   => (string)($r['strHomeTeamBadge'] ?? ''),
            'away_badge_url'   => (string)($r['strAwayTeamBadge'] ?? ''),
            'kickoff_ts'       => $kickoff_ts,
            'status'           => $st,
            'home_score'       => isset($r['intHomeScore']) && $r['intHomeScore'] !== '' ? (int)$r['intHomeScore'] : null,
            'away_score'       => isset($r['intAwayScore']) && $r['intAwayScore'] !== '' ? (int)$r['intAwayScore'] : null,
            'channels_csv'     => (string)($r['strTvStation'] ?? ''),
            'thumb_url'        => (string)($r['strThumb'] ?? ''),
        ];
    }
}
