<?php
declare(strict_types=1);
ini_set('display_errors', '1');
error_reporting(E_ALL);

require_once 'persiantranslate.php';

$eid = filter_input(INPUT_GET, 'eid', FILTER_SANITIZE_NUMBER_INT) ?? '';
if (empty($eid)) {
    die("لطفاً ID بازی را مشخص کنید: ?eid=123456");
}

// دریافت اطلاعات تیم‌ها از API بازی
function get_team_names_from_match(string $eid): array {
    $urls = [
        "https://prod-public-api.livescore.com/v1/api/app/match/soccer/$eid?MD=1&locale=en",
        "https://prod-public-api.livescore.com/v1/api/app/details/soccer/$eid?MD=1&locale=en",
        "https://prod-public-api.livescore.com/v1/api/app/incidents/soccer/$eid?MD=1&locale=en",
        "https://prod-public-api.livescore.com/v1/api/app/scoreboard/soccer/$eid?MD=1&locale=en"
    ];
    
    foreach ($urls as $url) {
        $response = @file_get_contents($url);
        if ($response === false) {
            continue;
        }
        
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE || empty($data)) {
            continue;
        }

        // بررسی مستقیم T1 و T2
        if (isset($data['T1'][0]['Nm'], $data['T2'][0]['Nm'])) {
            return [
                $data['T1'][0]['Nm'] ?? 'تیم میزبان',
                $data['T2'][0]['Nm'] ?? 'تیم مهمان',
                isset($data['T1'][0]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$data['T1'][0]['Img']}" : '',
                isset($data['T2'][0]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$data['T2'][0]['Img']}" : '',
                isset($data['Tr1'], $data['Tr2']) ? ($data['Tr1'] . ' - ' . $data['Tr2']) : '—',
                isset($data['Eps']) ? getStatusText($data['Eps']) : 'نامشخص'
            ];
        }

        // بررسی Teams
        if (isset($data['Teams'][0]['Nm'], $data['Teams'][1]['Nm'])) {
            return [
                $data['Teams'][0]['Nm'] ?? 'تیم میزبان',
                $data['Teams'][1]['Nm'] ?? 'تیم مهمان',
                isset($data['Teams'][0]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$data['Teams'][0]['Img']}" : '',
                isset($data['Teams'][1]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$data['Teams'][1]['Img']}" : '',
                isset($data['Tr1'], $data['Tr2']) ? ($data['Tr1'] . ' - ' . $data['Tr2']) : '—',
                isset($data['Eps']) ? getStatusText($data['Eps']) : 'نامشخص'
            ];
        }

        // بررسی در Stages و Events
        if (isset($data['Stages']) && is_array($data['Stages'])) {
            foreach ($data['Stages'] as $stage) {
                if (isset($stage['Events']) && is_array($stage['Events'])) {
                    foreach ($stage['Events'] as $event) {
                        if (isset($event['Eid']) && $event['Eid'] == $eid) {
                            return [
                                $event['T1'][0]['Nm'] ?? 'تیم میزبان',
                                $event['T2'][0]['Nm'] ?? 'تیم مهمان',
                                isset($event['T1'][0]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$event['T1'][0]['Img']}" : '',
                                isset($event['T2'][0]['Img']) ? "https://lsm-static-prod.livescore.com/medium/{$event['T2'][0]['Img']}" : '',
                                isset($event['Tr1'], $event['Tr2']) ? ($event['Tr1'] . ' - ' . $event['Tr2']) : '—',
                                isset($event['Eps']) ? getStatusText($event['Eps']) : 'نامشخص'
                            ];
                        }
                    }
                }
            }
        }
    }

    global $error_message;
    $error_message = "نام تیم‌ها یافت نشد. احتمالاً API داده‌ای برای این بازی ندارد.";
    return ['تیم میزبان', 'تیم مهمان', '', '', '—', 'نامشخص'];
}

// تابع برای تبدیل وضعیت بازی به متن
function getStatusText(string $eps): string {
    $statusMap = [
        'NS' => 'شروع نشده',
        '1H' => 'نیمه اول',
        'HT' => 'بین دو نیمه',
        '2H' => 'نیمه دوم',
        'FT' => 'پایان',
        'AET' => 'وقت اضافه',
        'PEN' => 'پنالتی'
    ];
    return $statusMap[$eps] ?? (is_numeric($eps) ? $eps . "'" : $eps);
}

// دریافت اطلاعات تیم‌ها و نتیجه
[$homeTeamName, $awayTeamName, $homeLogo, $awayLogo, $score, $status] = get_team_names_from_match($eid);
$homeTeamName = getTeamName($homeTeamName);
$awayTeamName = getTeamName($awayTeamName);

// دریافت داده‌های آماری
function fetch_stats(string $eid): array {
    $url = "https://prod-public-api.livescore.com/v1/api/app/statistics/soccer/$eid?MD=1&locale=en";
    $response = @file_get_contents($url);
    
    if ($response === false) {
        global $error_message;
        $error_message = "خطا در دریافت آمار از API";
        return [];
    }
    
    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        global $error_message;
        $error_message = "خطا در پردازش داده‌های دریافتی";
        return [];
    }
    
    return $data;
}

$statNames = [
    'Tnb'  => 'تیم',
    'Fls'  => 'خطاها',
    'Ths'  => 'اوت‌ها',
    'Ofs'  => 'آفساید',
    'Crs'  => 'کرنرها',
    'Ycs'  => 'کارت زرد',
    'Rcs'  => 'کارت قرمز',
    'YRcs' => 'کارت زرد دوم',
    'Shof' => 'شوت خارج چارچوب',
    'Shwd' => 'شوت به تیرک',
    'Shbl' => 'شوت بلوکه‌شده',
    'Att'  => 'حملات',
    'Gks'  => 'سیو دروازه‌بان',
    'Goa'  => 'موقعیت گل',
    'Pss'  => 'مالکیت توپ (%)',
    'Cos'  => 'ضربات ایستگاهی',
    'Shon' => 'شوت در چارچوب'
];

function displayStats(array $statsData, array $statNames, string $title, string $homeTeamName, string $awayTeamName, bool $isTotal = false): string {
    if (empty($statsData)) {
        return "<div class='text-[var(--muted)] p-4 text-center'>📭 داده‌ای برای $title وجود ندارد</div>";
    }

    $html = "<div class='stats-title'>$title</div>";

    foreach ($statsData[0] as $key => $value) {
        if ($key === 'Tnb') continue;

        $persianName = $statNames[$key] ?? $key;
        $team1Value = (int)($statsData[0][$key] ?? 0);
        $team2Value = (int)($statsData[1][$key] ?? 0);

        $total = $team1Value + $team2Value;
        $team1Percent = $total > 0 ? ($team1Value / $total) * 100 : 0;
        $team2Percent = $total > 0 ? ($team2Value / $total) * 100 : 0;

        $html .= "
        <div class='stats-item'>
            <div class='label'>".htmlspecialchars($persianName)."</div>
            <div class='stats-bar'>
                <div class='value'>".convertToPersianNumbers($team1Value)."</div>
                <div class='bar'>
                    <div class='home' style='width: {$team1Percent}%'></div>
                    <div class='away' style='width: {$team2Percent}%'></div>
                </div>
                <div class='value'>".convertToPersianNumbers($team2Value)."</div>
            </div>
        </div>
        ";
    }

    return $html;
}

function convertToPersianNumbers($string): string {
    $en = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    $fa = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    return str_replace($en, $fa, (string)$string);
}

$data = fetch_stats($eid);
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>آمار بازی - LiveCube</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@200;300;400;500;600;700&family=Vazirmatn:wght@100..900&display=swap" rel="stylesheet">

    <style>
        :root {
            --bg1: #0b0f16;
            --border: rgba(255,255,255,.12);
            --text: #e8eef7;
            --muted: #aab5c6;
            --accent: #ff7a1a;
            --primary: #4CAF50;
        }
        body {
            margin: 0;
            padding: 24px 16px calc(24px + env(safe-area-inset-bottom) + 72px);
            min-height: 100dvh;
            font-family:'Bai Jamjuree','Vazirmatn',sans-serif;
            color: var(--text);
            background:
                radial-gradient(900px 500px at 110% -20%, rgba(255,122,26,.12), transparent 60%),
                radial-gradient(700px 350px at -20% 120%, rgba(60,130,246,.12), transparent 60%),
                linear-gradient(180deg, #0a111a 0%, var(--bg1) 30%, #0a1118 100%);
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .container{max-width:820px;margin:0 auto}
        .card {
            background: linear-gradient(180deg, rgba(76,175,80,0.08), rgba(76,175,80,0.04));
            border: 1px solid var(--border);
            border-radius: 8px;
            box-shadow: 0 12px 32px rgba(0,0,0,.2);
            backdrop-filter: blur(8px);
            width: 100%;
            margin-bottom: 16px;
        }
        .header-bar {
            padding: 16px;
            text-align: center;
        }
        .brand {
          background: linear-gradient(90deg, #2E7D32 0%, #4CAF50 40%, #B2FF59 75%, #E8FFF7 100%);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
          filter: drop-shadow(0 2px 10px rgba(76,175,80,.25));
        }

        .match-result {
            background: linear-gradient(90deg, rgba(76,175,80,0.3), rgba(76,175,80,0.15));
            border: 1px solid var(--border);
            border-radius: 8px;
            padding: 14px;
            margin-bottom: 16px;
        }
        .teams {
            display: grid;
            grid-template-columns: 32px 1fr auto 1fr 32px;
            align-items: center;
            column-gap: 10px;
            font-size: 15px;
            width: 100%;
        }
        .teams .score {
            width: 60px;
            text-align: center;
            font-variant-numeric: tabular-nums;
            font-weight: 600;
            font-size: 15px;
            padding: 0.2rem 0.6rem;
            border-radius: 6px;
            background: rgba(255,255,255,.08);
            border: 1px solid var(--border);
            justify-self: center;
        }
        .team-name {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            min-width: 0;
        }
        .home-name {
            text-align: right;
            justify-self: end;
            margin: 0;
        }
        .away-name {
            text-align: left;
            justify-self: start;
            margin: 0;
        }
        .team-logo {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            object-fit: cover;
            display: block;
            border: 1px solid var(--border);
        }
        .minute {
            margin-top: 8px;
            display: flex;
            justify-content: center;
            font-size: 14px;
            color: var(--muted);
            text-align: center;
        }
        .stats-section {
            padding: 16px;
        }
        .stats-title {
            font-size: 16px;
            font-weight: 600;
            color: var(--primary);
            text-align: center;
            margin-bottom: 16px;
        }
        .stats-item {
            margin-bottom: 16px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .stats-item .label {
            font-size: 12px;
            font-weight: 500;
            color: var(--muted);
            margin-bottom: 8px;
            text-align: center;
        }
        .stats-bar {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            max-width: 400px;
            font-size: 14px;
            color: var(--text);
        }
        .stats-bar .value {
            width: 40px;
            text-align: center;
            font-weight: 600;
        }
        .stats-bar .bar {
            flex: 1;
            height: 12px;
            border-radius: 6px;
            background: rgba(255,255,255,0.1);
            margin: 0 12px;
            overflow: hidden;
            display: flex;
        }
        .stats-bar .bar .home {
            background: rgba(255, 200, 55, 0.9);
            height: 100%;
        }
        .stats-bar .bar .away {
            background: rgba(255, 87, 34, 0.9);
            height: 100%;
            margin-left: auto;
        }
        .back-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            border-radius: 6px;
            background: linear-gradient(90deg, rgba(76,175,80,0.2), rgba(76,175,80,0.1));
            border: 1px solid var(--border);
            color: var(--text);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 16px auto;
            display: block;
            text-align: center;
        }
        .back-btn:hover {
            background: linear-gradient(90deg, rgba(76,175,80,0.4), rgba(76,175,80,0.2));
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(76,175,80,0.25);
        }
        
/* Bottom Navigation (یکسان با سایر صفحات) */
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 50;
  background: rgba(10,17,26,.85);
  border-top: 1px solid var(--border);
  backdrop-filter: blur(8px);
  width: 100%;
}

.bottom-nav .wrap {
  display: flex;
  justify-content: space-between;
  gap: 4px;
  max-width: 900px;   /* هم‌قد container صفحات دیگر */
  margin: 0 auto;
  padding: 0 12px;
}

.bottom-nav a.item {
  flex: 1;
  padding: 8px 0 10px;
  text-align: center;
  font-size: 12px;
  color: var(--muted);
  text-decoration: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.bottom-nav a.item i { font-size: 18px; }
.bottom-nav a.item.active { color: #4CAF50; }
.bottom-nav .safe { height: env(safe-area-inset-bottom); }

        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        .loading::after {
            content: '';
            width: 40px;
            height: 40px;
            border: 4px solid var(--primary);
            border-top-color: transparent;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
@media (max-width: 600px) {
    .brand { font-size: 2rem; }
    .teams { font-size: 14px; }
    .teams .score { font-size: 16px; padding: 4px 10px; }
    .team-logo { width: 36px; height: 36px; }
    .stats-title { font-size: 16px; }
    .stats-bar { font-size: 12px; }
    .stats-bar .value { width: 36px; }
    .stats-item .label { font-size: 13px; }
    .bottom-nav .wrap {
        gap: 6px; /* کاهش فاصله در صفحه‌های کوچک */
        padding: 0 4px;
    }
    .bottom-nav a.item {
        min-width: 50px; /* عرض کمتر برای صفحه‌های کوچک */
        max-width: 80px;
        padding: 6px 2px 8px;
        font-size: 11px;
    }
    .bottom-nav a.item i {
        font-size: 16px; /* کاهش اندازه آیکون */
    }
}
    </style>
</head>
<body>
    <div class="loading" id="loading"></div>
    <div class="container">
        <!-- Header -->
<header class="card header-bar px-4 py-3 flex items-center justify-end">
    <h1 class="text-xl md:text-2xl brand font-extrabold">LiveCube</h1>
</header>


        <!-- نتیجه بازی -->
        <div class="card match-result mt-2">
            <div class="teams">
                <img src="<?= htmlspecialchars($homeLogo) ?>" class="team-logo" alt="<?= htmlspecialchars($homeTeamName) ?>">
                <span class="team-name home-name"><?= htmlspecialchars($homeTeamName) ?></span>
                <span class="score"><?= htmlspecialchars(convertToPersianNumbers($score)) ?></span>
                <span class="team-name away-name"><?= htmlspecialchars($awayTeamName) ?></span>
                <img src="<?= htmlspecialchars($awayLogo) ?>" class="team-logo" alt="<?= htmlspecialchars($awayTeamName) ?>">
            </div>
            <div class="minute"><?= htmlspecialchars($status) ?></div>
        </div>

        <!-- آمار بازی -->
        <?php if (isset($error_message)): ?>
            <div class="card stats-section">
                <div class="text-[var(--muted)] p-4 text-center">❌ <?= htmlspecialchars($error_message) ?></div>
            </div>
        <?php elseif (empty($data)): ?>
            <div class="card stats-section">
                <div class="text-[var(--muted)] p-4 text-center">📭 داده‌ای دریافت نشد</div>
            </div>
        <?php else: ?>
            <?php if (isset($data['PStat'][0]) && is_array($data['PStat'][0])): ?>
                <div class="card stats-section">
                    <?= displayStats([$data['PStat'][0][1], $data['PStat'][0][2]], $statNames, 'آمار نیمه اول', $homeTeamName, $awayTeamName) ?>
                </div>
            <?php endif; ?>
            <?php if (isset($data['PStat'][1]) && is_array($data['PStat'][1])): ?>
                <div class="card stats-section">
                    <?= displayStats([$data['PStat'][1][1], $data['PStat'][1][2]], $statNames, 'آمار نیمه دوم', $homeTeamName, $awayTeamName) ?>
                </div>
            <?php endif; ?>
            <?php if (isset($data['Stat']) && is_array($data['Stat'])): ?>
                <div class="card stats-section">
                    <?= displayStats($data['Stat'], $statNames, 'آمار کلی بازی', $homeTeamName, $awayTeamName, true) ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <script>
        window.addEventListener('load', () => {
            document.getElementById('loading').style.display = 'none';
        });
    </script>
      
<?php include __DIR__.'/parts/bottom-nav.php'; ?>
</body>
</html>