<?php
/**
 * IFF Scoreboard Helpers — loaded as mu-plugin, always wins over WPCode snippets
 */

// Force-define uzsl_short_name
function uzsl_short_name($name) {
    $words = explode(' ', trim($name));
    return count($words) <= 2 ? $name : $words[0] . ' ' . $words[1];
}

// Force-define get_uzbek_league_scores
function get_uzbek_league_scores() {
    $cached = get_transient('uzb_superliga_scores');
    if ($cached !== false) return $cached;
    $results = [];
    foreach (['eventsnextleague', 'eventspastleague'] as $ep) {
        $resp = wp_remote_get("https://www.thesportsdb.com/api/v1/json/3/{$ep}.php?id=4794", ['timeout' => 3]);
        if (is_wp_error($resp)) continue;
        $data = json_decode(wp_remote_retrieve_body($resp), true);
        if (!empty($data['events'])) $results = array_merge($results, array_slice($data['events'], 0, 8));
    }
    set_transient('uzb_superliga_scores', $results, 25 * MINUTE_IN_SECONDS);
    return $results;
}

// Force-define get_turkish_league_scores
function get_turkish_league_scores() {
    $cached = get_transient('tsl_scores');
    if ($cached !== false) return $cached;
    $results = [];
    foreach (['eventsnextleague', 'eventspastleague'] as $ep) {
        $resp = wp_remote_get("https://www.thesportsdb.com/api/v1/json/3/{$ep}.php?id=4339", ['timeout' => 3]);
        if (is_wp_error($resp)) continue;
        $data = json_decode(wp_remote_retrieve_body($resp), true);
        if (!empty($data['events'])) $results = array_merge($results, array_slice($data['events'], 0, 8));
    }
    set_transient('tsl_scores', $results, 25 * MINUTE_IN_SECONDS);
    return $results;
}

// Force-define build_uzbek_scoreboard — handles NS status from TheSportsDB
function build_uzbek_scoreboard($matches) {
    $html = '';
    foreach ($matches as $match) {
        $status     = trim($match['strStatus'] ?? '');
        $home_name  = $match['strHomeTeam'] ?? '';
        $away_name  = $match['strAwayTeam'] ?? '';
        $home_badge = $match['strHomeTeamBadge'] ?? '';
        $away_badge = $match['strAwayTeamBadge'] ?? '';
        $home_short = uzsl_short_name($home_name);
        $away_short = uzsl_short_name($away_name);

        if ($status === 'Match Finished') {
            $score_display = ($match['intHomeScore'] ?? '-') . ':' . ($match['intAwayScore'] ?? '-');
            $score_color   = '#333';
        } elseif (stripos($status, 'progress') !== false || stripos($status, 'live') !== false || stripos($status, 'half') !== false) {
            $score_display = ($match['intHomeScore'] ?? 0) . ':' . ($match['intAwayScore'] ?? 0);
            $score_color   = '#c00';
        } elseif (in_array($status, ['Not Started', 'NS', 'Scheduled', 'Pre Match', 'TBD'], true) || $status === '') {
            if (!empty($match['strTimeLocal']))    $local_time = substr($match['strTimeLocal'], 0, 5);
            elseif (!empty($match['strTime']))     $local_time = substr($match['strTime'], 0, 5);
            else                                   $local_time = '--:--';
            $score_display = $local_time;
            $score_color   = '#999';
        } else {
            continue;
        }

        $home_img = $home_badge ? '<img src="' . esc_url($home_badge) . '" alt="" loading="lazy" style="width:28px;height:28px;object-fit:contain;flex-shrink:0">' : '<span style="width:28px;height:28px;flex-shrink:0"></span>';
        $away_img = $away_badge ? '<img src="' . esc_url($away_badge) . '" alt="" loading="lazy" style="width:28px;height:28px;object-fit:contain;flex-shrink:0">' : '<span style="width:28px;height:28px;flex-shrink:0"></span>';

        $html .= '<div style="display:flex;align-items:center;padding:10px 5px;border-bottom:1px solid #eee;gap:8px">'
            . $home_img
            . '<span class="iff-team-name" style="font-size:13px;font-weight:bold;color:#333;flex:1;min-width:0;text-align:right;white-space:normal;overflow-wrap:break-word;word-break:break-word;line-height:1.25">' . esc_html($home_short) . '</span>'
            . '<span style="font-size:14px;font-weight:bold;color:' . $score_color . ';min-width:45px;text-align:center;flex-shrink:0">' . esc_html($score_display) . '</span>'
            . '<span class="iff-team-name" style="font-size:13px;font-weight:bold;color:#333;flex:1;min-width:0;text-align:left;white-space:normal;overflow-wrap:break-word;word-break:break-word;line-height:1.25">' . esc_html($away_short) . '</span>'
            . $away_img
            . '</div>';
    }
    if (empty($html)) {
        $html = '<div style="padding:10px;color:#666;font-size:12px;text-align:center">Ўйинлар йўқ</div>';
    }
    return $html;
}


function get_world_cup_scores() {
    $cache_file = WP_CONTENT_DIR . '/cache/wc_scores_v1.json';

    $stale = [];
    if (file_exists($cache_file)) {
        $obj = json_decode(file_get_contents($cache_file), true);
        if (is_array($obj) && !empty($obj)) $stale = $obj;
    }

    if (!empty($stale) && (time() - filemtime($cache_file)) < 300) {
        return $stale;
    }

    $matches = [];
    // Explicit date window instead of ESPN's implicit "today" — otherwise rest days between
    // fixtures return nothing at all, with no way to show recent results until the next match.
    // Uses wp_remote_get() (not raw curl_init) so it works regardless of whether the PHP
    // cURL extension is loaded for this SAPI — WordPress falls back to the streams transport.
    $from = date('Ymd', strtotime('-3 days'));
    $to   = date('Ymd', strtotime('+3 days'));
    $resp = wp_remote_get("https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world/scoreboard?dates={$from}-{$to}", [
        'timeout'    => 3,
        'user-agent' => 'Mozilla/5.0',
    ]);
    if (!is_wp_error($resp)) {
        $raw = wp_remote_retrieve_body($resp);
        if ($raw) {
            $data = json_decode($raw, true);
            foreach (($data['events'] ?? []) as $e) {
                $comps = $e['competitions'][0] ?? [];
                $teams = $comps['competitors'] ?? [];
                $home = $away = ['team' => ['displayName' => '?', 'shortDisplayName' => '?'], 'score' => ''];
                foreach ($teams as $t) {
                    if ($t['homeAway'] === 'home') $home = $t;
                    else $away = $t;
                }
                $group = '';
                foreach (($comps['notes'] ?? []) as $note) {
                    if (!empty($note['headline'])) { $group = $note['headline']; break; }
                }
                $kick = '';
                if (!empty($e['date'])) {
                    $kick = gmdate('H:i', strtotime($e['date']) + 5 * 3600);
                }
                $matches[] = [
                    'home'   => $home['team']['shortDisplayName'] ?? $home['team']['displayName'],
                    'away'   => $away['team']['shortDisplayName'] ?? $away['team']['displayName'],
                    'hscore' => $home['score'] ?? '',
                    'ascore' => $away['score'] ?? '',
                    'state'  => $e['status']['type']['state'] ?? 'pre',
                    'clock'  => $e['status']['displayClock'] ?? '',
                    'group'  => $group,
                    'kick'   => $kick,
                    'venue'  => $comps['venue']['address']['city'] ?? '',
                ];
            }
            $matches = array_slice($matches, 0, 8);
        }
    }

    if (!empty($matches)) {
        @file_put_contents($cache_file, json_encode($matches));
        return $matches;
    }
    return $stale;
}


function build_wc_scoreboard($matches) {
    if (empty($matches)) return '<p style="font-size:11px;color:#999;text-align:center;margin:5px 0;">Ўйинлар йўқ</p>';
    $html = '';
    foreach ($matches as $m) {
        $state = $m['state'];

        if ($state === 'post') {
            $score  = esc_html($m['hscore']) . ':' . esc_html($m['ascore']);
            $sc     = '#333';
            $detail = '<span style="font-size:9px;color:#888;font-weight:600;">FT</span>';
        } elseif ($state === 'in') {
            $score  = esc_html($m['hscore']) . ':' . esc_html($m['ascore']);
            $sc     = '#c00';
            $clock  = !empty($m['clock']) ? esc_html($m['clock']) : '';
            $apos   = "'";
            $detail = $clock
                ? "<span style=\"font-size:9px;color:#c00;font-weight:700;\">" . $clock . $apos . "</span>"
                : '<span style="font-size:9px;color:#c00;">&#9679;</span>';
        } else {
            $score  = !empty($m['kick']) ? esc_html($m['kick']) : 'vs';
            $sc     = '#555';
            $city   = !empty($m['venue']) ? esc_html($m['venue']) : '';
            $detail = $city ? '<span style="font-size:9px;color:#aaa;">' . $city . '</span>' : '';
        }

        $group_label = !empty($m['group'])
            ? '<span style="font-size:9px;color:#888;font-weight:600;text-transform:uppercase;letter-spacing:.4px;">' . esc_html($m['group']) . '</span>'
            : '';

        $html .= '<div style="padding:4px 0;border-bottom:1px solid #f0f0f0;">'
            . '<div style="display:flex;align-items:center;font-size:11px;gap:3px;">'
            . '<span class="iff-team-name" style="flex:1;min-width:0;text-align:right;overflow-wrap:break-word;word-break:break-word;white-space:normal;line-height:1.25;color:#333;">' . esc_html($m['home']) . '</span>'
            . '<span style="font-weight:700;color:' . $sc . ';padding:0 6px;flex-shrink:0;min-width:34px;text-align:center;">' . $score . '</span>'
            . '<span class="iff-team-name" style="flex:1;min-width:0;overflow-wrap:break-word;word-break:break-word;white-space:normal;line-height:1.25;color:#333;">' . esc_html($m['away']) . '</span>'
            . '</div>';

        if ($group_label || $detail) {
            $html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:1px;">'
                . $group_label
                . $detail
                . '</div>';
        }

        $html .= '</div>';
    }
    return $html;
}


// Override get_league_scores — trusts the API instead of guessing by month
if (!function_exists('get_league_scores')) {
function get_league_scores($league_code, $cache_key) {
    $cached = get_transient($cache_key);
    if ($cached !== false) return $cached;

    // Try file-based stale cache first
    $file = WP_CONTENT_DIR . '/cache/league_' . md5($cache_key) . '.json';
    if (file_exists($file) && (time() - filemtime($file)) < 3600) {
        $data = @json_decode(file_get_contents($file), true);
        if (is_array($data)) return $data;
    }

    // Actually fetch (short timeout; return stale/empty on failure)
    $api_key = get_option('iff_football_data_key', '');
    if (!$api_key) { return []; }

    $today = date('Y-m-d');
    $week  = date('Y-m-d', strtotime('+7 days'));
    $url   = "https://api.football-data.org/v4/competitions/{$league_code}/matches?dateFrom={$today}&dateTo={$week}";
    $resp  = wp_remote_get($url, ['timeout' => 3, 'headers' => ['X-Auth-Token' => $api_key]]);

    if (is_wp_error($resp)) {
        // Return stale file data if available
        if (file_exists($file)) {
            $data = @json_decode(file_get_contents($file), true);
            if (is_array($data)) return $data;
        }
        set_transient($cache_key, [], 60);
        return [];
    }

    $body    = json_decode(wp_remote_retrieve_body($resp), true);
    $matches = array_slice($body['matches'] ?? [], 0, 8);
    set_transient($cache_key, $matches, 25 * MINUTE_IN_SECONDS);
    @file_put_contents($file, json_encode($matches));
    return $matches;
}
}


// ── WC 2026 full-page shortcode ─────────────────────────────────────────────
function get_wc_full_schedule() {
    $cache_file = WP_CONTENT_DIR . '/cache/wc_full_schedule_v1.json';

    // Always load stale first — used as fallback if ESPN fails
    $stale = [];
    if (file_exists($cache_file)) {
        $raw_cache = file_get_contents($cache_file);
        $parsed    = json_decode($raw_cache, true);
        if (is_array($parsed) && !empty($parsed)) $stale = $parsed;
    }

    // Serve from cache if < 1 hour old
    if (!empty($stale) && file_exists($cache_file) && (time() - filemtime($cache_file)) < 3600) {
        return $stale;
    }

    // Fetch from ESPN: today + 8 days (via wp_remote_get, not raw curl_init — see get_world_cup_scores())
    $days = [];
    $from = date('Ymd');
    $to   = date('Ymd', strtotime('+8 days'));
    $url  = "https://site.api.espn.com/apis/site/v2/sports/soccer/fifa.world/scoreboard?dates={$from}-{$to}";
    $resp = wp_remote_get($url, [
        'timeout'    => 8,
        'user-agent' => 'Mozilla/5.0',
    ]);
    if (!is_wp_error($resp)) {
        $raw = wp_remote_retrieve_body($resp);
        if ($raw) {
            $data = json_decode($raw, true);
            foreach (($data['events'] ?? []) as $e) {
                $comps = $e['competitions'][0] ?? [];
                $teams = $comps['competitors'] ?? [];
                $home = $away = ['team' => ['displayName' => '?', 'shortDisplayName' => '?'], 'score' => ''];
                foreach ($teams as $t) {
                    if ($t['homeAway'] === 'home') $home = $t;
                    else $away = $t;
                }
                $group = '';
                foreach (($comps['notes'] ?? []) as $note) {
                    if (!empty($note['headline'])) { $group = $note['headline']; break; }
                }
                $kick = $day = '';
                if (!empty($e['date'])) {
                    $ts   = strtotime($e['date']);
                    $kick = gmdate('H:i', $ts + 5 * 3600);
                    $day  = gmdate('Y-m-d', $ts + 5 * 3600);
                }
                if (!$day) continue;
                $days[$day][] = [
                    'home'   => $home['team']['shortDisplayName'] ?? $home['team']['displayName'],
                    'away'   => $away['team']['shortDisplayName'] ?? $away['team']['displayName'],
                    'hscore' => $home['score'] ?? '',
                    'ascore' => $away['score'] ?? '',
                    'state'  => $e['status']['type']['state'] ?? 'pre',
                    'clock'  => $e['status']['displayClock'] ?? '',
                    'group'  => $group,
                    'kick'   => $kick,
                    'venue'  => $comps['venue']['fullName'] ?? ($comps['venue']['address']['city'] ?? ''),
                ];
            }
        }
    }

    // Persist new data only if non-empty
    if (!empty($days)) {
        @file_put_contents($cache_file, json_encode($days, JSON_UNESCAPED_UNICODE));
        return $days;
    }

    // ESPN failed or returned nothing — serve stale
    return $stale;
}


function wc2026_table_shortcode($atts) {
    $schedule = get_wc_full_schedule();
    $today    = gmdate('Y-m-d', time() + 5*3600);

    ob_start(); ?>
    <style>
    .wc-page { max-width:760px; margin:0 auto; font-family:'Segoe UI',Arial,sans-serif; }
    .wc-page h1 { font-size:22px; font-weight:700; margin-bottom:20px; display:flex; align-items:center; gap:10px; }
    .wc-day-header { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:2px; color:#666; padding:12px 0 6px; border-bottom:2px solid #111; margin-top:20px; }
    .wc-match { display:flex; align-items:center; padding:8px 0; border-bottom:1px solid #eee; gap:6px; }
    .wc-match .grp { font-size:9px; font-weight:700; color:#888; text-transform:uppercase; width:52px; flex-shrink:0; }
    .wc-match .team { flex:1; font-size:13px; font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    .wc-match .team.home { text-align:right; }
    .wc-match .score { font-size:14px; font-weight:700; min-width:42px; text-align:center; flex-shrink:0; }
    .wc-match .score.live { color:#c00; }
    .wc-match .score.pre  { color:#555; font-size:12px; }
    .wc-match .venue { font-size:9px; color:#aaa; min-width:80px; text-align:right; flex-shrink:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
    </style>
    <div class="wc-page">
      <h1><span>&#127942;</span> ЖЧ 2026 — Жадвал</h1>
      <?php if (empty($schedule)): ?>
        <p style="color:#999;">Маълумот топилмади.</p>
      <?php else:
        ksort($schedule);
        foreach ($schedule as $day => $matches):
          $label = ($day === $today) ? 'Бугун — ' . date('d.m.Y', strtotime($day)) : date('d.m.Y', strtotime($day)) . ' — ' . (new DateTime($day))->format('l'); ?>
          <div class="wc-day-header"><?= esc_html($label) ?></div>
          <?php foreach ($matches as $m):
            $state = $m['state'];
            if ($state === 'post') {
                $score = esc_html($m['hscore']) . ':' . esc_html($m['ascore']);
                $cls   = 'score';
                $sub   = 'FT';
            } elseif ($state === 'in') {
                $score = esc_html($m['hscore']) . ':' . esc_html($m['ascore']);
                $cls   = 'score live';
                $apos  = "'";
                $sub   = !empty($m['clock']) ? esc_html($m['clock']) . $apos : '&#9679;';
            } else {
                $score = esc_html($m['kick']) ?: '–:–';
                $cls   = 'score pre';
                $sub   = '';
            } ?>
            <div class="wc-match">
              <span class="grp"><?= esc_html($m['group']) ?></span>
              <span class="team home"><?= esc_html($m['home']) ?></span>
              <span class="<?= $cls ?>">
                <?= $score ?>
                <?php if ($sub): ?><br><small style="font-size:9px;font-weight:400;"><?= $sub ?></small><?php endif ?>
              </span>
              <span class="team"><?= esc_html($m['away']) ?></span>
              <span class="venue"><?= esc_html($m['venue']) ?></span>
            </div>
          <?php endforeach; ?>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('wc2026_table', 'wc2026_table_shortcode');

