<?php
/**
 * includes/sports-sync-lib.php
 * Zero-Delay Pro Exchange Multi-Provider Engine + Hybrid Auto-Settlement
 * - Strictly REAL Cricket (4), Football (1), Tennis (2), Horse Racing (7) + ALL Winner Cups / Outrights
 * - Blocks ALL Virtual / (e) / Dim Cricket / T5 XI / T10 XI / SRL / Esports / Cyber / FIFA / Basketball
 * - Preserves closed/completed match winners & scorecards in sports_result_archive
 * - Full Cricket, Football & Tennis score/result parser + 30s Automatic Odds & Fancy Settlement
 */

if (!function_exists('sports_terminal_statuses')) {
    function sports_terminal_statuses(): array {
        return [
            'CLOSED', 'CLOSE', 'SETTLED', 'SETTLE', 'CANCELLED', 'CANCELED',
            'INACTIVE', 'REMOVED', 'REMOVE', 'COMPLETE', 'COMPLETED', 'FINISHED',
            'FINISH', 'DECLARED', 'RESULT', 'VOID', 'ABANDONED', 'EXPIRED',
            'STOPPED', 'STOP', 'DELETED', 'DELETE', 'OFF', 'DISABLED', 'END', 'ENDED'
        ];
    }
}

if (!function_exists('sports_is_virtual_event')) {
    function sports_is_virtual_event(array $ctx): bool {
        foreach (['is_virtual', 'isVirtual', 'virtual', 'isSimulated', 'simulated'] as $flagKey) {
            if (!array_key_exists($flagKey, $ctx)) continue;
            $v = $ctx[$flagKey];
            if ($v === true || $v === 1 || (is_string($v) && in_array(strtolower(trim($v)), ['1', 'true', 'yes'], true))) {
                return true;
            }
        }

        $gtype = strtolower(trim((string)($ctx['gtype'] ?? $ctx['mtype'] ?? '')));
        if ($gtype !== '' && (strpos($gtype, 'virtual') !== false || strpos($gtype, 'esport') !== false || strpos($gtype, 'cyber') !== false)) {
            return true;
        }

        $combined = strtolower(trim(implode(' ', array_filter([
            (string)($ctx['sport_name'] ?? ''),
            (string)($ctx['competition_name'] ?? ''),
            (string)($ctx['event_name'] ?? ''),
            (string)($ctx['market_name'] ?? ''),
        ]))));
        if ($combined === '') return false;

        if (preg_match('/\(\s*(?:e|v|srl|sim|ai|bot|cyber|virtual|esports?)\s*\)/i', $combined)) {
            return true;
        }

        if (preg_match('/\b(virtual|v-?(?:cricket|football|soccer|tennis|racing|horse|ipl|t10|bbl)|dim\s+cricket|t[568]\s*xi|t10\s*xi|[12]\s*overs?|simulated|srl|e-?sports?|e-?soccer|e-?football|e-?cricket|e-?tennis|efifa|fifa|volta|cyber|nba\s*2k|gt\s*leagues?|electronic|2x[468]\s*min|greyhound)\b/i', $combined)) {
            return true;
        }

        return false;
    }
}

if (!function_exists('sports_resolve_sport_meta')) {
    function sports_resolve_sport_meta(string $rawName, string $rawId = ''): ?array {
        $n = strtolower(trim($rawName));
        $id = trim($rawId);

        if ($n !== '' && preg_match('/\b(virtual|simulated|srl|e-?sports?|e-?soccer|e-?football|e-?cricket|e-?tennis|cyber|fifa|volta|basketball|kabaddi|greyhound|casino|binary|politics|lottery|motor|formula|f1|table\s*tennis)\b/i', $n)) {
            return null;
        }

        if ($id === '4' || $n === 'cricket') {
            return ['etid' => 4, 'name' => 'Cricket', 'slug' => 'cricket', 'sort' => 1];
        }
        if ($id === '1' || $n === 'soccer' || $n === 'football') {
            return ['etid' => 1, 'name' => 'Football', 'slug' => 'football', 'sort' => 2];
        }
        if ($id === '2' || $n === 'tennis') {
            return ['etid' => 2, 'name' => 'Tennis', 'slug' => 'tennis', 'sort' => 3];
        }
        if ($id === '7' || $n === 'horse racing' || $n === 'horse-racing' || $n === 'racing' || (strpos($n, 'horse') !== false && strpos($n, 'racing') !== false)) {
            return ['etid' => 7, 'name' => 'Horse Racing', 'slug' => 'horse-racing', 'sort' => 4];
        }
        return null;
    }
}

if (!function_exists('sports_slug_to_etid')) {
    function sports_slug_to_etid(string $slug): int {
        $s = strtolower(trim($slug));
        if ($s === 'football' || $s === 'soccer') return 1;
        if ($s === 'tennis') return 2;
        if ($s === 'horse-racing' || strpos($s, 'horse') !== false) return 7;
        return 4;
    }
}

if (!function_exists('sports_match_fingerprint')) {
    function sports_match_fingerprint(int $etid, string $eventName): string {
        $clean = strtolower(trim($eventName));
        $clean = preg_replace('/\bwomen\b|\bwmn\b/i', 'w', $clean);
        $parts = preg_split('/\s+v(?:s)?\.?\s+/i', $clean, 2);
        if (count($parts) === 2) {
            $a = preg_replace('/[^a-z0-9]/', '', $parts[0]);
            $b = preg_replace('/[^a-z0-9]/', '', $parts[1]);
            $pair = [$a, $b];
            sort($pair);
            return $etid . '|' . $pair[0] . '|' . $pair[1];
        }
        return $etid . '|' . preg_replace('/[^a-z0-9]/', '', $clean);
    }
}

if (!function_exists('sports_names_match')) {
    function sports_names_match(string $a, string $b): bool {
        $norm = static function (string $s): string {
            $s = strtolower(trim($s));
            $s = preg_replace('/[^a-z0-9\s]/', ' ', $s);
            return trim((string)preg_replace('/\s+/', ' ', $s));
        };
        $na = $norm($a);
        $nb = $norm($b);
        if ($na === '' || $nb === '') return false;
        if ($na === $nb) return true;
        if (strlen($na) >= 4 && strlen($nb) >= 4 && (strpos($na, $nb) !== false || strpos($nb, $na) !== false)) {
            return true;
        }

        $acronym = static function (string $s): string {
            $words = array_values(array_filter(explode(' ', $s)));
            if (count($words) <= 1) return $words[0] ?? '';
            $out = '';
            foreach ($words as $w) {
                $out .= $w[0];
            }
            return $out;
        };
        $aa = $acronym($na);
        $ab = $acronym($nb);
        if (strlen($aa) >= 2 && ($aa === $nb || in_array($aa, explode(' ', $nb), true))) return true;
        if (strlen($ab) >= 2 && ($ab === $na || in_array($ab, explode(' ', $na), true))) return true;

        $stop = ['fc', 'sc', 'cf', 'ac', 'as', 'united', 'city', 'club', 'team', 'women', 'wmn', 'men', 'xi', 'super', 'kings', 'royals'];
        $ta = array_values(array_diff(array_filter(explode(' ', $na), static fn($w) => strlen($w) >= 3), $stop));
        $tb = array_values(array_diff(array_filter(explode(' ', $nb), static fn($w) => strlen($w) >= 3), $stop));
        if ($ta && $tb) {
            $common = array_intersect($ta, $tb);
            if (count($common) >= 1 && (count($ta) === 1 || count($tb) === 1 || count($common) >= 2)) {
                return true;
            }
        }
        return false;
    }
}

if (!function_exists('sports_find_best_selection')) {
    function sports_find_best_selection(string $candidate, array $selections): string {
        $cand = trim($candidate);
        if ($cand === '') return '';
        foreach ($selections as $s) {
            if (strcasecmp((string)$s, $cand) === 0) return (string)$s;
        }
        foreach ($selections as $s) {
            if (sports_names_match((string)$s, $cand)) return (string)$s;
        }
        return '';
    }
}

if (!function_exists('sports_parse_book_status')) {
    function sports_parse_book_status(string $book): array {
        $res = ['status' => '', 'in_play' => false, 'has_price' => false];
        $raw = trim($book);
        if ($raw === '') return $res;

        if ($raw[0] === '{' || $raw[0] === '[') {
            $dec = json_decode($raw, true);
            if (is_array($dec)) {
                $res['status'] = strtoupper(trim((string)($dec['status'] ?? $dec['marketStatus'] ?? $dec['gstatus'] ?? '')));
                $ip = $dec['inPlay'] ?? $dec['in_play'] ?? false;
                $res['in_play'] = ($ip === true || $ip === 1 || (is_string($ip) && strtolower(trim($ip)) === 'true'));
                $res['has_price'] = !empty($dec['runners']);
            }
            return $res;
        }

        if (strpos($raw, '~') !== false && preg_match('/~[1-9][0-9.]*/', $raw)) {
            $res['has_price'] = true;
        }

        $p = explode('|', $raw);
        if (count($p) < 2) return $res;

        $startIdx = -1;
        foreach ($p as $idx => $seg) {
            if ($idx >= 1 && strpos($seg, '~') !== false) { $startIdx = $idx; break; }
        }
        $headerEnd = $startIdx >= 0 ? $startIdx : count($p);
        $terminal = sports_terminal_statuses();
        $known = array_merge(['OPEN', 'ACTIVE', 'SUSPENDED', 'SUSPEND', 'LOCKED', 'BET_LOCK', 'BALL_RUNNING', 'BALL RUNNING'], $terminal);

        for ($i = 1; $i < $headerEnd; $i++) {
            $tok = strtoupper(trim((string)$p[$i]));
            if ($tok === '') continue;
            if (in_array($tok, $known, true)) {
                if ($res['status'] === '' || $res['status'] === 'OPEN' || $res['status'] === 'ACTIVE' || in_array($tok, $terminal, true)) {
                    $res['status'] = $tok;
                }
            }
        }

        if ($res['status'] === '' && isset($p[2]) && ($startIdx < 0 || $startIdx > 2)) {
            $cand = strtoupper(trim((string)$p[2]));
            if ($cand !== '' && $cand !== 'TRUE' && $cand !== 'FALSE' && !is_numeric($cand)) $res['status'] = $cand;
        }
        if (isset($p[3]) && ($startIdx < 0 || $startIdx > 3)) {
            $res['in_play'] = strtolower(trim((string)$p[3])) === 'true';
        }
        return $res;
    }
}

if (!function_exists('sports_extract_winner_from_market')) {
    function sports_extract_winner_from_market(array $market, string $book = ''): string {
        foreach (['winner', 'winnerName', 'winner_name'] as $wk) {
            if (!empty($market[$wk]) && is_string($market[$wk])) {
                return trim($market[$wk]);
            }
        }

        $runners = $market['runners'] ?? ($market['section'] ?? []);
        if (is_string($runners)) {
            $dec = json_decode($runners, true);
            $runners = is_array($dec) ? $dec : [];
        }

        $runnerMap = [];
        if (is_array($runners)) {
            foreach ($runners as $r) {
                if (!is_array($r)) continue;
                $rName = trim((string)($r['runnerName'] ?? $r['name'] ?? $r['nat'] ?? $r['rname'] ?? ''));
                $rId = trim((string)($r['selectionId'] ?? $r['runnerId'] ?? $r['id'] ?? $r['sid'] ?? ''));
                if ($rId !== '' && $rName !== '') {
                    $runnerMap[$rId] = $rName;
                }
                $rSt = strtoupper(trim((string)($r['status'] ?? $r['gstatus'] ?? '')));
                if ($rSt === 'WINNER' || !empty($r['winner']) || !empty($r['isWinner'])) {
                    if ($rName !== '') return $rName;
                }
            }
        }

        if ($book !== '' && stripos($book, '~WINNER') !== false) {
            $chunks = preg_split('/[|,]/', $book);
            if (is_array($chunks)) {
                foreach ($chunks as $ch) {
                    if (stripos($ch, '~WINNER') === false) continue;
                    $seg = explode('~', $ch);
                    $rid = trim((string)($seg[0] ?? ''));
                    if ($rid !== '' && isset($runnerMap[$rid])) {
                        return $runnerMap[$rid];
                    }
                }
            }
        }

        return '';
    }
}

if (!function_exists('sports_alt_id_map_get')) {
    function sports_alt_id_map_get(string $eventId): array {
        $file = sys_get_temp_dir() . '/sp_alt_id_map.json';
        if (!is_file($file)) return [];
        $data = json_decode((string)@file_get_contents($file), true);
        return (is_array($data) && isset($data[$eventId]) && is_array($data[$eventId])) ? $data[$eventId] : [];
    }
}

if (!function_exists('sports_provider_lock_get')) {
    function sports_provider_lock_get(string $eventId): ?array {
        $file = sys_get_temp_dir() . '/sp_plock_' . md5($eventId) . '.json';
        if (!is_file($file)) return null;
        $dec = json_decode((string)@file_get_contents($file), true);
        if (!is_array($dec) || empty($dec['provider'])) return null;
        $ttl = ($dec['provider'] === 'allpanel') ? 300 : 15;
        if ((time() - (int)@filemtime($file)) > $ttl) return null;
        return $dec;
    }
}

if (!function_exists('sports_provider_lock_set')) {
    function sports_provider_lock_set(string $eventId, string $provider, int $fails = 0): void {
        $file = sys_get_temp_dir() . '/sp_plock_' . md5($eventId) . '.json';
        @file_put_contents($file, json_encode([
            'provider' => $provider,
            'fails' => $fails,
            'ts' => time(),
        ]), LOCK_EX);
    }
}

if (!function_exists('sports_provider_lock_clear')) {
    function sports_provider_lock_clear(string $eventId): void {
        $file = sys_get_temp_dir() . '/sp_plock_' . md5($eventId) . '.json';
        if (is_file($file)) @unlink($file);
    }
}

if (!function_exists('sports_clear_match_caches')) {
    function sports_clear_match_caches(array $eventIds): void {
        $tmp = sys_get_temp_dir();
        foreach (array_unique(array_filter(array_map('strval', $eventIds))) as $evId) {
            $cleanEvId = preg_replace('/[^0-9A-Za-z._-]/', '', $evId);
            $files = [
                $tmp . '/sp_plock_' . md5($evId) . '.json',
                $tmp . '/sp_last_ok_' . md5($evId) . '.json',
                $tmp . '/sp_score_live_' . md5($cleanEvId) . '.json',
                $tmp . '/sp_scoreurl_' . md5($cleanEvId) . '.txt',
                $tmp . '/sp_tvmeta_' . md5($cleanEvId) . '.txt',
            ];
            foreach ([4, 1, 2, 7] as $etid) {
                $files[] = $tmp . '/sp_lcache_' . md5('live_ev_v2_' . $evId . '_' . $etid) . '.json';
            }
            foreach ($files as $f) {
                if (is_file($f)) @unlink($f);
            }
        }
    }
}

if (!function_exists('sports_live_cache_get')) {
    function sports_live_cache_get(string $key, float $ttlSec = 0.35): ?array {
        $file = sys_get_temp_dir() . '/sp_lcache_' . md5($key) . '.json';
        if (!is_file($file)) return null;
        $raw = @file_get_contents($file);
        if (!$raw) return null;
        $dec = json_decode($raw, true);
        if (!is_array($dec) || !isset($dec['_ts']) || !isset($dec['payload'])) return null;
        if ((microtime(true) - (float)$dec['_ts']) > $ttlSec) return null;
        return is_array($dec['payload']) ? $dec['payload'] : null;
    }
}

if (!function_exists('sports_live_cache_set')) {
    function sports_live_cache_set(string $key, array $payload): void {
        $file = sys_get_temp_dir() . '/sp_lcache_' . md5($key) . '.json';
        @file_put_contents($file, json_encode([
            '_ts' => microtime(true),
            'payload' => $payload,
        ], JSON_UNESCAPED_UNICODE), LOCK_EX);
    }
}

if (!function_exists('sports_provider_get')) {
    function sports_provider_get(string $path, int $timeout = 8): array {
        static $ch = null;
        $base = 'https://api.oexch99.com/delaymarkets';
        $url = $base . '/' . ltrim($path, '/');
        if (!function_exists('curl_init')) throw new RuntimeException('PHP cURL extension is required.');
        if ($ch === null) $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_CONNECTTIMEOUT_MS => min(1500, $timeout * 1000),
            CURLOPT_TIMEOUT_MS => $timeout * 1000,
            CURLOPT_ENCODING => '',
            CURLOPT_TCP_KEEPALIVE => 1,
            CURLOPT_TCP_NODELAY => 1,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Cache-Control: no-cache, no-store, max-age=0',
                'Pragma: no-cache',
            ],
            CURLOPT_USERAGENT => 'SportsDataSync/3.5',
        ]);
        $body = curl_exec($ch);
        $err = curl_error($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($body === false || $err !== '') {
            curl_close($ch);
            $ch = null;
            throw new RuntimeException('Provider connection failed: ' . $err);
        }
        if ($code < 200 || $code >= 300) throw new RuntimeException('Provider returned HTTP ' . $code);
        $data = json_decode($body, true);
        if (!is_array($data)) throw new RuntimeException('Provider response was not valid JSON.');
        return $data;
    }
}

if (!function_exists('sports_multi_race')) {
    function sports_multi_race(array $requests, int $maxWaitMs = 1100, int $graceMs = 260): array {
        if (!$requests || !function_exists('curl_multi_init')) return [];

        $mh = curl_multi_init();
        $handles = [];
        $meta = [];
        $results = [];
        $startTime = microtime(true);

        foreach ($requests as $key => $cfg) {
            $ch = curl_init();
            $timeoutMs = (int)($cfg['timeout_ms'] ?? $maxWaitMs);
            $connectMs = (int)($cfg['connect_ms'] ?? min(500, $timeoutMs));
            $method = strtoupper((string)($cfg['method'] ?? 'GET'));
            $headers = array_merge([
                'Accept: application/json, text/plain, */*',
                'Cache-Control: no-cache, no-store, max-age=0',
                'Pragma: no-cache',
            ], is_array($cfg['headers'] ?? null) ? $cfg['headers'] : []);

            $opts = [
                CURLOPT_URL => (string)$cfg['url'],
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_CONNECTTIMEOUT_MS => $connectMs,
                CURLOPT_TIMEOUT_MS => $timeoutMs,
                CURLOPT_NOSIGNAL => 1,
                CURLOPT_ENCODING => '',
                CURLOPT_TCP_KEEPALIVE => 1,
                CURLOPT_TCP_NODELAY => 1,
                CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
                CURLOPT_HTTPHEADER => $headers,
                CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
            ];

            if ($method === 'POST') {
                $opts[CURLOPT_POST] = true;
                $opts[CURLOPT_POSTFIELDS] = is_array($cfg['body'] ?? null)
                    ? json_encode($cfg['body'])
                    : (string)($cfg['body'] ?? '');
            }

            curl_setopt_array($ch, $opts);
            curl_multi_add_handle($mh, $ch);
            $handles[$key] = $ch;
            $meta[(int)$ch] = [
                'key' => $key,
                'fast_win' => !empty($cfg['fast_win']),
                'validator' => $cfg['validator'] ?? null,
            ];
        }

        $firstFastWinAt = null;
        $active = null;

        do {
            $mrc = curl_multi_exec($mh, $active);

            while ($info = curl_multi_info_read($mh)) {
                $ch = $info['handle'];
                $mInfo = $meta[(int)$ch] ?? null;
                if (!$mInfo) continue;

                $key = $mInfo['key'];
                $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $raw = ($info['result'] === CURLE_OK && $code >= 200 && $code < 300)
                    ? curl_multi_getcontent($ch)
                    : '';
                $decoded = ($raw !== '' && $raw !== null) ? json_decode($raw, true) : null;
                $elapsedMs = (int)round((microtime(true) - $startTime) * 1000);

                $isValidJson = is_array($decoded);
                $isValid = $isValidJson && $decoded !== [];
                if ($isValid && is_callable($mInfo['validator'])) {
                    $isValid = (bool)$mInfo['validator']($decoded);
                }

                $results[$key] = [
                    'ok' => $isValid,
                    'http_code' => $code,
                    'empty_payload' => ($isValidJson && !$isValid),
                    'ms' => $elapsedMs,
                    'data' => $isValid ? $decoded : null,
                ];

                if ($isValid && $mInfo['fast_win'] && $firstFastWinAt === null) {
                    $firstFastWinAt = microtime(true);
                }

                curl_multi_remove_handle($mh, $ch);
                curl_close($ch);
                unset($handles[$key]);
            }

            $now = microtime(true);
            $totalElapsedMs = ($now - $startTime) * 1000;
            if ($totalElapsedMs >= $maxWaitMs) break;
            if ($firstFastWinAt !== null && (($now - $firstFastWinAt) * 1000) >= $graceMs) break;

            if ($active > 0) {
                $sel = curl_multi_select($mh, 0.01);
                if ($sel === -1) usleep(2000);
            }
        } while ($active > 0 && ($mrc === CURLM_OK || $mrc === CURLM_CALL_MULTI_PERFORM));

        foreach ($handles as $key => $ch) {
            if (!isset($results[$key])) {
                $results[$key] = [
                    'ok' => false,
                    'http_code' => 0,
                    'empty_payload' => false,
                    'ms' => (int)round((microtime(true) - $startTime) * 1000),
                    'data' => null,
                    'aborted' => true,
                ];
            }
            curl_multi_remove_handle($mh, $ch);
            curl_close($ch);
        }
        curl_multi_close($mh);

        return $results;
    }
}

if (!function_exists('sports_extract_scorecard')) {
    function sports_extract_scorecard(array $raw, array $matchMeta = []): ?array {
        $src = $raw;
        foreach (['scorecard', 'scoreCard', 'score', 'scoreboard', 'data'] as $k) {
            if (isset($src[$k]) && is_array($src[$k]) && !empty($src[$k])) {
                if (
                    isset($src[$k]['score']) || isset($src[$k]['t1']) || isset($src[$k]['spnnation1']) ||
                    isset($src[$k]['innings']) || isset($src[$k]['team1']) || isset($src[$k]['score1']) ||
                    isset($src[$k]['hs']) || isset($src[$k]['as']) || isset($src[$k]['sets']) || isset($src[$k]['ft'])
                ) {
                    $src = $src[$k];
                    break;
                }
            }
        }
        if (isset($src['score']) && is_array($src['score']) && !empty($src['score'])) {
            $src = $src['score'];
        }

        $shortCode = static function(string $name): string {
            $words = preg_split('/\s+/', trim($name));
            if (!$words) return '';
            if (count($words) === 1) return strtoupper(substr($words[0], 0, 3));
            $code = '';
            foreach ($words as $w) {
                if ($w !== '' && ctype_alnum($w[0])) $code .= strtoupper($w[0]);
                if (strlen($code) >= 3) break;
            }
            return $code;
        };

        $t1Name = trim((string)($src['spnnation1'] ?? $src['team1'] ?? $src['t1_name'] ?? $matchMeta['home_name'] ?? ''));
        $t2Name = trim((string)($src['spnnation2'] ?? $src['team2'] ?? $src['t2_name'] ?? $matchMeta['away_name'] ?? ''));

        $t1Score = '';
        $t2Score = '';
        $t1Overs = trim((string)($src['over1'] ?? $src['t1_overs'] ?? $src['home_overs'] ?? ''));
        $t2Overs = trim((string)($src['over2'] ?? $src['t2_overs'] ?? $src['away_overs'] ?? ''));

        $parseSide = static function($val): array {
            if ($val === null || $val === '') return ['', ''];
            if (is_array($val)) {
                if (isset($val[0]) && is_array($val[0])) {
                    $last = end($val);
                    $r = $last['r'] ?? $last['runs'] ?? $last['score'] ?? $last['g'] ?? $last['pts'] ?? '';
                    $w = $last['w'] ?? $last['wickets'] ?? null;
                    $o = (string)($last['o'] ?? $last['overs'] ?? '');
                    if ($r !== '') {
                        return [(string)$r . ($w !== null && $w !== '' ? '/' . $w : ''), $o];
                    }
                } else {
                    $r = $val['r'] ?? $val['runs'] ?? $val['score'] ?? $val['goals'] ?? $val['sets'] ?? $val['pts'] ?? '';
                    $w = $val['w'] ?? $val['wickets'] ?? null;
                    $o = (string)($val['o'] ?? $val['overs'] ?? '');
                    if ($r !== '') {
                        return [(string)$r . ($w !== null && $w !== '' ? '/' . $w : ''), $o];
                    }
                }
                return ['', ''];
            }
            return [trim((string)$val), ''];
        };

        foreach (['score1', 't1_score', 'home_score', 'spnscore1', 'goals_home', 'hs', 'home', 't1'] as $k) {
            if (isset($src[$k]) && $src[$k] !== '' && $src[$k] !== '-') {
                [$sc, $ov] = $parseSide($src[$k]);
                if ($sc !== '') {
                    $t1Score = $sc;
                    if ($t1Overs === '' && $ov !== '') $t1Overs = $ov;
                    break;
                }
            }
        }
        foreach (['score2', 't2_score', 'away_score', 'spnscore2', 'goals_away', 'as', 'away', 't2'] as $k) {
            if (isset($src[$k]) && $src[$k] !== '' && $src[$k] !== '-') {
                [$sc, $ov] = $parseSide($src[$k]);
                if ($sc !== '') {
                    $t2Score = $sc;
                    if ($t2Overs === '' && $ov !== '') $t2Overs = $ov;
                    break;
                }
            }
        }

        // Football "ft": "2-1" or "2:1"
        $ftStr = trim((string)($src['ft'] ?? $src['final_score'] ?? ''));
        if ($t1Score === '' && $t2Score === '' && preg_match('/^(\d+)\s*[-:]\s*(\d+)$/', $ftStr, $fm)) {
            $t1Score = $fm[1];
            $t2Score = $fm[2];
        }

        // Tennis sets array
        $tennisTotalGames = null;
        $setsMeta = [];
        if (isset($src['sets']) && is_array($src['sets']) && !empty($src['sets'])) {
            $hSets = 0; $aSets = 0; $totGames = 0; $setTexts = [];
            foreach ($src['sets'] as $st) {
                if (!is_array($st)) continue;
                $hs = (int)($st['h'] ?? $st['home'] ?? $st['p1'] ?? 0);
                $as = (int)($st['a'] ?? $st['away'] ?? $st['p2'] ?? 0);
                if ($hs > $as) $hSets++;
                elseif ($as > $hs) $aSets++;
                $totGames += ($hs + $as);
                $setTexts[] = "{$hs}-{$as}";
            }
            if ($setTexts) {
                $tennisTotalGames = $totGames;
                $setsMeta = $setTexts;
                if ($t1Score === '') $t1Score = (string)$hSets . ' (' . implode(', ', $setTexts) . ')';
                if ($t2Score === '') $t2Score = (string)$aSets;
            }
        }

        if ($t1Score !== '' && $t1Overs === '' && preg_match('/^([0-9\/\-]+)\s*\(([^)]+)\)/', $t1Score, $m)) {
            $t1Score = trim($m[1]);
            $t1Overs = trim($m[2]);
        }
        if ($t2Score !== '' && $t2Overs === '' && preg_match('/^([0-9\/\-]+)\s*\(([^)]+)\)/', $t2Score, $m)) {
            $t2Score = trim($m[1]);
            $t2Overs = trim($m[2]);
        }

        $needMsg = trim((string)($src['spnmessage'] ?? $src['message'] ?? $src['msg'] ?? $src['m'] ?? $src['status_msg'] ?? $src['need_text'] ?? ''));

        if ($t1Score === '' && $t2Score === '' && empty($src['balls']) && empty($src['overs']) && $needMsg === '') {
            return null;
        }

        $target = trim((string)($src['target'] ?? $src['target_runs'] ?? ''));
        $crr = trim((string)($src['crr'] ?? $src['spnrunrate1'] ?? $src['spnrunrate2'] ?? $src['run_rate'] ?? ''));
        $rrr = trim((string)($src['rrr'] ?? $src['spnreqrate1'] ?? $src['spnreqrate2'] ?? $src['req_run_rate'] ?? ''));
        $ballEvent = trim((string)($src['spnballrunningstatus'] ?? $src['ball_event'] ?? $src['last_ball'] ?? $src['current_ball'] ?? ''));
        $format = trim((string)($src['format'] ?? $src['match_type'] ?? 'T20'));
        $venue = trim((string)($src['venue'] ?? $matchMeta['venue'] ?? $matchMeta['competition'] ?? ''));
        $battingTeam = (int)($src['activenation1'] ?? 0) === 1 ? 1 : ((int)($src['activenation2'] ?? 0) === 1 ? 2 : ($t2Score !== '' ? 2 : 1));

        $overs = [];
        if (isset($src['overs']) && is_array($src['overs'])) {
            $overs = $src['overs'];
        } elseif (isset($src['balls']) && is_array($src['balls'])) {
            $cleanBalls = array_values(array_filter(array_map(static function($b) {
                return trim((string)$b);
            }, $src['balls']), static function($b) { return $b !== ''; }));
            if ($cleanBalls) {
                $overs[] = [
                    'over' => $battingTeam === 2 ? $t2Overs : $t1Overs,
                    'runs' => null,
                    'balls' => $cleanBalls,
                ];
            }
        }

        if ($ballEvent === '' && !empty($overs[0]['balls'])) {
            $ballEvent = (string)end($overs[0]['balls']);
        }

        return [
            'format' => $format,
            'venue' => $venue,
            'target' => $target,
            'need_text' => $needMsg,
            'ball_event' => strtoupper($ballEvent),
            'batting_team' => $battingTeam,
            'crr' => preg_replace('/^CRR\s*:?\s*/i', '', $crr),
            'rrr' => preg_replace('/^RRR\s*:?\s*/i', '', $rrr),
            'tennis_total_games' => $tennisTotalGames,
            'sets_list' => $setsMeta,
            't1' => [
                'name' => $t1Name,
                'code' => trim((string)($src['t1_code'] ?? $shortCode($t1Name))),
                'logo' => trim((string)($src['t1_logo'] ?? $src['team1_logo'] ?? '')),
                'score' => $t1Score,
                'overs' => $t1Overs,
            ],
            't2' => [
                'name' => $t2Name,
                'code' => trim((string)($src['t2_code'] ?? $shortCode($t2Name))),
                'logo' => trim((string)($src['t2_logo'] ?? $src['team2_logo'] ?? '')),
                'score' => $t2Score,
                'overs' => $t2Overs,
            ],
            'overs' => $overs,
        ];
    }
}

if (!function_exists('sports_ensure_result_archive_table')) {
    function sports_ensure_result_archive_table(PDO $pdo): void {
        static $done = false;
        if ($done) return;
        try {
            $pdo->exec("
                CREATE TABLE IF NOT EXISTS sports_result_archive (
                    event_id VARCHAR(80) PRIMARY KEY,
                    event_name VARCHAR(255) NOT NULL DEFAULT '',
                    fingerprint VARCHAR(255) NOT NULL DEFAULT '',
                    sport_slug VARCHAR(40) NOT NULL DEFAULT 'cricket',
                    etid INT NOT NULL DEFAULT 4,
                    allpanel_gmid VARCHAR(80) NOT NULL DEFAULT '',
                    market_ids_json TEXT NULL,
                    winner_name VARCHAR(255) NOT NULL DEFAULT '',
                    match_status VARCHAR(64) NOT NULL DEFAULT '',
                    scorecard_json MEDIUMTEXT NULL,
                    markets_result_json MEDIUMTEXT NULL,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    KEY idx_fp (fingerprint)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
            ");
            $done = true;
        } catch (Throwable $e) {
            error_log('[Sports ResultArchive] ' . $e->getMessage());
        }
    }
}

if (!function_exists('sports_archive_event_snapshot')) {
    function sports_archive_event_snapshot(PDO $pdo, array $snap): void {
        $evId = trim((string)($snap['event_id'] ?? ''));
        if ($evId === '') return;
        try {
            sports_ensure_result_archive_table($pdo);
            $stmt = $pdo->prepare("
                INSERT INTO sports_result_archive
                    (event_id, event_name, fingerprint, sport_slug, etid, allpanel_gmid, market_ids_json, winner_name, match_status, scorecard_json, markets_result_json)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    event_name = IF(VALUES(event_name) <> '', VALUES(event_name), event_name),
                    fingerprint = IF(VALUES(fingerprint) <> '', VALUES(fingerprint), fingerprint),
                    sport_slug = IF(VALUES(sport_slug) <> '', VALUES(sport_slug), sport_slug),
                    etid = IF(VALUES(etid) > 0, VALUES(etid), etid),
                    allpanel_gmid = IF(VALUES(allpanel_gmid) <> '', VALUES(allpanel_gmid), allpanel_gmid),
                    market_ids_json = IF(VALUES(market_ids_json) IS NOT NULL AND VALUES(market_ids_json) <> '' AND VALUES(market_ids_json) <> '[]', VALUES(market_ids_json), market_ids_json),
                    winner_name = IF(VALUES(winner_name) <> '', VALUES(winner_name), winner_name),
                    match_status = IF(VALUES(match_status) <> '', VALUES(match_status), match_status),
                    scorecard_json = IF(VALUES(scorecard_json) IS NOT NULL AND VALUES(scorecard_json) <> '', VALUES(scorecard_json), scorecard_json),
                    markets_result_json = IF(VALUES(markets_result_json) IS NOT NULL AND VALUES(markets_result_json) <> '' AND VALUES(markets_result_json) <> '[]', VALUES(markets_result_json), markets_result_json)
            ");
            $stmt->execute([
                $evId,
                (string)($snap['event_name'] ?? ''),
                (string)($snap['fingerprint'] ?? ''),
                (string)($snap['sport_slug'] ?? 'cricket'),
                (int)($snap['etid'] ?? 4),
                (string)($snap['allpanel_gmid'] ?? ''),
                (string)($snap['market_ids_json'] ?? '[]'),
                (string)($snap['winner_name'] ?? ''),
                (string)($snap['match_status'] ?? ''),
                (string)($snap['scorecard_json'] ?? ''),
                (string)($snap['markets_result_json'] ?? '[]'),
            ]);
        } catch (Throwable $e) {
            error_log('[Sports ArchiveSave] ' . $e->getMessage());
        }
    }
}

if (!function_exists('sports_race_live_event')) {
    function sports_race_live_event(string $eventId, int $etid = 4, array $savedMarketIds = []): array {
        $cacheKey = 'live_ev_v2_' . $eventId . '_' . $etid;
        $cached = sports_live_cache_get($cacheKey, 0.35);
        if ($cached !== null) {
            $cached['_cached'] = true;
            return $cached;
        }

        $alt = sports_alt_id_map_get($eventId);
        $apGmid = !empty($alt['allpanel_gmid']) ? (string)$alt['allpanel_gmid'] : $eventId;
        $encId = rawurlencode($eventId);
        $encAp = rawurlencode($apGmid);

        $lock = sports_provider_lock_get($eventId);
        $lockedProv = $lock ? (string)$lock['provider'] : '';

        $apReq = [
            'url' => "https://www.allpanelexch8.com/api/sports?endpoint=%2FgamedataPrivate&gmid={$encAp}&etid={$etid}",
            'method' => 'GET',
            'headers' => [
                'Origin: https://www.allpanelexch8.com',
                'Referer: https://www.allpanelexch8.com/',
            ],
            'timeout_ms' => 1050,
            'connect_ms' => 500,
            'fast_win' => true,
            'validator' => static function($d): bool {
                return isset($d['data']['data']) && is_array($d['data']['data']) && count($d['data']['data']) > 0;
            },
        ];

        $oexchReq = [
            'url' => 'https://api.oexch99.com/delaymarkets/events/detail/' . $encId,
            'method' => 'GET',
            'timeout_ms' => 1050,
            'connect_ms' => 500,
            'fast_win' => false,
        ];

        $bfMarketIds = array_values(array_filter(array_map('strval', $savedMarketIds), static function($mid) {
            return $mid !== '' && strpos($mid, '1.') === 0;
        }));
        $ocricReq = null;
        if ($bfMarketIds) {
            $parts = [];
            foreach (array_slice($bfMarketIds, 0, 10) as $mid) {
                $parts[] = 'market_ids%5B%5D=' . rawurlencode($mid);
            }
            $ocricReq = [
                'url' => 'https://odd.ocric99.com/ws/getMarketDataNew',
                'method' => 'POST',
                'body' => implode('&', $parts),
                'headers' => [
                    'Origin: https://reddybook.store',
                    'Referer: https://reddybook.store/',
                    'Content-Type: application/x-www-form-urlencoded',
                ],
                'timeout_ms' => 950,
                'connect_ms' => 450,
                'fast_win' => false,
                'validator' => static function($d): bool {
                    if (!is_array($d)) return false;
                    foreach ($d as $item) {
                        if (is_array($item) && !empty($item['runners'])) return true;
                    }
                    return false;
                },
            ];
        }

        if ($lockedProv === 'allpanel') {
            $requests = ['allpanel' => $apReq];
            if ($ocricReq) $requests['ocric99'] = $ocricReq;
            $race = sports_multi_race($requests, 1050, 280);
            if (!empty($race['allpanel']['ok'])) {
                sports_provider_lock_set($eventId, 'allpanel', 0);
                $race['_primary'] = 'allpanel';
                sports_live_cache_set($cacheKey, $race);
                return $race;
            }
            $apCode = (int)($race['allpanel']['http_code'] ?? 0);
            if (!empty($race['allpanel']['empty_payload']) || $apCode === 404 || $apCode === 410) {
                $race['_primary'] = 'none';
                $race['_completed'] = true;
                return $race;
            }
            $fb = sports_multi_race(['oexch99' => $oexchReq], 950, 100);
            if (!empty($fb['oexch99']['ok'])) {
                $race['oexch99'] = $fb['oexch99'];
                $race['_primary'] = 'oexch99';
                sports_provider_lock_set($eventId, 'oexch99', 0);
                sports_live_cache_set($cacheKey, $race);
                return $race;
            }
            $race['_primary'] = 'none';
            return $race;
        }

        if ($lockedProv === 'oexch99') {
            $requests = ['oexch99' => $oexchReq];
            if ($ocricReq) $requests['ocric99'] = $ocricReq;
            $race = sports_multi_race($requests, 1050, 450);
            if (!empty($race['oexch99']['ok'])) {
                $race['_primary'] = 'oexch99';
                sports_live_cache_set($cacheKey, $race);
                return $race;
            }
            sports_provider_lock_clear($eventId);
        }

        $requests = ['allpanel' => $apReq, 'oexch99' => $oexchReq];
        if ($ocricReq) $requests['ocric99'] = $ocricReq;
        $race = sports_multi_race($requests, 1200, 320);

        $apOk = !empty($race['allpanel']['ok']);
        $oxOk = !empty($race['oexch99']['ok']);
        $apGone = !empty($race['allpanel']['empty_payload']) || (int)($race['allpanel']['http_code'] ?? 0) === 404;

        if ($apOk) {
            sports_provider_lock_set($eventId, 'allpanel', 0);
            $race['_primary'] = 'allpanel';
            sports_live_cache_set($cacheKey, $race);
        } elseif ($apGone && !empty($alt['allpanel_gmid'])) {
            $race['_primary'] = 'none';
            $race['_completed'] = true;
        } elseif ($oxOk) {
            sports_provider_lock_set($eventId, 'oexch99', 0);
            $race['_primary'] = 'oexch99';
            sports_live_cache_set($cacheKey, $race);
        } else {
            $race['_primary'] = 'none';
        }

        return $race;
    }
}

if (!function_exists('sports_delete_matches')) {
    function sports_delete_matches(PDO $pdo, array $matchIds): int {
        $ids = array_values(array_unique(array_filter(array_map('intval', $matchIds), static function($id) {
            return $id > 0;
        })));
        if (!$ids) return 0;
        $ph = implode(',', array_fill(0, count($ids), '?'));

        try {
            $evStmt = $pdo->prepare(
                "SELECT DISTINCT provider_event_id FROM sports_provider_events WHERE match_id IN ($ph)
                 UNION
                 SELECT DISTINCT source_event_id FROM sports_matches WHERE id IN ($ph) AND source_event_id IS NOT NULL AND source_event_id <> ''"
            );
            $evStmt->execute(array_merge($ids, $ids));
            $evIds = $evStmt->fetchAll(PDO::FETCH_COLUMN);
            if ($evIds && function_exists('sports_clear_match_caches')) {
                sports_clear_match_caches($evIds);
            }
        } catch (Throwable $cacheErr) {
            error_log('[Sports CacheClear] ' . $cacheErr->getMessage());
        }

        $pdo->prepare("DELETE FROM sports_provider_markets WHERE match_id IN ($ph)")->execute($ids);
        $pdo->prepare("DELETE FROM sports_provider_events WHERE match_id IN ($ph)")->execute($ids);
        try {
            $delStmt = $pdo->prepare("DELETE FROM sports_matches WHERE id IN ($ph)");
            $delStmt->execute($ids);
            return $delStmt->rowCount();
        } catch (Throwable $fkErr) {
            $pdo->prepare("UPDATE sports_matches SET status='completed' WHERE id IN ($ph)")->execute($ids);
            error_log('[Sports Sync Delete Fallback] ' . $fkErr->getMessage());
            return count($ids);
        }
    }
}

if (!function_exists('sports_sync_run')) {
    function sports_sync_run(PDO $pdo): array {
        sports_ensure_result_archive_table($pdo);

        // Strictly ONLY Real Cricket (4), Football (1), Tennis (2), Horse Racing (7) fetched together
        $sportIds = [4, 1, 2, 7];
        $syncReqs = [
            'oexch99' => [
                'url' => 'https://api.oexch99.com/delaymarkets/markets/current',
                'timeout_ms' => 5500,
                'connect_ms' => 2500,
            ],
        ];
        foreach ($sportIds as $sid) {
            $syncReqs['ap_' . $sid] = [
                'url' => "https://www.allpanelexch8.com/api/sports?endpoint=%2FhighlighthomePrivate&etid={$sid}",
                'headers' => ['Origin: https://www.allpanelexch8.com', 'Referer: https://www.allpanelexch8.com/'],
                'timeout_ms' => 3500,
                'connect_ms' => 1500,
            ];
        }

        $feeds = sports_multi_race($syncReqs, 5500, 5500);

        $rows = [];
        if (!empty($feeds['oexch99']['ok']) && is_array($feeds['oexch99']['data'])) {
            $payload = $feeds['oexch99']['data'];
            $rows = $payload;
            foreach (['data', 'markets', 'results', 'items', 'catalogues'] as $key) {
                if (isset($payload[$key]) && is_array($payload[$key])) {
                    $rows = $payload[$key];
                    break;
                }
            }
        }

        $apByFp = [];
        $apSportCount = [];
        foreach ($sportIds as $sid) {
            $apSportCount[$sid] = 0;
            $apFeed = $feeds['ap_' . $sid] ?? [];
            if (empty($apFeed['ok'])) continue;
            $apData = $apFeed['data']['data']['data'] ?? [];
            $list = array_merge(
                is_array($apData['t1'] ?? null) ? $apData['t1'] : [],
                is_array($apData['t2'] ?? null) ? $apData['t2'] : []
            );
            foreach ($list as $item) {
                if (!is_array($item)) continue;
                $itemSt = strtoupper(trim((string)($item['status'] ?? $item['gstatus'] ?? $item['mstatus'] ?? '')));
                $evId = trim((string)($item['gmid'] ?? $item['eventId'] ?? $item['gameId'] ?? ''));
                $evName = trim((string)($item['ename'] ?? $item['eventName'] ?? ''));
                $compName = trim((string)($item['cname'] ?? $item['seriesName'] ?? ''));
                if ($evId === '' || $evName === '') continue;

                if (sports_is_virtual_event([
                    'isVirtual' => $item['isVirtual'] ?? ($item['virtual'] ?? false),
                    'gtype' => $item['gtype'] ?? ($item['mtype'] ?? ''),
                    'competition_name' => $compName,
                    'event_name' => $evName,
                ])) {
                    continue;
                }

                if ($itemSt !== '' && in_array($itemSt, sports_terminal_statuses(), true)) {
                    $apWin = sports_extract_winner_from_market($item);
                    if ($apWin !== '') {
                        sports_archive_event_snapshot($pdo, [
                            'event_id' => $evId,
                            'event_name' => $evName,
                            'fingerprint' => sports_match_fingerprint($sid, $evName),
                            'sport_slug' => ($sid === 1 ? 'football' : ($sid === 2 ? 'tennis' : ($sid === 7 ? 'horse-racing' : 'cricket'))),
                            'etid' => $sid,
                            'allpanel_gmid' => $evId,
                            'winner_name' => $apWin,
                            'match_status' => $itemSt,
                        ]);
                    }
                    continue;
                }

                $apSportCount[$sid]++;
                $fp = sports_match_fingerprint($sid, $evName);
                if (!isset($apByFp[$fp])) {
                    $apByFp[$fp] = [
                        'event_id' => $evId,
                        'market_id' => trim((string)($item['mid'] ?? ('1.' . $evId))),
                        'event_name' => $evName,
                        'competition' => $compName,
                        'etid' => $sid,
                        'start_time' => (string)($item['stime'] ?? $item['eventTime'] ?? ''),
                        'in_play' => !empty($item['iplay']) || !empty($item['inPlay']) || !empty($item['isPlayFlag']),
                        'has_tv' => !empty($item['tv']),
                        'sections' => is_array($item['section'] ?? null) ? $item['section'] : [],
                        'raw' => $item,
                    ];
                }
            }
        }

        if (!$rows && !$apByFp) {
            throw new RuntimeException('All feeds returned no market records; existing data was not changed.');
        }

        $altFile = sys_get_temp_dir() . '/sp_alt_id_map.json';
        $prevAltMap = is_file($altFile) ? (json_decode((string)@file_get_contents($altFile), true) ?: []) : [];
        if (!is_array($prevAltMap)) $prevAltMap = [];

        $closedStatuses = sports_terminal_statuses();
        $nowTs = time();

        $upsertMatch = $pdo->prepare('INSERT INTO sports_matches (sport_id,competition_id,home_name,away_name,start_time,status,venue,source_event_id) VALUES (?,?,?,?,?,?,?,?)');
        $updateMatch = $pdo->prepare('UPDATE sports_matches SET sport_id=?,competition_id=?,home_name=?,away_name=?,start_time=?,status=?,venue=?,source_event_id=? WHERE id=?');
        $findMatch = $pdo->prepare('SELECT match_id FROM sports_provider_events WHERE provider_event_id=? LIMIT 1');
        $findMatchBySource = $pdo->prepare('SELECT id FROM sports_matches WHERE source_event_id=? LIMIT 1');
        $mapMatch = $pdo->prepare('INSERT INTO sports_provider_events(provider_event_id,match_id,provider_event_name) VALUES(?,?,?) ON DUPLICATE KEY UPDATE match_id=VALUES(match_id),provider_event_name=VALUES(provider_event_name)');
        $findSport = $pdo->prepare('SELECT id FROM sports WHERE slug=? LIMIT 1');
        $addSport = $pdo->prepare('INSERT INTO sports(name,slug,sort_order) VALUES(?,?,?)');
        $findComp = $pdo->prepare('SELECT id FROM sports_competitions WHERE sport_id=? AND name=? LIMIT 1');
        $addComp = $pdo->prepare('INSERT INTO sports_competitions(sport_id,name,season) VALUES(?,?,?)');
        $upsertMarket = $pdo->prepare('INSERT INTO sports_provider_markets (provider_market_id,match_id,market_type,betting_type,market_name,provider,status,in_play,bet_lock,market_time,sort_priority,runners_json,odds_raw,metadata_json,raw_json,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1) ON DUPLICATE KEY UPDATE match_id=VALUES(match_id),market_type=VALUES(market_type),betting_type=VALUES(betting_type),market_name=VALUES(market_name),provider=VALUES(provider),status=VALUES(status),in_play=VALUES(in_play),bet_lock=VALUES(bet_lock),market_time=VALUES(market_time),sort_priority=VALUES(sort_priority),runners_json=VALUES(runners_json),odds_raw=VALUES(odds_raw),metadata_json=VALUES(metadata_json),raw_json=VALUES(raw_json),is_active=1');

        $seenEvents = [];
        $seenFingerprints = [];
        $seenMatchIds = [];
        $eventMatchIdMap = [];
        $closedMainEvents = [];
        $seenMarkets = [];
        $eventInPlay = [];
        $altIdMap = [];
        $archiveQueue = [];
        $inserted = 0;
        $updated = 0;
        $deleted = 0;

        $pdo->beginTransaction();
        try {
            $pdo->exec("UPDATE sports SET is_active = CASE WHEN slug IN ('cricket','football','tennis','horse-racing') THEN 1 ELSE 0 END");

            foreach ($rows as $row) {
                if (!is_array($row)) continue;
                $event = $row['event'] ?? ($row['catalogue']['event'] ?? []);
                $eventType = $row['eventType'] ?? ($row['catalogue']['eventType'] ?? []);
                $competition = $row['competition'] ?? ($row['catalogue']['competition'] ?? []);
                $market = $row['catalogue'] ?? $row['market'] ?? (isset($row['marketId']) ? $row : []);
                if (!is_array($market) || !$market) continue;

                if (!empty($row['isArchived']) || (isset($row['isActive']) && $row['isActive'] === false)) continue;

                $eventId = trim((string)($event['id'] ?? $row['eventId'] ?? $market['eventId'] ?? ''));
                $eventName = trim((string)($event['name'] ?? $row['eventName'] ?? $market['eventName'] ?? ''));
                if ($eventId === '' || $eventName === '') continue;

                $rawSport = (string)($eventType['name'] ?? $row['sportName'] ?? $row['sport'] ?? '');
                $rawSportId = trim((string)($eventType['id'] ?? $row['eventTypeId'] ?? $market['eventTypeId'] ?? $row['sportId'] ?? ''));
                $compName = trim((string)($competition['name'] ?? $row['competitionName'] ?? ''));
                $marketName = (string)($market['marketName'] ?? $row['marketName'] ?? 'Market');
                $marketType = (string)($market['marketType'] ?? $row['marketType'] ?? 'OTHER');
                $marketId = trim((string)($market['marketId'] ?? $market['id'] ?? $row['marketId'] ?? ''));

                if (sports_is_virtual_event([
                    'isVirtual' => $row['isVirtual'] ?? ($event['isVirtual'] ?? ($market['isVirtual'] ?? ($row['virtual'] ?? false))),
                    'isSimulated' => $row['isSimulated'] ?? ($event['isSimulated'] ?? false),
                    'sport_name' => $rawSport,
                    'competition_name' => $compName,
                    'event_name' => $eventName,
                    'market_name' => $marketName,
                ])) {
                    continue;
                }

                $sportMeta = sports_resolve_sport_meta($rawSport, $rawSportId);
                if (!$sportMeta) continue;

                $meta = $row['metadata'] ?? ($market['metadata'] ?? []);
                if (!is_array($meta)) $meta = [];
                $book = '';
                foreach ([$meta['book'] ?? '', $row['book'] ?? '', $market['book'] ?? '', $market['metadata']['book'] ?? ''] as $cand) {
                    $candStr = trim((string)$cand);
                    if ($candStr !== '') { $book = $candStr; break; }
                }

                $bh = sports_parse_book_status($book);
                $bookStatus = $bh['status'];
                $bookInPlay = $bh['in_play'];
                $bookHasPrice = $bh['has_price'];

                $parts = preg_split('/\s+v(?:s)?\.?\s+/i', $eventName, 2);
                $home = trim($parts[0] ?? $eventName);
                $away = trim($parts[1] ?? '');

                $isOutrightRow = ($sportMeta['etid'] !== 7) && ($away === '' || stripos($marketType, 'OUTRIGHT') !== false || stripos($marketType, 'WINNER') !== false);
                $rawMktStatus = strtoupper(trim((string)($market['status'] ?? $row['status'] ?? '')));
                $isMainMarket = ($isOutrightRow || strtoupper($marketType) === 'MATCH_ODDS' || strtoupper($marketName) === 'MATCH ODDS' || strtoupper($marketName) === 'WIN MARKET');
                $fp = sports_match_fingerprint($sportMeta['etid'], $eventName);

                $winFound = sports_extract_winner_from_market($market, $book);
                if (!isset($archiveQueue[$eventId])) {
                    $archiveQueue[$eventId] = [
                        'event_id' => $eventId,
                        'event_name' => $eventName,
                        'fingerprint' => $fp,
                        'sport_slug' => $sportMeta['slug'],
                        'etid' => $sportMeta['etid'],
                        'allpanel_gmid' => (string)($apByFp[$fp]['event_id'] ?? ($prevAltMap[$eventId]['allpanel_gmid'] ?? '')),
                        'market_ids' => [],
                        'winner_name' => '',
                        'match_status' => '',
                        'scorecard' => sports_extract_scorecard($row, ['home_name' => $home, 'away_name' => $away]),
                        'markets_result' => [],
                    ];
                }
                if ($marketId !== '') $archiveQueue[$eventId]['market_ids'][$marketId] = true;
                if ($winFound !== '') {
                    if ($isMainMarket || $archiveQueue[$eventId]['winner_name'] === '') {
                        $archiveQueue[$eventId]['winner_name'] = $winFound;
                    }
                    $archiveQueue[$eventId]['markets_result'][] = [
                        'market_id' => $marketId,
                        'market_name' => $marketName,
                        'status' => $bookStatus ?: $rawMktStatus,
                        'winner' => $winFound,
                    ];
                }

                if (in_array($rawMktStatus, $closedStatuses, true) || in_array($bookStatus, $closedStatuses, true)) {
                    $archiveQueue[$eventId]['match_status'] = $bookStatus ?: $rawMktStatus;
                    if ($isMainMarket) $closedMainEvents[$eventId] = true;
                    continue;
                }
                if (isset($closedMainEvents[$eventId])) continue;

                if (isset($seenFingerprints[$fp]) && $seenFingerprints[$fp] !== $eventId) continue;

                $openDate = (string)($event['openDate'] ?? $market['marketTime'] ?? '');
                try {
                    $dtObj = new DateTimeImmutable($openDate ?: 'now');
                    $dt = $dtObj->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
                    $startTs = $dtObj->getTimestamp();
                } catch (Throwable $e) {
                    $dt = gmdate('Y-m-d H:i:s');
                    $startTs = $nowTs;
                }

                $maxAgeSec = $isOutrightRow ? (120 * 86400) : ($sportMeta['etid'] === 7 ? 7200 : (5 * 86400));
                if ($startTs < ($nowTs - $maxAgeSec)) {
                    continue;
                }

                $inPlay = !empty($market['inPlay']) || !empty($row['inPlay']) || $bookInPlay || !empty($apByFp[$fp]['in_play']);

                if (!$isOutrightRow && $sportMeta['etid'] !== 7 && !isset($apByFp[$fp])) {
                    if (($apSportCount[$sportMeta['etid']] ?? 0) > 0 && isset($prevAltMap[$eventId]) && ($inPlay || $startTs <= ($nowTs - 900))) {
                        continue;
                    }
                    if ($inPlay && $startTs < ($nowTs - 4 * 3600) && (!$bookHasPrice || $bookStatus === 'SUSPENDED')) {
                        continue;
                    }
                }

                $seenFingerprints[$fp] = $eventId;
                if (isset($apByFp[$fp])) {
                    $altIdMap[$eventId] = ['allpanel_gmid' => $apByFp[$fp]['event_id'], 'etid' => $sportMeta['etid']];
                    $archiveQueue[$eventId]['allpanel_gmid'] = $apByFp[$fp]['event_id'];
                }

                if ($marketId === '') continue;

                $findSport->execute([$sportMeta['slug']]);
                $sportId = (int)$findSport->fetchColumn();
                if (!$sportId) {
                    $addSport->execute([$sportMeta['name'], $sportMeta['slug'], $sportMeta['sort']]);
                    $sportId = (int)$pdo->lastInsertId();
                }

                $compId = null;
                if ($compName !== '') {
                    $findComp->execute([$sportId, $compName]);
                    $compId = (int)$findComp->fetchColumn();
                    if (!$compId) {
                        $addComp->execute([$sportId, $compName, '']);
                        $compId = (int)$pdo->lastInsertId();
                    }
                }

                $eventInPlay[$eventId] = ($eventInPlay[$eventId] ?? false) || $inPlay;
                $status = $eventInPlay[$eventId] ? 'live' : 'upcoming';
                $venue = (string)($event['venue'] ?? '');

                $findMatch->execute([$eventId]);
                $matchId = (int)$findMatch->fetchColumn();
                if (!$matchId) {
                    $findMatchBySource->execute([$eventId]);
                    $matchId = (int)$findMatchBySource->fetchColumn();
                }
                if ($matchId) {
                    $updateMatch->execute([$sportId, $compId ?: null, $home, $away, $dt, $status, $venue, $eventId, $matchId]);
                    $updated++;
                } else {
                    $upsertMatch->execute([$sportId, $compId ?: null, $home, $away, $dt, $status, $venue, $eventId]);
                    $matchId = (int)$pdo->lastInsertId();
                    $inserted++;
                }
                $mapMatch->execute([$eventId, $matchId, $eventName]);

                $seenEvents[$eventId] = true;
                $seenMatchIds[$matchId] = true;
                $eventMatchIdMap[$eventId] = $matchId;
                $seenMarkets[$marketId] = true;

                $condition = $market['marketCondition'] ?? [];
                $runners = $market['runners'] ?? ($row['runners'] ?? []);
                $effectiveStatus = $bookStatus !== '' ? $bookStatus : (string)($market['status'] ?? $row['status'] ?? 'OPEN');

                $upsertMarket->execute([
                    $marketId,
                    $matchId,
                    $marketType,
                    (string)($market['bettingType'] ?? $row['bettingType'] ?? ''),
                    $marketName,
                    (string)($market['provider'] ?? $row['provider'] ?? 'oexch99'),
                    $effectiveStatus,
                    $inPlay ? 1 : 0,
                    !empty($condition['betLock']) ? 1 : 0,
                    (string)($market['marketTime'] ?? ''),
                    (int)($market['sortPriority'] ?? 0),
                    json_encode($runners, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
                    $book,
                    json_encode($meta, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
                    json_encode($row, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
                ]);
            }

            foreach ($closedMainEvents as $closedEvId => $_) {
                if (isset($seenEvents[$closedEvId])) {
                    unset($seenEvents[$closedEvId]);
                    $closedMid = $eventMatchIdMap[$closedEvId] ?? 0;
                    if ($closedMid > 0) unset($seenMatchIds[$closedMid]);
                }
            }

            foreach ($apByFp as $fp => $fm) {
                $evId = $fm['event_id'];
                if (isset($seenEvents[$evId]) || isset($seenFingerprints[$fp]) || isset($closedMainEvents[$evId])) continue;
                $seenFingerprints[$fp] = $evId;
                $altIdMap[$evId] = ['allpanel_gmid' => $evId, 'etid' => $fm['etid']];

                $sportMeta = sports_resolve_sport_meta('', (string)$fm['etid']);
                if (!$sportMeta) continue;

                $findSport->execute([$sportMeta['slug']]);
                $sportId = (int)$findSport->fetchColumn();
                if (!$sportId) {
                    $addSport->execute([$sportMeta['name'], $sportMeta['slug'], $sportMeta['sort']]);
                    $sportId = (int)$pdo->lastInsertId();
                }

                $compId = null;
                if ($fm['competition'] !== '') {
                    $findComp->execute([$sportId, $fm['competition']]);
                    $compId = (int)$findComp->fetchColumn();
                    if (!$compId) {
                        $addComp->execute([$sportId, $fm['competition'], '']);
                        $compId = (int)$pdo->lastInsertId();
                    }
                }

                $parts = preg_split('/\s+v(?:s)?\.?\s+/i', $fm['event_name'], 2);
                $home = trim($parts[0] ?? $fm['event_name']);
                $away = trim($parts[1] ?? '');

                try {
                    $dt = (new DateTimeImmutable($fm['start_time'] ?: 'now'))->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
                } catch (Throwable $e) {
                    $dt = gmdate('Y-m-d H:i:s');
                }

                $status = $fm['in_play'] ? 'live' : 'upcoming';

                $findMatch->execute([$evId]);
                $matchId = (int)$findMatch->fetchColumn();
                if (!$matchId) {
                    $findMatchBySource->execute([$evId]);
                    $matchId = (int)$findMatchBySource->fetchColumn();
                }
                if ($matchId) {
                    $updateMatch->execute([$sportId, $compId ?: null, $home, $away, $dt, $status, '', $evId, $matchId]);
                    $updated++;
                } else {
                    $upsertMatch->execute([$sportId, $compId ?: null, $home, $away, $dt, $status, '', $evId]);
                    $matchId = (int)$pdo->lastInsertId();
                    $inserted++;
                }
                $mapMatch->execute([$evId, $matchId, $fm['event_name']]);

                $mktId = $fm['market_id'] !== '' ? $fm['market_id'] : ('1.' . $evId);
                $seenEvents[$evId] = true;
                $seenMatchIds[$matchId] = true;
                $seenMarkets[$mktId] = true;

                $archiveQueue[$evId] = [
                    'event_id' => $evId,
                    'event_name' => $fm['event_name'],
                    'fingerprint' => $fp,
                    'sport_slug' => $sportMeta['slug'],
                    'etid' => $fm['etid'],
                    'allpanel_gmid' => $evId,
                    'market_ids' => [$mktId => true],
                    'winner_name' => '',
                    'match_status' => $status,
                    'scorecard' => null,
                    'markets_result' => [],
                ];

                $quickRunners = [];
                foreach ($fm['sections'] as $sIdx => $sec) {
                    if (!is_array($sec)) continue;
                    $b1 = null; $bs1 = null; $l1 = null; $ls1 = null;
                    if (isset($sec['odds']) && is_array($sec['odds'])) {
                        foreach ($sec['odds'] as $o) {
                            $on = strtolower((string)($o['oname'] ?? ''));
                            if ($on === 'back1' && (float)($o['odds'] ?? 0) > 0) { $b1 = (float)$o['odds']; $bs1 = (float)($o['size'] ?? 0); }
                            if ($on === 'lay1' && (float)($o['odds'] ?? 0) > 0) { $l1 = (float)$o['odds']; $ls1 = (float)($o['size'] ?? 0); }
                        }
                    }
                    $rSt = !empty($sec['gstatus']) ? (string)$sec['gstatus'] : 'ACTIVE';
                    $quickRunners[] = [
                        'id' => $sec['sid'] ?? ($sIdx + 1),
                        'name' => (string)($sec['nat'] ?? $sec['rname'] ?? ($sIdx === 0 ? $home : ($sIdx === 1 ? $away : 'Runner ' . ($sIdx + 1)))),
                        'status' => $rSt,
                        'back' => $b1,
                        'backSize' => $bs1,
                        'lay' => $l1,
                        'laySize' => $ls1,
                    ];
                }

                $upsertMarket->execute([
                    $mktId,
                    $matchId,
                    'MATCH_ODDS',
                    'ODDS',
                    $fm['etid'] === 7 ? 'Win Market' : 'Match Odds',
                    'allpanel',
                    'OPEN',
                    $fm['in_play'] ? 1 : 0,
                    0,
                    $dt,
                    1,
                    json_encode($quickRunners, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
                    '',
                    json_encode(['hasTv' => $fm['has_tv']], JSON_UNESCAPED_UNICODE),
                    json_encode($fm['raw'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
                ]);
            }

            if (!$seenEvents || !$seenMatchIds) {
                throw new RuntimeException('No supported active events found.');
            }

            @file_put_contents($altFile, json_encode($altIdMap), LOCK_EX);

            $activeMatchIds = array_map('intval', array_keys($seenMatchIds));
            $matchPh = implode(',', array_fill(0, count($activeMatchIds), '?'));
            $staleStmt = $pdo->prepare(
                "SELECT DISTINCT match_id FROM sports_provider_events WHERE match_id NOT IN ($matchPh)
                 UNION
                 SELECT id AS match_id FROM sports_matches WHERE source_event_id IS NOT NULL AND source_event_id <> '' AND id NOT IN ($matchPh)"
            );
            $staleStmt->execute(array_merge($activeMatchIds, $activeMatchIds));
            $staleMatchIds = array_map('intval', $staleStmt->fetchAll(PDO::FETCH_COLUMN));

            if ($staleMatchIds) {
                try {
                    $stPh = implode(',', array_fill(0, count($staleMatchIds), '?'));
                    $oldStmt = $pdo->prepare("
                        SELECT m.id, m.home_name, m.away_name, m.source_event_id, s.slug AS sport_slug,
                               pe.provider_event_id, pe.provider_event_name
                        FROM sports_matches m
                        LEFT JOIN sports s ON s.id = m.sport_id
                        LEFT JOIN sports_provider_events pe ON pe.match_id = m.id
                        WHERE m.id IN ($stPh)
                    ");
                    $oldStmt->execute($staleMatchIds);
                    $oldRows = $oldStmt->fetchAll(PDO::FETCH_ASSOC);

                    $oldMktStmt = $pdo->prepare("SELECT match_id, provider_market_id, market_name, status, runners_json, odds_raw FROM sports_provider_markets WHERE match_id IN ($stPh)");
                    $oldMktStmt->execute($staleMatchIds);
                    $oldMktsByMatch = [];
                    foreach ($oldMktStmt->fetchAll(PDO::FETCH_ASSOC) as $om) {
                        $oldMktsByMatch[(int)$om['match_id']][] = $om;
                    }

                    $tmpDir = sys_get_temp_dir();
                    foreach ($oldRows as $or) {
                        $evId = trim((string)($or['provider_event_id'] ?: $or['source_event_id']));
                        if ($evId === '') continue;
                        $evName = trim((string)$or['provider_event_name']);
                        if ($evName === '') {
                            $evName = trim((string)$or['home_name']) . ($or['away_name'] !== '' ? ' v ' . trim((string)$or['away_name']) : '');
                        }
                        $slug = (string)($or['sport_slug'] ?: 'cricket');
                        $etid = sports_slug_to_etid($slug);
                        $mIds = [];
                        $wName = '';
                        foreach ($oldMktsByMatch[(int)$or['id']] ?? [] as $om) {
                            $mIds[] = (string)$om['provider_market_id'];
                            if ($wName === '') {
                                $wName = sports_extract_winner_from_market([
                                    'runners' => $om['runners_json'],
                                ], (string)$om['odds_raw']);
                            }
                        }

                        $cleanEvId = preg_replace('/[^0-9A-Za-z._-]/', '', $evId);
                        $cachedSc = null;
                        $scFile = $tmpDir . '/sp_score_live_' . md5($cleanEvId) . '.json';
                        if (is_file($scFile)) {
                            $decSc = json_decode((string)@file_get_contents($scFile), true);
                            if (is_array($decSc)) $cachedSc = $decSc;
                        }

                        if (!isset($archiveQueue[$evId])) {
                            $archiveQueue[$evId] = [
                                'event_id' => $evId,
                                'event_name' => $evName,
                                'fingerprint' => sports_match_fingerprint($etid, $evName),
                                'sport_slug' => $slug,
                                'etid' => $etid,
                                'allpanel_gmid' => (string)($prevAltMap[$evId]['allpanel_gmid'] ?? ''),
                                'market_ids' => array_fill_keys($mIds, true),
                                'winner_name' => $wName,
                                'match_status' => 'completed',
                                'scorecard' => $cachedSc,
                                'markets_result' => [],
                            ];
                        } elseif ($cachedSc && empty($archiveQueue[$evId]['scorecard'])) {
                            $archiveQueue[$evId]['scorecard'] = $cachedSc;
                        }
                    }
                } catch (Throwable $archErr) {
                    error_log('[Sports PreDelete Archive] ' . $archErr->getMessage());
                }

                $deleted = sports_delete_matches($pdo, $staleMatchIds);
            }

            $activeMarketIds = array_map('strval', array_keys($seenMarkets));
            if ($activeMarketIds) {
                $mktPh = implode(',', array_fill(0, count($activeMarketIds), '?'));
                $pdo->prepare("DELETE FROM sports_provider_markets WHERE provider_market_id NOT IN ($mktPh)")->execute($activeMarketIds);
            }

            $pdo->exec("INSERT INTO sports_provider_sync_log(id,last_success_at,events_seen,markets_seen,last_error) VALUES(1,UTC_TIMESTAMP()," . (int)count($seenEvents) . "," . (int)count($seenMarkets) . ",NULL) ON DUPLICATE KEY UPDATE last_success_at=VALUES(last_success_at),events_seen=VALUES(events_seen),markets_seen=VALUES(markets_seen),last_error=NULL");
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }

        $tmpDir = sys_get_temp_dir();
        foreach ($archiveQueue as $evId => $aq) {
            if (empty($aq['scorecard'])) {
                $cleanEvId = preg_replace('/[^0-9A-Za-z._-]/', '', (string)$evId);
                $scFile = $tmpDir . '/sp_score_live_' . md5($cleanEvId) . '.json';
                if (is_file($scFile)) {
                    $decSc = json_decode((string)@file_get_contents($scFile), true);
                    if (is_array($decSc)) $aq['scorecard'] = $decSc;
                }
            }
            sports_archive_event_snapshot($pdo, [
                'event_id' => $aq['event_id'],
                'event_name' => $aq['event_name'],
                'fingerprint' => $aq['fingerprint'],
                'sport_slug' => $aq['sport_slug'],
                'etid' => $aq['etid'],
                'allpanel_gmid' => $aq['allpanel_gmid'],
                'market_ids_json' => json_encode(array_keys($aq['market_ids']), JSON_UNESCAPED_UNICODE),
                'winner_name' => $aq['winner_name'],
                'match_status' => $aq['match_status'],
                'scorecard_json' => !empty($aq['scorecard']) ? json_encode($aq['scorecard'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) : '',
                'markets_result_json' => !empty($aq['markets_result']) ? json_encode($aq['markets_result'], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) : '[]',
            ]);
        }

        try {
            sports_maybe_background_auto_settle($pdo);
        } catch (Throwable $autoErr) {
            error_log('[Sports AutoSettle] ' . $autoErr->getMessage());
        }

        return [
            'events' => count($seenEvents),
            'markets' => count($seenMarkets),
            'inserted' => $inserted,
            'updated' => $updated,
            'deleted' => $deleted,
        ];
    }
}

if (!function_exists('sports_fetch_result_for_control')) {
    /**
     * Direct Server-Side Result Verifier for Cricket, Football & Tennis (Odds + Fancy):
     * Connects to DB + Archive + sp_scoreurl + oexch99 + AllPanel + ocric99 + free Cricinfo RSS / ESPN Scoreboard.
     */
    function sports_fetch_result_for_control(PDO $pdo, string $matchName, string $marketName = '', bool $isFancy = false, array $selections = []): array {
        sports_ensure_result_archive_table($pdo);

        $parts = preg_split('/\s+v(?:s)?\.?\s+/i', trim($matchName), 2);
        $homeTitle = trim((string)($parts[0] ?? $matchName));
        $awayTitle = trim((string)($parts[1] ?? ''));
        $candidateFps = [];
        foreach ([4, 1, 2, 7] as $sid) {
            $candidateFps[$sid] = sports_match_fingerprint($sid, $matchName);
        }

        $eventId = '';
        $apGmid = '';
        $etid = 4;
        $sportSlug = 'cricket';
        $marketIds = [];
        $archivedWinner = '';
        $archivedStatus = '';
        $archivedScorecard = null;
        $archivedMarketsResult = [];
        $dbMarkets = [];

        // Detect sport hint from market name if needed
        if (preg_match('/\b(goals?|corners?|cards?|halftime|half\s*time|both\s*teams\s*to\s*score|btts)\b/i', $marketName)) {
            $etid = 1;
            $sportSlug = 'football';
        } elseif (preg_match('/\b(sets?|games?|tiebreak|aces?)\b/i', $marketName)) {
            $etid = 2;
            $sportSlug = 'tennis';
        }

        // 1. Search Active DB tables
        try {
            $stmt = $pdo->query("
                SELECT m.id, m.home_name, m.away_name, m.status, m.source_event_id, s.slug AS sport_slug,
                       pe.provider_event_id, pe.provider_event_name
                FROM sports_matches m
                LEFT JOIN sports s ON s.id = m.sport_id
                LEFT JOIN sports_provider_events pe ON pe.match_id = m.id
                ORDER BY m.id DESC
                LIMIT 500
            ");
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
                $full = trim((string)$r['home_name']) . ($r['away_name'] !== '' ? ' v ' . trim((string)$r['away_name']) : '');
                $peName = trim((string)($r['provider_event_name'] ?? ''));
                $rEtid = sports_slug_to_etid((string)($r['sport_slug'] ?? 'cricket'));
                if (
                    sports_match_fingerprint($rEtid, $full) === $candidateFps[$rEtid] ||
                    ($peName !== '' && sports_match_fingerprint($rEtid, $peName) === $candidateFps[$rEtid]) ||
                    sports_names_match($full, $matchName)
                ) {
                    $eventId = trim((string)($r['provider_event_id'] ?: $r['source_event_id']));
                    $etid = $rEtid;
                    $sportSlug = (string)($r['sport_slug'] ?: 'cricket');
                    if (trim((string)$r['home_name']) !== '') $homeTitle = trim((string)$r['home_name']);
                    if (trim((string)$r['away_name']) !== '') $awayTitle = trim((string)$r['away_name']);

                    $mSt = $pdo->prepare("SELECT provider_market_id, market_name, market_type, status, runners_json, odds_raw, raw_json FROM sports_provider_markets WHERE match_id = ?");
                    $mSt->execute([(int)$r['id']]);
                    $dbMarkets = $mSt->fetchAll(PDO::FETCH_ASSOC) ?: [];
                    foreach ($dbMarkets as $dm) {
                        $marketIds[] = (string)$dm['provider_market_id'];
                    }
                    break;
                }
            }
        } catch (Throwable $e) {}

        // 2. Search Archive table
        try {
            $aRows = $pdo->query("SELECT * FROM sports_result_archive ORDER BY updated_at DESC LIMIT 600")->fetchAll(PDO::FETCH_ASSOC) ?: [];
            foreach ($aRows as $ar) {
                $arEtid = (int)($ar['etid'] ?: 4);
                if (
                    in_array((string)$ar['fingerprint'], $candidateFps, true) ||
                    sports_names_match((string)$ar['event_name'], $matchName)
                ) {
                    if ($eventId === '') $eventId = trim((string)$ar['event_id']);
                    if ($apGmid === '') $apGmid = trim((string)$ar['allpanel_gmid']);
                    $etid = $arEtid;
                    $sportSlug = (string)($ar['sport_slug'] ?: $sportSlug);
                    if ($archivedWinner === '') $archivedWinner = trim((string)$ar['winner_name']);
                    if ($archivedStatus === '') $archivedStatus = trim((string)$ar['match_status']);
                    if (!$archivedScorecard && !empty($ar['scorecard_json'])) {
                        $dec = json_decode((string)$ar['scorecard_json'], true);
                        if (is_array($dec)) $archivedScorecard = $dec;
                    }
                    if (!empty($ar['market_ids_json'])) {
                        $mArr = json_decode((string)$ar['market_ids_json'], true);
                        if (is_array($mArr)) $marketIds = array_merge($marketIds, $mArr);
                    }
                    if (!empty($ar['markets_result_json'])) {
                        $mrArr = json_decode((string)$ar['markets_result_json'], true);
                        if (is_array($mrArr)) $archivedMarketsResult = $mrArr;
                    }
                    break;
                }
            }
        } catch (Throwable $e) {}

        if ($eventId !== '' && $apGmid === '') {
            $alt = sports_alt_id_map_get($eventId);
            if (!empty($alt['allpanel_gmid'])) $apGmid = (string)$alt['allpanel_gmid'];
        }

        // 3. Query live oexch99 + AllPanel highlight feeds (including CLOSED events)
        $discoveryReqs = [
            'oexch99_list' => [
                'url' => 'https://api.oexch99.com/delaymarkets/markets/current',
                'timeout_ms' => 3500,
                'connect_ms' => 1500,
            ],
        ];
        foreach ([4, 1, 2, 7] as $sid) {
            $discoveryReqs['ap_' . $sid] = [
                'url' => "https://www.allpanelexch8.com/api/sports?endpoint=%2FhighlighthomePrivate&etid={$sid}",
                'headers' => ['Origin: https://www.allpanelexch8.com', 'Referer: https://www.allpanelexch8.com/'],
                'timeout_ms' => 2500,
                'connect_ms' => 1200,
            ];
        }
        $disc = sports_multi_race($discoveryReqs, 3600, 3600);

        $oexchMarketsFound = [];
        if (!empty($disc['oexch99_list']['ok']) && is_array($disc['oexch99_list']['data'])) {
            $payload = $disc['oexch99_list']['data'];
            $rows = $payload;
            foreach (['data', 'markets', 'results', 'items', 'catalogues'] as $key) {
                if (isset($payload[$key]) && is_array($payload[$key])) { $rows = $payload[$key]; break; }
            }
            foreach ($rows as $row) {
                if (!is_array($row)) continue;
                $ev = $row['event'] ?? ($row['catalogue']['event'] ?? []);
                $mkt = $row['catalogue'] ?? $row['market'] ?? $row;
                $evType = $row['eventType'] ?? ($row['catalogue']['eventType'] ?? []);
                $evName = trim((string)($ev['name'] ?? $row['eventName'] ?? $mkt['eventName'] ?? ''));
                $evIdRow = trim((string)($ev['id'] ?? $row['eventId'] ?? $mkt['eventId'] ?? ''));
                if ($evName === '' && $evIdRow === '') continue;

                $spMeta = sports_resolve_sport_meta(
                    (string)($evType['name'] ?? $row['sportName'] ?? ''),
                    (string)($evType['id'] ?? $row['eventTypeId'] ?? '')
                );
                $rowEtid = $spMeta ? $spMeta['etid'] : $etid;
                $fpMatch = ($eventId !== '' && $evIdRow === $eventId) ||
                    ($evName !== '' && (sports_match_fingerprint($rowEtid, $evName) === $candidateFps[$rowEtid] || sports_names_match($evName, $matchName)));
                if (!$fpMatch) continue;

                if ($eventId === '' && $evIdRow !== '') $eventId = $evIdRow;
                if ($spMeta) {
                    $etid = $spMeta['etid'];
                    $sportSlug = $spMeta['slug'];
                }
                $mid = trim((string)($mkt['marketId'] ?? $mkt['id'] ?? $row['marketId'] ?? ''));
                if ($mid !== '') $marketIds[] = $mid;
                $oexchMarketsFound[] = $row;
            }
        }

        $apHighlightItem = null;
        foreach ([4, 1, 2, 7] as $sid) {
            $apFeed = $disc['ap_' . $sid] ?? [];
            if (empty($apFeed['ok'])) continue;
            $apData = $apFeed['data']['data']['data'] ?? [];
            $list = array_merge(
                is_array($apData['t1'] ?? null) ? $apData['t1'] : [],
                is_array($apData['t2'] ?? null) ? $apData['t2'] : []
            );
            foreach ($list as $item) {
                if (!is_array($item)) continue;
                $evIdRow = trim((string)($item['gmid'] ?? $item['eventId'] ?? $item['gameId'] ?? ''));
                $evName = trim((string)($item['ename'] ?? $item['eventName'] ?? ''));
                if ($evName === '' && $evIdRow === '') continue;
                if (
                    ($apGmid !== '' && $evIdRow === $apGmid) ||
                    ($eventId !== '' && $evIdRow === $eventId) ||
                    ($evName !== '' && (sports_match_fingerprint($sid, $evName) === $candidateFps[$sid] || sports_names_match($evName, $matchName)))
                ) {
                    $apHighlightItem = $item;
                    $apGmid = $evIdRow !== '' ? $evIdRow : $apGmid;
                    if ($eventId === '' && $evIdRow !== '') $eventId = $evIdRow;
                    $etid = $sid;
                    $sportSlug = ($sid === 1 ? 'football' : ($sid === 2 ? 'tennis' : ($sid === 7 ? 'horse-racing' : 'cricket')));
                    if (!empty($item['mid'])) $marketIds[] = (string)$item['mid'];
                    break 2;
                }
            }
        }

        // Check cached scorecard URL file (/tmp/sp_scoreurl_*.txt)
        $scoreUrl = '';
        $tmpDir = sys_get_temp_dir();
        foreach (array_unique(array_filter([$eventId, $apGmid])) as $cid) {
            $cleanCid = preg_replace('/[^0-9A-Za-z._-]/', '', $cid);
            $suFile = $tmpDir . '/sp_scoreurl_' . md5($cleanCid) . '.txt';
            if (is_file($suFile)) {
                $candUrl = trim((string)@file_get_contents($suFile));
                if (preg_match('~^https?://~i', $candUrl)) {
                    $scoreUrl = $candUrl;
                    break;
                }
            }
        }

        // 4. Race specific detail endpoints
        $marketIds = array_values(array_unique(array_filter($marketIds)));
        $detailReqs = [];
        if ($eventId !== '') {
            $detailReqs['oexch_detail'] = [
                'url' => 'https://api.oexch99.com/delaymarkets/events/detail/' . rawurlencode($eventId),
                'timeout_ms' => 2500,
                'connect_ms' => 1000,
            ];
        }
        $apTargetId = $apGmid !== '' ? $apGmid : $eventId;
        if ($apTargetId !== '') {
            $detailReqs['ap_detail'] = [
                'url' => 'https://www.allpanelexch8.com/api/sports?endpoint=%2FgamedataPrivate&gmid=' . rawurlencode($apTargetId) . '&etid=' . $etid,
                'headers' => ['Origin: https://www.allpanelexch8.com', 'Referer: https://www.allpanelexch8.com/'],
                'timeout_ms' => 2500,
                'connect_ms' => 1000,
            ];
        }
        if ($scoreUrl !== '') {
            $detailReqs['cached_score_url'] = [
                'url' => $scoreUrl,
                'timeout_ms' => 2200,
                'connect_ms' => 900,
            ];
        }
        $bfMids = array_values(array_filter($marketIds, static fn($m) => strpos($m, '1.') === 0));
        if ($bfMids) {
            $partsBody = [];
            foreach (array_slice($bfMids, 0, 12) as $mid) {
                $partsBody[] = 'market_ids%5B%5D=' . rawurlencode($mid);
            }
            $detailReqs['ocric99'] = [
                'url' => 'https://odd.ocric99.com/ws/getMarketDataNew',
                'method' => 'POST',
                'body' => implode('&', $partsBody),
                'headers' => [
                    'Origin: https://reddybook.store',
                    'Referer: https://reddybook.store/',
                    'Content-Type: application/x-www-form-urlencoded',
                ],
                'timeout_ms' => 2200,
                'connect_ms' => 900,
            ];
        }

        $details = $detailReqs ? sports_multi_race($detailReqs, 2800, 2800) : [];

        $allMarkets = [];
        $scorecard = $archivedScorecard;
        $mainStatusCandidates = [];
        $targetStatusCandidates = [];
        if ($archivedStatus !== '') $mainStatusCandidates[] = $archivedStatus;

        $winnerCandidate = $archivedWinner;
        $fancyActualRuns = null;
        $sourcesUsed = [];
        $players = [];
        $seenPlayers = [];
        $fowList = [];
        $matchedFancySection = null;
        $apSectionsSample = [];
        $oexchDetailSample = null;
        $tennisTotalGames = is_array($scorecard) && isset($scorecard['tennis_total_games']) && is_numeric($scorecard['tennis_total_games'])
            ? (float)$scorecard['tennis_total_games'] : null;

        $collectPlayersAndFow = static function($node, int $depth = 0) use (&$collectPlayersAndFow, &$players, &$seenPlayers, &$fowList): void {
            if (!is_array($node) || $depth > 5) return;
            foreach ($node as $k => $v) {
                if (is_string($k) && preg_match('/^(batsmen|batting|players|home_batsmen|away_batsmen|batters)$/i', $k) && is_array($v)) {
                    foreach ($v as $p) {
                        if (!is_array($p)) continue;
                        $pName = trim((string)($p['name'] ?? $p['player_name'] ?? $p['batsman'] ?? $p['batsman_name'] ?? $p['title'] ?? $p['n'] ?? ''));
                        $pRuns = $p['runs'] ?? ($p['r'] ?? ($p['score'] ?? null));
                        $dismissal = strtolower(trim((string)($p['out'] ?? $p['dismissal'] ?? $p['status'] ?? $p['wicket'] ?? '')));
                        $isOut = ($dismissal !== '' && strpos($dismissal, 'not out') === false && $dismissal !== 'batting' && $dismissal !== 'false' && $dismissal !== '0');
                        if ($pName !== '' && $pRuns !== null && is_numeric($pRuns)) {
                            $lk = strtolower($pName);
                            if (!isset($seenPlayers[$lk])) {
                                $seenPlayers[$lk] = true;
                                $players[] = ['name' => $pName, 'runs' => (float)$pRuns, 'is_out' => $isOut];
                            }
                        }
                    }
                } elseif (is_string($k) && preg_match('/^(fow|fall_of_wickets|fallOfWickets|wickets)$/i', $k) && is_array($v)) {
                    foreach ($v as $idx => $fw) {
                        if (is_array($fw)) {
                            $wNo = (int)($fw['wicket'] ?? $fw['wkt'] ?? ($idx + 1));
                            $wScore = $fw['score'] ?? ($fw['runs'] ?? ($fw['r'] ?? null));
                            $wTeam = trim((string)($fw['team'] ?? $fw['team_name'] ?? ''));
                            if ($wScore !== null && is_numeric($wScore)) {
                                $fowList[] = ['wicket' => $wNo, 'runs' => (float)$wScore, 'team' => $wTeam];
                            }
                        } elseif (is_string($fw) && preg_match('/^(\d+)\s*[-–\/]\s*(\d+)/', trim($fw), $fm)) {
                            $fowList[] = ['wicket' => (int)$fm[2], 'runs' => (float)$fm[1], 'team' => ''];
                        }
                    }
                } elseif (is_array($v)) {
                    $collectPlayersAndFow($v, $depth + 1);
                }
            }
        };

        if ($dbMarkets) $sourcesUsed[] = 'db';
        if ($archivedWinner !== '' || $archivedScorecard) $sourcesUsed[] = 'archive';
        if (is_array($archivedScorecard)) $collectPlayersAndFow($archivedScorecard);

        foreach ($dbMarkets as $dm) {
            $runners = json_decode((string)$dm['runners_json'], true) ?: [];
            $rawRow = json_decode((string)$dm['raw_json'], true) ?: [];
            $allMarkets[] = [
                'market_id' => (string)$dm['provider_market_id'],
                'market_name' => (string)$dm['market_name'],
                'market_type' => (string)$dm['market_type'],
                'status' => (string)$dm['status'],
                'runners' => $runners,
                'odds_raw' => (string)$dm['odds_raw'],
                'raw' => $rawRow,
            ];
            if (!$scorecard && $rawRow) {
                $sc = sports_extract_scorecard($rawRow, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
                if ($sc) $scorecard = $sc;
            }
            if ($rawRow) $collectPlayersAndFow($rawRow);
        }

        foreach ($oexchMarketsFound as $row) {
            $mkt = $row['catalogue'] ?? $row['market'] ?? $row;
            $meta = $row['metadata'] ?? ($mkt['metadata'] ?? []);
            $book = trim((string)($meta['book'] ?? $row['book'] ?? $mkt['book'] ?? ''));
            $bh = sports_parse_book_status($book);
            $st = strtoupper(trim((string)($bh['status'] ?: ($mkt['status'] ?? $row['status'] ?? ''))));
            $allMarkets[] = [
                'market_id' => (string)($mkt['marketId'] ?? $mkt['id'] ?? $row['marketId'] ?? ''),
                'market_name' => (string)($mkt['marketName'] ?? $row['marketName'] ?? ''),
                'market_type' => (string)($mkt['marketType'] ?? $row['marketType'] ?? ''),
                'status' => $st,
                'runners' => $mkt['runners'] ?? ($row['runners'] ?? []),
                'odds_raw' => $book,
                'raw' => $row,
            ];
            $sc = sports_extract_scorecard($row, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
            if ($sc) $scorecard = $sc;
            $collectPlayersAndFow($row);
            $sourcesUsed[] = 'oexch99_list';
        }

        if (!empty($details['oexch_detail']['ok']) && is_array($details['oexch_detail']['data'])) {
            $oxDet = $details['oexch_detail']['data'];
            $sourcesUsed[] = 'oexch99_detail';
            $oexchDetailSample = array_keys($oxDet);
            $sc = sports_extract_scorecard($oxDet, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
            if ($sc) $scorecard = $sc;
            $collectPlayersAndFow($oxDet);
            $detMarkets = $oxDet['markets'] ?? ($oxDet['data']['markets'] ?? ($oxDet['catalogues'] ?? (isset($oxDet[0]) ? $oxDet : [])));
            if (is_array($detMarkets)) {
                foreach ($detMarkets as $dm) {
                    if (!is_array($dm)) continue;
                    $mkt = $dm['catalogue'] ?? $dm;
                    $book = trim((string)($dm['metadata']['book'] ?? $dm['book'] ?? $mkt['book'] ?? ''));
                    $bh = sports_parse_book_status($book);
                    $st = strtoupper(trim((string)($bh['status'] ?: ($mkt['status'] ?? $dm['status'] ?? ''))));
                    $allMarkets[] = [
                        'market_id' => (string)($mkt['marketId'] ?? $mkt['id'] ?? ''),
                        'market_name' => (string)($mkt['marketName'] ?? $dm['marketName'] ?? ''),
                        'market_type' => (string)($mkt['marketType'] ?? $dm['marketType'] ?? ''),
                        'status' => $st,
                        'runners' => $mkt['runners'] ?? ($dm['runners'] ?? []),
                        'odds_raw' => $book,
                        'raw' => $dm,
                    ];
                }
            }
        }

        if ($apHighlightItem) {
            $sourcesUsed[] = 'allpanel_list';
            $apSt = strtoupper(trim((string)($apHighlightItem['status'] ?? $apHighlightItem['gstatus'] ?? '')));
            $allMarkets[] = [
                'market_id' => (string)($apHighlightItem['mid'] ?? ''),
                'market_name' => 'Match Odds',
                'market_type' => 'MATCH_ODDS',
                'status' => $apSt,
                'runners' => $apHighlightItem['section'] ?? [],
                'odds_raw' => '',
                'raw' => $apHighlightItem,
            ];
            $sc = sports_extract_scorecard($apHighlightItem, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
            if ($sc) $scorecard = $sc;
            $collectPlayersAndFow($apHighlightItem);
        }

        if (!empty($details['ap_detail']['ok']) && is_array($details['ap_detail']['data'])) {
            $apDet = $details['ap_detail']['data'];
            $sourcesUsed[] = 'allpanel_detail';
            $sc = sports_extract_scorecard($apDet, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
            if ($sc) $scorecard = $sc;
            $collectPlayersAndFow($apDet);
            $apBlocks = $apDet['data']['data'] ?? ($apDet['data'] ?? []);
            if (is_array($apBlocks)) {
                foreach ($apBlocks as $blk) {
                    if (!is_array($blk)) continue;
                    $mNm = trim((string)($blk['mname'] ?? $blk['marketName'] ?? ''));
                    $gType = trim((string)($blk['gtype'] ?? ''));
                    $mSt = strtoupper(trim((string)($blk['status'] ?? $blk['gstatus'] ?? '')));
                    $secs = is_array($blk['section'] ?? null) ? $blk['section'] : [];
                    $allMarkets[] = [
                        'market_id' => (string)($blk['mid'] ?? ''),
                        'market_name' => $mNm,
                        'market_type' => $gType,
                        'status' => $mSt,
                        'runners' => $secs,
                        'odds_raw' => '',
                        'raw' => $blk,
                    ];

                    if (count($apSectionsSample) < 10 && $secs) {
                        $apSectionsSample[] = ['mname' => $mNm, 'gtype' => $gType, 'sample_nat' => (string)($secs[0]['nat'] ?? '')];
                    }
                    if ($marketName !== '' && $secs) {
                        foreach ($secs as $sec) {
                            if (!is_array($sec)) continue;
                            $sNat = trim((string)($sec['nat'] ?? $sec['rname'] ?? ''));
                            if ($sNat !== '' && (strcasecmp($sNat, $marketName) === 0 || sports_names_match($sNat, $marketName))) {
                                $matchedFancySection = $sec;
                                $sSt = strtoupper(trim((string)($sec['gstatus'] ?? $sec['status'] ?? '')));
                                if ($sSt !== '') $targetStatusCandidates[] = $sSt;
                                foreach (['result', 'res', 'settled_value', 'runs', 'actual_runs'] as $rk) {
                                    if (isset($sec[$rk]) && $sec[$rk] !== '' && is_numeric($sec[$rk])) {
                                        $fancyActualRuns = (float)$sec[$rk];
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        if (!empty($details['cached_score_url']['ok']) && is_array($details['cached_score_url']['data'])) {
            $sourcesUsed[] = 'score_url';
            $scData = $details['cached_score_url']['data'];
            $sc = sports_extract_scorecard($scData, ['home_name' => $homeTitle, 'away_name' => $awayTitle]);
            if ($sc) $scorecard = $sc;
            $collectPlayersAndFow($scData);
        }

        if (!empty($details['ocric99']['ok']) && is_array($details['ocric99']['data'])) {
            $sourcesUsed[] = 'ocric99';
            foreach ($details['ocric99']['data'] as $oc) {
                if (!is_array($oc)) continue;
                $ocSt = strtoupper(trim((string)($oc['status'] ?? '')));
                $allMarkets[] = [
                    'market_id' => (string)($oc['marketId'] ?? ''),
                    'market_name' => (string)($oc['marketName'] ?? 'Match Odds'),
                    'market_type' => 'MATCH_ODDS',
                    'status' => $ocSt,
                    'runners' => $oc['runners'] ?? [],
                    'odds_raw' => '',
                    'raw' => $oc,
                ];
            }
        }

        if (!$scorecard) {
            foreach (array_unique(array_filter([$eventId, $apGmid])) as $cid) {
                $cleanEvId = preg_replace('/[^0-9A-Za-z._-]/', '', $cid);
                $scFile = $tmpDir . '/sp_score_live_' . md5($cleanEvId) . '.json';
                if (is_file($scFile)) {
                    $decSc = json_decode((string)@file_get_contents($scFile), true);
                    if (is_array($decSc)) {
                        $scorecard = $decSc;
                        $collectPlayersAndFow($decSc);
                        $sourcesUsed[] = 'disk_score_cache';
                        break;
                    }
                }
            }
        }

        foreach ($archivedMarketsResult as $amr) {
            if (!is_array($amr)) continue;
            $amrName = trim((string)($amr['market_name'] ?? ''));
            if ($amrName !== '' && ($marketName === '' || strcasecmp($amrName, $marketName) === 0 || sports_names_match($amrName, $marketName))) {
                if (!empty($amr['winner']) && $winnerCandidate === '') {
                    $winnerCandidate = (string)$amr['winner'];
                }
                if (!empty($amr['status'])) {
                    $targetStatusCandidates[] = strtoupper((string)$amr['status']);
                }
            }
        }

        $matchedMarket = null;
        foreach ($allMarkets as $am) {
            $amName = trim((string)($am['market_name'] ?? ''));
            $amType = strtoupper(trim((string)($am['market_type'] ?? '')));
            $amStatus = strtoupper(trim((string)($am['status'] ?? '')));
            $isMainMkt = ($amType === 'MATCH_ODDS' || strcasecmp($amName, 'Match Odds') === 0 || strcasecmp($amName, 'Win Market') === 0);

            if ($isMainMkt && $amStatus !== '') {
                $mainStatusCandidates[] = $amStatus;
            }
            if ($marketName !== '' && $amName !== '' && (strcasecmp($amName, $marketName) === 0 || sports_names_match($amName, $marketName))) {
                $matchedMarket = $am;
                if ($amStatus !== '') $targetStatusCandidates[] = $amStatus;
            }

            $w = sports_extract_winner_from_market($am, (string)($am['odds_raw'] ?? ''));
            if ($w !== '') {
                if ($matchedMarket === $am || $isMainMkt || stripos($amName, 'bookmaker') !== false || $winnerCandidate === '') {
                    $winnerCandidate = $w;
                }
            }

            $rawM = is_array($am['raw'] ?? null) ? $am['raw'] : [];
            if ($isFancy && ($matchedMarket === $am || ($amName !== '' && sports_names_match($amName, $marketName)))) {
                foreach (['result', 'settled_value', 'settledValue', 'runs', 'actual_runs', 'res'] as $rk) {
                    if (isset($rawM[$rk]) && $rawM[$rk] !== '' && is_numeric($rawM[$rk])) {
                        $fancyActualRuns = (float)$rawM[$rk];
                        break;
                    }
                }
            }
        }

        // Parse scorecard numbers
        $homeScoreText = '-';
        $awayScoreText = '-';
        $homeRuns = null;
        $awayRuns = null;
        $needText = '';

        if (is_array($scorecard)) {
            $t1 = is_array($scorecard['t1'] ?? null) ? $scorecard['t1'] : [];
            $t2 = is_array($scorecard['t2'] ?? null) ? $scorecard['t2'] : [];
            $hRaw = trim((string)($t1['score'] ?? $scorecard['score1'] ?? $scorecard['home_score'] ?? ''));
            $hOv = trim((string)($t1['overs'] ?? $scorecard['over1'] ?? ''));
            $aRaw = trim((string)($t2['score'] ?? $scorecard['score2'] ?? $scorecard['away_score'] ?? ''));
            $aOv = trim((string)($t2['overs'] ?? $scorecard['over2'] ?? ''));

            if ($hRaw !== '') {
                $homeScoreText = $hRaw . ($hOv !== '' ? " ({$hOv})" : '');
                if (preg_match('/^(\d+)/', $hRaw, $hm)) $homeRuns = (float)$hm[1];
            }
            if ($aRaw !== '') {
                $awayScoreText = $aRaw . ($aOv !== '' ? " ({$aOv})" : '');
                if (preg_match('/^(\d+)/', $aRaw, $am)) $awayRuns = (float)$am[1];
            }
            $needText = trim((string)($scorecard['need_text'] ?? $scorecard['spnmessage'] ?? $scorecard['message'] ?? ''));
            if ($tennisTotalGames === null && isset($scorecard['tennis_total_games']) && is_numeric($scorecard['tennis_total_games'])) {
                $tennisTotalGames = (float)$scorecard['tennis_total_games'];
            }
        }

        // 5a. Free Cricinfo Live Scores RSS fallback for ALL Cricket (zero billing)
      $players = isset($players) && is_array($players) ? $players : [];
$fowList = isset($fowList) && is_array($fowList) ? $fowList : [];
$seenPlayers = isset($seenPlayers) && is_array($seenPlayers) ? $seenPlayers : [];
foreach ($players as $exPl) {
    if (!empty($exPl['name'])) {
        $seenPlayers[strtolower(trim((string)$exPl['name']))] = true;
    }
}

$needCricinfo = ($homeRuns === null && $awayRuns === null) || empty($players) || empty($fowList);

if ($etid === 4 && $needCricinfo && function_exists('curl_init')) {
    $chRss = curl_init('https://static.cricinfo.com/rss/livescores.xml');
    curl_setopt_array($chRss, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT_MS => 1500,
        CURLOPT_TIMEOUT_MS => 3500,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    ]);
    $xmlRaw = curl_exec($chRss);
    $xmlCode = (int)curl_getinfo($chRss, CURLINFO_HTTP_CODE);
    curl_close($chRss);

    if (is_string($xmlRaw) && $xmlRaw !== '' && $xmlCode >= 200 && $xmlCode < 300) {
        $prevUseErr = libxml_use_internal_errors(true);
        $sx = @simplexml_load_string($xmlRaw);
        libxml_clear_errors();
        libxml_use_internal_errors($prevUseErr);

        if ($sx && isset($sx->channel->item)) {
            foreach ($sx->channel->item as $item) {
                $title = trim((string)$item->title);
                if ($title === '') continue;

                $rssParts = preg_split('/\s+v(?:s\.?)?\s+/i', $title, 2);
                if (count($rssParts) !== 2) continue;

                $sA = trim($rssParts[0]);
                $sB = trim($rssParts[1]);

                $matchForward = sports_names_match($sA, $homeTitle) && sports_names_match($sB, $awayTitle);
                $matchReverse = sports_names_match($sA, $awayTitle) && sports_names_match($sB, $homeTitle);
                if (!$matchForward && !$matchReverse) continue;

                $sourcesUsed[] = 'cricinfo_rss';

                $extractScore = static function (string $sideStr): array {
                    if (preg_match('/(?:^|\s)(\d+(?:\/\d+)?d?(?:\s*&\s*\d+(?:\/\d+)?d?)?(?:\s*\([^)]+\))?)\s*\*?\s*$/i', $sideStr, $sm)) {
                        $txt = trim($sm[1]);
                        $runs = preg_match('/^(\d+)/', $txt, $rm) ? (float)$rm[1] : null;
                        return [$txt, $runs];
                    }
                    return ['-', null];
                };

                [$txtA, $runsA] = $extractScore($sA);
                [$txtB, $runsB] = $extractScore($sB);

                if ($matchForward) {
                    if ($homeRuns === null && $txtA !== '-') { $homeScoreText = $txtA; $homeRuns = $runsA; }
                    if ($awayRuns === null && $txtB !== '-') { $awayScoreText = $txtB; $awayRuns = $runsB; }
                } else {
                    if ($homeRuns === null && $txtB !== '-') { $homeScoreText = $txtB; $homeRuns = $runsB; }
                    if ($awayRuns === null && $txtA !== '-') { $awayScoreText = $txtA; $awayRuns = $runsA; }
                }

                // Try Cricinfo match JSON for batsmen runs & fall-of-wickets (fow)
                $linkStr = trim((string)($item->guid ?: $item->link));
                if (preg_match('/(\d{5,9})(?:\.html|\/(?:live-cricket-score|full-scorecard|match-preview|ball-by-ball-commentary|match-report))/i', $linkStr, $midM)) {
                    $ciUrl = 'https://www.espncricinfo.com/matches/engine/match/' . $midM[1] . '.json';
                    $chCi = curl_init($ciUrl);
                    curl_setopt_array($chCi, [
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_FOLLOWLOCATION => true,
                        CURLOPT_CONNECTTIMEOUT_MS => 1500,
                        CURLOPT_TIMEOUT_MS => 3500,
                        CURLOPT_HTTPHEADER => ['Accept: application/json'],
                        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                    ]);
                    $ciRaw = curl_exec($chCi);
                    $ciCode = (int)curl_getinfo($chCi, CURLINFO_HTTP_CODE);
                    curl_close($chCi);

                    if (is_string($ciRaw) && $ciRaw !== '' && $ciCode >= 200 && $ciCode < 300) {
                        $ciJson = json_decode($ciRaw, true);
                        if (is_array($ciJson)) {
                            $sourcesUsed[] = 'cricinfo_json';

                            $ciStatus = strtolower((string)($ciJson['match']['match_status'] ?? ''));
                            if ($ciStatus === 'complete' || $ciStatus === 'dormant' || !empty($ciJson['match']['winner_team_id'])) {
                                $mainStatusCandidates[] = 'COMPLETED';
                            }

                            if (!empty($ciJson['live']['status'])) {
                                $needText = (string)$ciJson['live']['status'];
                            }

                            $teamMap = [];
                            foreach (($ciJson['team'] ?? []) as $tm) {
                                if (!is_array($tm)) continue;
                                $tId = (string)($tm['team_id'] ?? '');
                                if ($tId !== '') {
                                    $teamMap[$tId] = (string)($tm['team_name'] ?? $tm['team_short_name'] ?? '');
                                }
                            }

                            $seenFow = [];
                            foreach ($fowList as $efw) {
                                $seenFow[strtolower((string)($efw['team'] ?? '')) . '#' . (int)($efw['wicket'] ?? 0)] = true;
                            }

                            foreach (($ciJson['innings'] ?? []) as $inn) {
                                if (!is_array($inn)) continue;
                                $btId = (string)($inn['batting_team_id'] ?? '');
                                $innTeam = $teamMap[$btId] ?? '';

                                foreach (($inn['fow'] ?? []) as $fw) {
                                    if (!is_array($fw)) continue;
                                    $wNo = (int)($fw['fow_order'] ?? 0);
                                    $wRuns = $fw['fow_runs'] ?? null;
                                    if ($wNo > 0 && is_numeric($wRuns)) {
                                        $fwKey = strtolower($innTeam) . '#' . $wNo;
                                        if (!isset($seenFow[$fwKey])) {
                                            $seenFow[$fwKey] = true;
                                            $fowList[] = [
                                                'wicket' => $wNo,
                                                'runs'   => (float)$wRuns,
                                                'team'   => $innTeam,
                                            ];
                                        }
                                    }
                                }
                            }

                            foreach (($ciJson['centre']['batting'] ?? []) as $bat) {
                                if (!is_array($bat)) continue;
                                $pNm = trim((string)($bat['known_as'] ?? $bat['popular_name'] ?? ''));
                                $pRn = $bat['runs'] ?? null;
                                $isNotOut = !empty($bat['notout']);
                                if ($pNm !== '' && is_numeric($pRn)) {
                                    $lk = strtolower($pNm);
                                    if (!isset($seenPlayers[$lk])) {
                                        $seenPlayers[$lk] = true;
                                        $players[] = [
                                            'name'   => $pNm,
                                            'runs'   => (float)$pRn,
                                            'is_out' => !$isNotOut,
                                        ];
                                    }
                                }
                            }
                        }
                    }
                }

                if ($needText === '') {
                    $needText = $title;
                }
                break;
            }
        }
    }
}

        // 5b. Free Public ESPN Scoreboard fallback (Football + Tennis ATP/WTA + IPL) across Today & Yesterday
        $todayStr = gmdate('Ymd');
        $yestStr = gmdate('Ymd', time() - 86400);
        $espnReqs = [];
        if ($etid === 1) {
            $espnReqs['soc_today'] = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/soccer/all/scoreboard?dates=' . $todayStr, 'timeout_ms' => 1900, 'connect_ms' => 900];
            $espnReqs['soc_yest']  = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/soccer/all/scoreboard?dates=' . $yestStr, 'timeout_ms' => 1900, 'connect_ms' => 900];
        } elseif ($etid === 2) {
            $espnReqs['atp_cur']  = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/tennis/atp/scoreboard', 'timeout_ms' => 1900, 'connect_ms' => 900];
            $espnReqs['wta_cur']  = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/tennis/wta/scoreboard', 'timeout_ms' => 1900, 'connect_ms' => 900];
            $espnReqs['atp_yest'] = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/tennis/atp/scoreboard?dates=' . $yestStr, 'timeout_ms' => 1900, 'connect_ms' => 900];
            $espnReqs['wta_yest'] = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/tennis/wta/scoreboard?dates=' . $yestStr, 'timeout_ms' => 1900, 'connect_ms' => 900];
        } elseif ($etid === 4) {
            $espnReqs['ipl_cur']  = ['url' => 'https://site.api.espn.com/apis/site/v2/sports/cricket/8048/scoreboard', 'timeout_ms' => 1800, 'connect_ms' => 800];
        }

        if (($winnerCandidate === '' || ($homeRuns === null && $awayRuns === null)) && $espnReqs) {
            $espnRes = sports_multi_race($espnReqs, 2200, 2200);
            foreach ($espnRes as $er) {
                if (empty($er['ok']) || empty($er['data']['events']) || !is_array($er['data']['events'])) continue;
                foreach ($er['data']['events'] as $ev) {
                    // Tennis nests matches under groupings[].competitions[]; Football/Cricket under competitions[]
                    $compCandidates = [];
                    if (!empty($ev['competitions']) && is_array($ev['competitions'])) {
                        foreach ($ev['competitions'] as $cObj) $compCandidates[] = $cObj;
                    }
                    if (!empty($ev['groupings']) && is_array($ev['groupings'])) {
                        foreach ($ev['groupings'] as $grpObj) {
                            if (!empty($grpObj['competitions']) && is_array($grpObj['competitions'])) {
                                foreach ($grpObj['competitions'] as $cObj) $compCandidates[] = $cObj;
                            }
                        }
                    }

                    foreach ($compCandidates as $comp) {
                        $comps = $comp['competitors'] ?? [];
                        if (count($comps) < 2) continue;
                        $c0Name = trim((string)($comps[0]['team']['displayName'] ?? $comps[0]['athlete']['displayName'] ?? $comps[0]['athlete']['shortName'] ?? ''));
                        $c1Name = trim((string)($comps[1]['team']['displayName'] ?? $comps[1]['athlete']['displayName'] ?? $comps[1]['athlete']['shortName'] ?? ''));
                        $evNm = trim((string)($ev['name'] ?? $ev['shortName'] ?? ($c0Name . ' v ' . $c1Name)));

                        $matchesEvent = sports_names_match($evNm, $matchName) ||
                            ($c0Name !== '' && $c1Name !== '' && (
                                (sports_names_match($c0Name, $homeTitle) && sports_names_match($c1Name, $awayTitle)) ||
                                (sports_names_match($c0Name, $awayTitle) && sports_names_match($c1Name, $homeTitle))
                            ));
                        if (!$matchesEvent) continue;

                        $sourcesUsed[] = 'espn_scoreboard';
                        $evState = strtolower((string)($comp['status']['type']['state'] ?? $ev['status']['type']['state'] ?? ''));
                        $evCompleted = !empty($comp['status']['type']['completed']) || !empty($ev['status']['type']['completed']) || $evState === 'post';
                        if ($evCompleted) $mainStatusCandidates[] = 'COMPLETED';
                        elseif ($evState === 'in') $mainStatusCandidates[] = 'LIVE';

                        $evDetail = trim((string)($comp['status']['type']['detail'] ?? $comp['status']['type']['shortDetail'] ?? $ev['status']['type']['detail'] ?? ''));
                        if ($needText === '' && $evDetail !== '') $needText = $evDetail;

                        // Parse Tennis set linescores if present
                        if ($etid === 2 && !empty($comps[0]['linescores']) && is_array($comps[0]['linescores'])) {
                            $ls0 = $comps[0]['linescores'];
                            $ls1 = is_array($comps[1]['linescores'] ?? null) ? $comps[1]['linescores'] : [];
                            $setPairs = [];
                            $totG = 0; $w0 = 0; $w1 = 0;
                            $maxSets = max(count($ls0), count($ls1));
                            for ($si = 0; $si < $maxSets; $si++) {
                                $g0 = (int)($ls0[$si]['value'] ?? 0);
                                $g1 = (int)($ls1[$si]['value'] ?? 0);
                                $totG += ($g0 + $g1);
                                if ($g0 > $g1) $w0++; elseif ($g1 > $g0) $w1++;
                                $setPairs[] = "{$g0}-{$g1}";
                            }
                            if ($setPairs) {
                                $tennisTotalGames = (float)$totG;
                                $is0Home = sports_names_match($c0Name, $homeTitle);
                                if ($is0Home) {
                                    $homeScoreText = "{$w0} Sets (" . implode(', ', $setPairs) . ")";
                                    $awayScoreText = "{$w1} Sets";
                                    $homeRuns = (float)$w0;
                                    $awayRuns = (float)$w1;
                                } else {
                                    $homeScoreText = "{$w1} Sets";
                                    $awayScoreText = "{$w0} Sets (" . implode(', ', $setPairs) . ")";
                                    $homeRuns = (float)$w1;
                                    $awayRuns = (float)$w0;
                                }
                            }
                        }

                        foreach ($comps as $cItem) {
                            $tNm = trim((string)($cItem['team']['displayName'] ?? $cItem['athlete']['displayName'] ?? $cItem['athlete']['shortName'] ?? ''));
                            $scVal = trim((string)($cItem['score'] ?? ''));
                            if (!empty($cItem['winner']) && $evCompleted && $winnerCandidate === '' && $tNm !== '') {
                                $winnerCandidate = $tNm;
                            }
                            if ($scVal !== '' && $etid !== 2) {
                                if (sports_names_match($tNm, $homeTitle)) {
                                    $homeScoreText = $scVal;
                                    if (preg_match('/^(\d+)/', $scVal, $hm)) $homeRuns = (float)$hm[1];
                                } elseif (sports_names_match($tNm, $awayTitle)) {
                                    $awayScoreText = $scVal;
                                    if (preg_match('/^(\d+)/', $scVal, $am)) $awayRuns = (float)$am[1];
                                }
                            }
                        }
                        break 3;
                    }
                }
            }
        }

        // Determine completion ONLY from target market or main MATCH_ODDS status
        $terminal = sports_terminal_statuses();
        $isAbandoned = false;
        $isCompleted = false;
        $statusPool = $targetStatusCandidates ?: $mainStatusCandidates;
        foreach ($statusPool as $stCand) {
            $u = strtoupper(trim((string)$stCand));
            if ($u === '' || $u === 'SUSPENDED' || $u === 'SUSPEND' || $u === 'OPEN' || $u === 'ACTIVE') continue;
            if (in_array($u, ['ABANDONED', 'CANCELLED', 'CANCELED', 'VOID'], true)) {
                $isAbandoned = true;
                $isCompleted = true;
            } elseif (in_array($u, $terminal, true) || $u === 'COMPLETED') {
                $isCompleted = true;
            }
        }

        if (!$isCompleted && $needText !== '' && preg_match('/\b(won by|match tied|match drawn|no result|abandoned|cancelled|full[\s-]*time|final)\b/i', $needText)) {
            $isCompleted = true;
            if (preg_match('/\b(no result|abandoned|cancelled)\b/i', $needText)) {
                $isAbandoned = true;
            }
        }
        if (!$isFancy && $winnerCandidate !== '') {
            $isCompleted = true;
        }
        if ($isFancy && $fancyActualRuns !== null) {
            $isCompleted = true;
        }

        if ($winnerCandidate === '' && $needText !== '') {
            if (preg_match('/^(.+?)\s+(?:won|beat|win)\b/i', $needText, $wm)) {
                $winnerCandidate = trim($wm[1]);
            } elseif (preg_match('/\b(draw|drawn|tied|tie)\b/i', $needText)) {
                $winnerCandidate = 'Draw';
            }
        }
        if ($winnerCandidate === '' && $isCompleted && $homeRuns !== null && $awayRuns !== null) {
            if ($homeRuns > $awayRuns) $winnerCandidate = $homeTitle;
            elseif ($awayRuns > $homeRuns) $winnerCandidate = $awayTitle;
            else $winnerCandidate = 'Draw';
        }

        $matchedSelection = '';
        if ($winnerCandidate !== '' && $selections) {
            $matchedSelection = sports_find_best_selection($winnerCandidate, $selections);
        }
        if ($matchedSelection === '' && $winnerCandidate !== '') {
            $matchedSelection = $winnerCandidate;
        }

        // Fancy resolution (Cricket Players, FOW, Team Totals + Football Total Goals + Tennis Total Games)
        if ($isFancy && $fancyActualRuns === null) {
            $ctx = trim($marketName . ' ' . implode(' ', $selections));

            // 1. Fall of Wicket (e.g. "2nd Wkt IND")
            if (preg_match('/\b([1-9])(?:st|nd|rd|th)?\s*wkt\b/i', $ctx, $wm) && $fowList) {
                $wNum = (int)$wm[1];
                foreach ($fowList as $fw) {
                    if ((int)$fw['wicket'] === $wNum && ($fw['team'] === '' || sports_names_match($ctx, (string)$fw['team']))) {
                        $fancyActualRuns = (float)$fw['runs'];
                        break;
                    }
                }
            }

            // 2. Player Batting Runs (only if player is out OR match is completed)
            if ($fancyActualRuns === null) {
                foreach ($players as $pl) {
                    if (sports_names_match($ctx, (string)$pl['name'])) {
                        if ($isCompleted || !empty($pl['is_out'])) {
                            $fancyActualRuns = (float)$pl['runs'];
                        }
                        break;
                    }
                }
            }

            // 3. Tennis Total Games / Football Total Goals / Cricket Team & Match Totals (only when completed)
            if ($fancyActualRuns === null && $isCompleted) {
                $isPlayerOrWktFancy = (bool)preg_match('/\b(wkt|wicket|runs\b.*(kohli|sharma|padikkal|gill|jaiswal|rahul|pant|iyer|williamson|conway|ravindra|mitchell|latham|player)|boundary|fours|sixes|partnership|over\b)\b/i', $ctx);
                if ($etid === 2 && $tennisTotalGames !== null && preg_match('/\btotal\s*games?\b/i', $ctx)) {
                    $fancyActualRuns = $tennisTotalGames;
                } elseif (preg_match('/\b(total|combined|match\s+runs|both\s+teams|total\s+goals|over\/under|total\s+points)\b/i', $ctx) && $homeRuns !== null && $awayRuns !== null) {
                    $fancyActualRuns = $homeRuns + $awayRuns;
                } elseif (!$isPlayerOrWktFancy) {
                    if ($homeRuns !== null && sports_names_match($ctx, $homeTitle)) {
                        $fancyActualRuns = $homeRuns;
                    } elseif ($awayRuns !== null && sports_names_match($ctx, $awayTitle)) {
                        $fancyActualRuns = $awayRuns;
                    }
                }
            }
        }

        if ($eventId !== '' && ($winnerCandidate !== '' || $scorecard || $homeRuns !== null || $awayRuns !== null)) {
            sports_archive_event_snapshot($pdo, [
                'event_id' => $eventId,
                'event_name' => $matchName,
                'fingerprint' => sports_match_fingerprint($etid, $matchName),
                'sport_slug' => $sportSlug,
                'etid' => $etid,
                'allpanel_gmid' => $apGmid,
                'market_ids_json' => json_encode($marketIds, JSON_UNESCAPED_UNICODE),
                'winner_name' => $winnerCandidate,
                'match_status' => $isAbandoned ? 'ABANDONED' : ($isCompleted ? 'COMPLETED' : 'LIVE'),
                'scorecard_json' => $scorecard ? json_encode($scorecard, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE) : '',
            ]);
        }

        $scoreSummaryParts = [];
        if ($homeScoreText !== '-' || $awayScoreText !== '-') {
            $scoreSummaryParts[] = "{$homeTitle}: {$homeScoreText} | {$awayTitle}: {$awayScoreText}";
        }
        if ($needText !== '') {
            $scoreSummaryParts[] = $needText;
        }

        $found = !empty($sourcesUsed) || $eventId !== '' || $winnerCandidate !== '' || $homeRuns !== null || $awayRuns !== null;

        return [
            'ok' => true,
            'found' => $found,
            'event_id' => $eventId,
            'allpanel_gmid' => $apGmid,
            'sport' => $sportSlug,
            'status' => $isAbandoned ? 'abandoned' : ($isCompleted ? 'completed' : ($found ? 'live' : 'unknown')),
            'is_completed' => $isCompleted,
            'is_abandoned' => $isAbandoned,
            'home_name' => $homeTitle,
            'away_name' => $awayTitle,
            'home_score' => $homeScoreText,
            'away_score' => $awayScoreText,
            'home_runs' => $homeRuns,
            'away_runs' => $awayRuns,
            'total_runs' => ($homeRuns !== null && $awayRuns !== null) ? ($homeRuns + $awayRuns) : null,
            'tennis_total_games' => $tennisTotalGames,
            'winner' => $matchedSelection,
            'raw_winner' => $winnerCandidate,
            'actual_runs' => $fancyActualRuns,
            'message' => $needText,
            'score_summary' => implode(' — ', $scoreSummaryParts),
            'players' => $players,
            'sources' => array_values(array_unique($sourcesUsed)),
            'raw_debug' => [
                'event_id' => $eventId,
                'allpanel_gmid' => $apGmid,
                'sport_etid' => $etid,
                'score_url_cached' => $scoreUrl,
                'market_ids' => $marketIds,
                'main_statuses' => array_values(array_unique($mainStatusCandidates)),
                'target_statuses' => array_values(array_unique($targetStatusCandidates)),
                'matched_fancy_section' => $matchedFancySection,
                'ap_sections_sample' => $apSectionsSample,
                'oexch_detail_keys' => $oexchDetailSample,
                'scorecard' => $scorecard,
            ],
        ];
    }
}

if (!function_exists('sports_parse_bet_tx')) {
    function sports_parse_bet_tx(array $t): array {
        $desc = (string)($t['description'] ?? '');
        $round = ''; $match = ''; $market = ''; $sel = ''; $btype = ''; $odds = ''; $runs = '';
        if (preg_match('/\[ROUND:([^\]]+)\]/', $desc, $m))     $round = trim($m[1]);
        if (preg_match('/\[MATCH:([^\]]+)\]/', $desc, $m))     $match = trim($m[1]);
        if (preg_match('/\[MARKET:([^\]]+)\]/', $desc, $m))    $market = trim($m[1]);
        if (preg_match('/\[SELECTION:([^\]]+)\]/', $desc, $m)) $sel = trim($m[1]);
        if (preg_match('/\[BTYPE:([^\]]+)\]/', $desc, $m))     $btype = strtoupper(trim($m[1]));
        if (preg_match('/\[ODDS:([^\]]+)\]/', $desc, $m))      $odds = trim($m[1]);
        if (preg_match('/\[RUNS:([^\]]+)\]/', $desc, $m))      $runs = trim($m[1]);

        $liability = abs((float)$t['amount']);
        $isFancy = ($runs !== '' || in_array($btype, ['YES', 'NO'], true));
        $profit = $liability;

        if ($isFancy) {
            $lineVal = 0.0;
            $bhav = 100.0;
            if (strpos($runs, '/') !== false) {
                [$lv, $bv] = explode('/', $runs, 2);
                $lineVal = (float)$lv;
                $bhav = (float)$bv > 0 ? (float)$bv : 100.0;
            } else {
                $lineVal = (float)($runs !== '' ? $runs : $odds);
            }
            $rate = $bhav / 100.0;
            $profit = ($btype === 'NO' || $btype === 'LAY')
                ? round($liability / max(0.01, $rate), 2)
                : round($liability * $rate, 2);
            $lineNumber = $lineVal;
        } elseif (substr($odds, -1) === 'p') {
            $bmVal = (float)rtrim($odds, 'p');
            $rate = max(0.01, $bmVal / 100.0);
            $profit = ($btype === 'LAY')
                ? round($liability / $rate, 2)
                : round($liability * $rate, 2);
            $lineNumber = $bmVal;
        } else {
            $dec = (float)$odds;
            if ($dec > 1.0) {
                $profit = ($btype === 'LAY')
                    ? round($liability / ($dec - 1.0), 2)
                    : round($liability * ($dec - 1.0), 2);
            }
            $lineNumber = $dec;
        }

        return [
            'tx_id'      => (int)$t['id'],
            'user_id'    => (int)$t['user_id'],
            'username'   => (string)(!empty($t['username']) ? $t['username'] : ('User #' . $t['user_id'])),
            'round'      => $round,
            'match'      => $match !== '' ? $match : 'Live Sports Match',
            'market'     => $market !== '' ? $market : 'Match Odds',
            'selection'  => $sel !== '' ? $sel : 'Selection',
            'btype'      => $btype !== '' ? $btype : 'BACK',
            'odds'       => $odds,
            'runs'       => $runs,
            'is_fancy'   => $isFancy,
            'line_val'   => $lineNumber,
            'liability'  => $liability,
            'profit'     => $profit,
            'created_at' => (string)$t['created_at'],
            'raw_desc'   => $desc,
        ];
    }
}

if (!function_exists('sports_load_open_bets')) {
    function sports_load_open_bets(PDO $pdo): array {
        $rows = $pdo->query('
            SELECT wt.id, wt.user_id, wt.type, wt.amount, wt.description, wt.created_at,
                   u.username
            FROM wallet_transactions wt
            LEFT JOIN users u ON u.id = wt.user_id
            WHERE wt.type IN ("bet_lock", "bet_win", "bet_refund")
            ORDER BY wt.id DESC
            LIMIT 1000
        ')->fetchAll(PDO::FETCH_ASSOC);

        $settledRounds = [];
        $locks = [];
        foreach ($rows as $r) {
            $desc = (string)($r['description'] ?? '');
            if (!preg_match('/\[ROUND:([^\]]+)\]/', $desc, $rm)) continue;
            $rnd = trim($rm[1]);
            $isSports = (stripos($desc, '[PROV:SPORTS]') !== false || stripos($desc, '[MATCH:') !== false);
            if (!$isSports) continue;

            if ($r['type'] === 'bet_win' || $r['type'] === 'bet_refund') {
                $settledRounds[$rnd] = true;
            } elseif ($r['type'] === 'bet_lock') {
                $locks[] = ['round' => $rnd, 'row' => $r];
            }
        }

        $open = [];
        foreach ($locks as $item) {
            if (!empty($settledRounds[$item['round']])) continue;
            $open[] = sports_parse_bet_tx($item['row']);
        }
        return $open;
    }
}

if (!function_exists('sports_settle_single_bet_tx')) {
    function sports_settle_single_bet_tx(PDO $pdo, array $bet, string $outcome, array $txCols): string {
        if (!in_array($outcome, ['WON', 'LOST', 'REFUND'], true)) {
            return 'invalid';
        }
        if ($bet['round'] === '') {
            return 'no_round';
        }

        $chk = $pdo->prepare("
            SELECT COUNT(*) FROM wallet_transactions
            WHERE user_id = ? AND type IN ('bet_win', 'bet_refund') AND description LIKE ?
        ");
        $chk->execute([$bet['user_id'], '%[ROUND:' . $bet['round'] . ']%']);
        if ((int)$chk->fetchColumn() > 0) {
            return 'already_settled';
        }

        $wSt = $pdo->prepare('SELECT COALESCE(cash_balance, 0) AS cash_balance, COALESCE(locked_exposure, 0) AS locked_exposure, COALESCE(pnl, 0) AS pnl FROM wallets WHERE user_id = ? FOR UPDATE');
        $wSt->execute([$bet['user_id']]);
        $w = $wSt->fetch(PDO::FETCH_ASSOC);
        if (!$w) {
            return 'no_wallet';
        }

        $cash = (float)$w['cash_balance'];
        $exp  = (float)$w['locked_exposure'];
        $pnl  = (float)$w['pnl'];

        $liab = (float)$bet['liability'];
        $prof = (float)$bet['profit'];
        $relExp = min($liab, $exp);
        $newExp = round(max(0.0, $exp - $relExp), 2);

        $txUid = 'STL-' . strtoupper(bin2hex(random_bytes(5)));
        $runsTag = $bet['runs'] !== '' ? (' [RUNS:' . $bet['runs'] . ']') : '';
        $baseTags = sprintf(
            '[PROV:SPORTS] [ROUND:%s] [MATCH:%s] [MARKET:%s] [SELECTION:%s] [BTYPE:%s]%s [ODDS:%s]',
            $bet['round'],
            $bet['match'],
            $bet['market'],
            $bet['selection'],
            $bet['btype'],
            $runsTag,
            $bet['odds']
        );

        if ($outcome === 'WON') {
            $payout = round($liab + $prof, 2);
            $newCash = round($cash + $payout, 2);
            $newPnl  = round($pnl + $prof, 2);
            $pdo->prepare('UPDATE wallets SET cash_balance = ?, locked_exposure = ?, pnl = ? WHERE user_id = ?')
                ->execute([$newCash, $newExp, $newPnl, $bet['user_id']]);
            $txType = 'bet_win';
            $txAmt  = $payout;
            $desc   = 'Won: ' . $bet['match'] . ' ' . $baseTags . ' (Won)';
        } elseif ($outcome === 'REFUND') {
            $newCash = round($cash + $liab, 2);
            $pdo->prepare('UPDATE wallets SET cash_balance = ?, locked_exposure = ? WHERE user_id = ?')
                ->execute([$newCash, $newExp, $bet['user_id']]);
            $txType = 'bet_refund';
            $txAmt  = $liab;
            $desc   = 'Refunded: ' . $bet['match'] . ' ' . $baseTags . ' (Refunded)';
        } else {
            $newCash = $cash;
            $newPnl  = round($pnl - $liab, 2);
            $pdo->prepare('UPDATE wallets SET locked_exposure = ?, pnl = ? WHERE user_id = ?')
                ->execute([$newExp, $newPnl, $bet['user_id']]);
            $txType = 'bet_refund';
            $txAmt  = 0.00;
            $desc   = 'Lost: ' . $bet['match'] . ' ' . $baseTags . ' (Settled)';
        }

        if (in_array('status', $txCols, true)) {
            $pdo->prepare('INSERT INTO wallet_transactions (user_id, tx_uid, type, amount, balance_after, description, status, created_at) VALUES (?, ?, ?, ?, ?, ?, "completed", NOW())')
                ->execute([$bet['user_id'], $txUid, $txType, $txAmt, $newCash, $desc]);
        } else {
            $pdo->prepare('INSERT INTO wallet_transactions (user_id, tx_uid, type, amount, balance_after, description, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())')
                ->execute([$bet['user_id'], $txUid, $txType, $txAmt, $newCash, $desc]);
        }
        return 'ok';
    }
}

if (!function_exists('sports_settle_market_group')) {
    function sports_settle_market_group(PDO $pdo, string $mMatch, string $mMarket, string $mode, string $winner, string $actualRuns): int {
        $txCols = $pdo->query('SHOW COLUMNS FROM wallet_transactions')->fetchAll(PDO::FETCH_COLUMN) ?: [];
        $openAll = sports_load_open_bets($pdo);
        $targets = array_values(array_filter($openAll, static fn($b) => $b['match'] === $mMatch && $b['market'] === $mMarket));
        if (empty($targets)) return 0;

        $settledCount = 0;
        $pdo->beginTransaction();
        try {
            foreach ($targets as $b) {
                if ($mode === 'refund') {
                    $outcome = 'REFUND';
                } elseif ($mode === 'fancy') {
                    $runsNum = (float)$actualRuns;
                    $lineVal = (float)$b['line_val'];
                    $isYes = in_array($b['btype'], ['YES', 'BACK'], true);
                    $outcome = ($runsNum >= $lineVal) ? ($isYes ? 'WON' : 'LOST') : ($isYes ? 'LOST' : 'WON');
                } else {
                    $isWinnerPick = (strcasecmp($b['selection'], $winner) === 0);
                    $isBack = ($b['btype'] === 'BACK' || $b['btype'] === 'YES');
                    $outcome = $isWinnerPick ? ($isBack ? 'WON' : 'LOST') : ($isBack ? 'LOST' : 'WON');
                }
                if (sports_settle_single_bet_tx($pdo, $b, $outcome, $txCols) === 'ok') {
                    $settledCount++;
                }
            }
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }
        return $settledCount;
    }
}

if (!function_exists('sports_auto_settle_open_bets')) {
    function sports_auto_settle_open_bets(PDO $pdo, int $maxMarkets = 15, int $maxSeconds = 12): array {
        $lockFile = sys_get_temp_dir() . '/sp_autosettle_run.lock';
        $fp = @fopen($lockFile, 'c+');
        if ($fp && !@flock($fp, LOCK_EX | LOCK_NB)) {
            @fclose($fp);
            return ['settled' => 0, 'skipped' => 0, 'checked' => 0, 'details' => ['Already running']];
        }

        $startAt = microtime(true);
        $settledTotal = 0;
        $skippedTotal = 0;
        $checkedTotal = 0;
        $details = [];

        try {
            $openBets = sports_load_open_bets($pdo);
            if (!$openBets) {
                return ['settled' => 0, 'skipped' => 0, 'checked' => 0, 'details' => []];
            }

            $groups = [];
            foreach ($openBets as $b) {
                $gk = $b['match'] . '|||' . $b['market'];
                if (!isset($groups[$gk])) {
                    $groups[$gk] = [
                        'match' => $b['match'],
                        'market' => $b['market'],
                        'is_fancy' => $b['is_fancy'],
                        'selections' => [],
                    ];
                }
                $groups[$gk]['selections'][$b['selection']] = true;
            }

            foreach ($groups as $grp) {
                if ($checkedTotal >= $maxMarkets || (microtime(true) - $startAt) >= $maxSeconds) {
                    break;
                }
                $checkedTotal++;
                $selList = array_keys($grp['selections']);
                $res = sports_fetch_result_for_control(
                    $pdo,
                    (string)$grp['match'],
                    (string)$grp['market'],
                    (bool)$grp['is_fancy'],
                    $selList
                );

                $settledThis = 0;
                if (!empty($res['is_completed'])) {
                    if (!empty($res['is_abandoned'])) {
                        $settledThis = sports_settle_market_group($pdo, $grp['match'], $grp['market'], 'refund', '', '');
                        if ($settledThis > 0) $details[] = "{$grp['match']} ({$grp['market']}): Auto-Refunded {$settledThis}";
                    } elseif ($grp['is_fancy'] && $res['actual_runs'] !== null && is_numeric($res['actual_runs'])) {
                        $runsStr = (string)$res['actual_runs'];
                        $settledThis = sports_settle_market_group($pdo, $grp['match'], $grp['market'], 'fancy', '', $runsStr);
                        if ($settledThis > 0) $details[] = "{$grp['match']} ({$grp['market']}): Auto-Settled {$settledThis} @ {$runsStr}";
                    } elseif (!$grp['is_fancy'] && !empty($res['winner'])) {
                        $matchedSel = sports_find_best_selection((string)$res['winner'], $selList);
                        if ($matchedSel !== '') {
                            $settledThis = sports_settle_market_group($pdo, $grp['match'], $grp['market'], 'odds', $matchedSel, '');
                            if ($settledThis > 0) $details[] = "{$grp['match']} ({$grp['market']}): Auto-Settled {$settledThis} — Winner: {$matchedSel}";
                        }
                    }
                }

                if ($settledThis > 0) {
                    $settledTotal += $settledThis;
                } else {
                    $skippedTotal++;
                }
            }
        } finally {
            if ($fp) {
                @flock($fp, LOCK_UN);
                @fclose($fp);
            }
        }

        return [
            'settled' => $settledTotal,
            'skipped' => $skippedTotal,
            'checked' => $checkedTotal,
            'details' => $details,
        ];
    }
}

if (!function_exists('sports_maybe_background_auto_settle')) {
    function sports_maybe_background_auto_settle(PDO $pdo): void {
        $enabled = true;
        try {
            $st = $pdo->prepare("SELECT setting_value FROM sports_control_settings WHERE setting_key = 'api_auto_settle' LIMIT 1");
            $st->execute();
            $val = $st->fetchColumn();
            if ($val !== false && $val !== null) {
                $enabled = ((string)$val === '1');
            }
        } catch (Throwable $e) {
            $enabled = true;
        }
        if (!$enabled) return;

        try {
            $hasOpen = $pdo->query("SELECT 1 FROM wallet_transactions WHERE type = 'bet_lock' AND (description LIKE '%[PROV:SPORTS]%' OR description LIKE '%[MATCH:%') LIMIT 1")->fetchColumn();
            if (!$hasOpen) return;
        } catch (Throwable $e) {
            return;
        }

        // Throttle background auto-settle to max once every 30 seconds
        $tsFile = sys_get_temp_dir() . '/sp_autosettle_ts.txt';
        $lastTs = is_file($tsFile) ? (int)@file_get_contents($tsFile) : 0;
        if ((time() - $lastTs) < 30) return;
        @file_put_contents($tsFile, (string)time(), LOCK_EX);

        $summary = sports_auto_settle_open_bets($pdo, 8, 8);
        if (!empty($summary['settled'])) {
            try {
                $pdo->prepare("
                    INSERT INTO sports_control_settings (setting_key, setting_value)
                    VALUES ('last_auto_settle_info', ?)
                    ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
                ")->execute([gmdate('Y-m-d H:i:s') . ' UTC: ' . implode(' | ', $summary['details'])]);
            } catch (Throwable $e) {}
        }
    }
}