<?php
// =============================================================================
// SportsProvider — TheSportsDB free tier (v1).
//
// API base: https://www.thesportsdb.com/api/v1/json/3/...
// No key needed for v1. Heavy caching (12h leagues, 5min events) so the cron
// + admin "Pull now" doesn't get rate-limited.
// =============================================================================

require_once __DIR__ . '/provider_interface.php';

class TheSportsDbProvider implements SportsProvider
{
    private const BASE = 'https://www.thesportsdb.com/api/v1/json/3';

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

    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::BASE . $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'] ?? $payload['countries'] ?? [];
        $out  = [];
        foreach ($rows as $r) {
            // Filter to Soccer-only by default — most IBO setups use sports for
            // football; admins can broaden the filter via webview_settings.
            $sport = (string)($r['strSport'] ?? '');
            if ($sport !== '' && stripos($sport, 'Soccer') === false) continue;
            $out[] = [
                'source_league_id' => (string)($r['idLeague'] ?? ''),
                'name'             => (string)($r['strLeague'] ?? ''),
                'country'          => '',  // /all_leagues.php doesn't expose country; pull via lookupleague.php on demand
                'logo_url'         => '',
            ];
        }
        return $out;
    }

    public function fetch_events(array $league_ids, int $from_ts, int $to_ts): array
    {
        $events = [];
        // Hit both eventsnextleague + eventspastleague so we always have content
        // even when a league is between seasons (eventsnextleague returns null).
        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
                $payload = $cached;
                if ($payload === null) {
                    $raw = sports_http_get(self::BASE . $endpoint);
                    if ($raw === null) continue;
                    $payload = json_decode($raw, true);
                    if (!is_array($payload)) continue;
                    sports_cache_set($this->name(), $endpoint, $payload);
                }
                if (empty($payload['events']) || !is_array($payload['events'])) continue;
                foreach ($payload['events'] as $r) {
                    $kickoff_ts = isset($r['strTimestamp']) ? strtotime($r['strTimestamp']) : null;
                    if ($kickoff_ts !== null && ($kickoff_ts < $from_ts || $kickoff_ts > $to_ts)) continue;
                    $events[] = [
                        'source_event_id'  => (string)($r['idEvent'] ?? ''),
                        'source_league_id' => (string)$lid,
                        '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'           => $this->status_of($r),
                        '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'] ?? ''),
                    ];
                }
            }
        }
        // De-dupe by source_event_id (past + next can overlap on a "today" row)
        $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 status_of(array $r): string
    {
        $s = strtolower((string)($r['strStatus'] ?? ''));
        if (in_array($s, ['ft', 'aet', 'pen', 'finished'], true)) return 'FT';
        if (in_array($s, ['1h', '2h', 'ht', 'in play', 'live'], true)) return 'LIVE';
        if ($s === 'tba' || $s === 'tbd') return 'TBA';
        return 'UPCOMING';
    }
}
