<?php
header('Content-Type: text/html; charset=utf-8');

require_once 'functions.php';
require_once 'persiantranslate.php';
date_default_timezone_set('Asia/Tehran');

$team_id   = (int)($_GET['team_id'] ?? 0);
$team_name = $_GET['team_name'] ?? '';
$mode      = $_GET['mode'] ?? 'future';
$team_logo = $_GET['team_logo'] ?? '';
$team_logo_url = $team_logo ? 'https://lsm-static-prod.livescore.com/medium/'.$team_logo : '';

if ($team_id <= 0) { echo 'team_id نامعتبر است'; exit; }

function getJson($url){
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 12,
    CURLOPT_HTTPHEADER => ['Accept: application/json'],
  ]);
  $body = curl_exec($ch);
  $http = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);
  if ($http !== 200 || $body === false) return null;
  $data = json_decode($body, true);
  return (json_last_error() === JSON_ERROR_NONE) ? $data : null;
}

$fixtures = [];
$daysRange = ($mode === 'past') ? range(1, 60) : range(0, 30);

foreach ($daysRange as $i) {
  $offset = ($mode === 'past' ? "-$i day" : "+$i day");
  $ymd = (new DateTime($offset))->format('Ymd');
  $url = "https://prod-public-api.livescore.com/v1/api/app/date/soccer/{$ymd}/3.30";
  $d = getJson($url);
  if (!$d || empty($d['Stages'])) continue;

  foreach ($d['Stages'] as $stage) {
    if (empty($stage['Events'])) continue;

    // فارسی‌سازی نام لیگ
    $cnm = $stage['Cnm'] ?? '';
    $snm = $stage['Snm'] ?? '';
    $league = getleagues($cnm) . ' / ' . getleagues($snm);

    foreach ($stage['Events'] as $ev) {
      $homeId = $ev['T1'][0]['ID'] ?? ($ev['T1']['ID'] ?? null);
      $awayId = $ev['T2'][0]['ID'] ?? ($ev['T2']['ID'] ?? null);
      if ($homeId == $team_id || $awayId == $team_id) {

        // فارسی‌سازی نام تیم‌ها
        $homeRaw = $ev['T1'][0]['Nm'] ?? ($ev['T1']['Nm'] ?? 'Home');
        $awayRaw = $ev['T2'][0]['Nm'] ?? ($ev['T2']['Nm'] ?? 'Away');
        $home = getTeamName($homeRaw);
        $away = getTeamName($awayRaw);

        $esd = substr($ev['Esd'] ?? '', 0, 12); // YYYYMMDDHHMM
        $dt  = $esd ? DateTime::createFromFormat('YmdHi', $esd, new DateTimeZone('Asia/Tehran')) : null;
        if ($dt) $dt->setTimezone(new DateTimeZone('Asia/Tehran'));

        $hs = $ev['Tr1'] ?? ($ev['Trh'] ?? null);
        $as = $ev['Tr2'] ?? ($ev['Tra'] ?? null);
        $score = ($hs !== null && $as !== null) ? "{$hs}–{$as}" : '';

$ymdIso = sprintf('%s-%s-%s', substr($ymd,0,4), substr($ymd,4,2), substr($ymd,6,2));

$fixtures[] = [
  'ts_g'   => $dt ? $dt->format('Y-m-d H:i') : $ymdIso,
  'ts_j'   => $dt
              ? (gregorianToJalaliDate($dt->format('Y-m-d')) . ' ' . $dt->format('H:i'))
              : gregorianToJalaliDate($ymdIso),
  'league' => $league,
  'home'   => $home,
  'away'   => $away,
  'score'  => $score,
];

      }
    }
  }
}

if ($mode === 'past') {
  usort($fixtures, function ($a, $b) { return strcmp($b['ts'] ?? '', $a['ts'] ?? ''); });
}

function h($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

// تیتر صفحه را هم فارسی‌شده نشان بده
$team_name_fa = getTeamName($team_name);
$base = "team_fixtures.php?team_id={$team_id}&team_name=" . urlencode($team_name_fa)
      . ($team_logo ? "&team_logo=" . urlencode($team_logo) : "");
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>برنامه و نتایج | <?=h($team_name_fa)?> | 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&amp;family=Vazirmatn:wght@100..900&amp;display=swap" rel="stylesheet">
<style>
  :root{
    --bg1:#0b0f16; --border:rgba(255,255,255,.10);
    --text:#e8eef7; --muted:#aab5c6; --accent:#ff7a1a;
  }
  body{
    margin:0; padding:16px 16px calc(16px + env(safe-area-inset-bottom) + 72px); min-height:100dvh;
    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,.10), transparent 60%),
      radial-gradient(700px 350px at -20% 120%, rgba(60,130,246,.10), transparent 60%),
      linear-gradient(180deg, #0a111a 0%, var(--bg1) 30%, #0a1118 100%);
  }
  .container{max-width:820px;margin:0 auto}

  .card{
    background: linear-gradient(180deg, rgba(76, 175, 80, 0.06), rgba(76, 175, 80, 0.03));
    border:1px solid var(--border); border-radius:6px;
    box-shadow:0 10px 30px rgba(0,0,0,.25); backdrop-filter: blur(6px);
  }
  .header-bar{display:flex;align-items:center;justify-content:space-between;direction:ltr}
  .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));
  }

  .chips{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px; }
  .chip{
    padding:.35rem .7rem; border-radius:6px; font-weight:700; font-size:14px;
    border:1px solid var(--border); background:rgba(255,255,255,.05);
  }
  .chip-live{background:rgba(76, 175, 80, 0.2); color:#ccc; border-color:rgba(76, 175, 80, 0.5);}
  .chip-title{color:#ccc; display:flex; align-items:center; gap:8px}

  .match{background:rgba(255,255,255,.02); border:1px solid var(--border); border-radius:6px; padding:12px; margin-bottom:12px}
  .league-title{color:#ccc; font-weight:600; font-size:16px; margin-bottom:8px; display:flex; align-items:center; gap:8px}
  .teams{display:flex; align-items:center; justify-content:center; gap:10px; flex-wrap:nowrap; font-size:14px}
  .teams .score{
    font-variant-numeric:tabular-nums; font-weight:400; font-size:16px; padding:.1rem .5rem; border-radius:6px;
    background:rgba(255,255,255,.06); border:1px solid var(--border);
  }
  .minute{ margin-top:6px; display:flex; justify-content:center; font-size:13px; color:#c9d3e5; }
  
  .loading-overlay{
  position:fixed; inset:0; z-index:9999;
  background:rgba(0,0,0,.55);
  display:none; align-items:center; justify-content:center;
}
.loading-overlay.show{ display:flex; }
.loading-box{
  background:linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.03));
  border:1px solid rgba(255,255,255,.12); border-radius:12px;
  padding:18px 22px; color:#e8eef7; min-width:220px; text-align:center;
  box-shadow:0 10px 30px rgba(0,0,0,.35);
}
.spinner{
  width:42px;height:42px;border:3px solid rgba(255,255,255,.25);
  border-top-color:#4CAF50;border-radius:50%;
  margin:0 auto 12px; animation:spin 1s linear infinite;
}
@keyframes spin{ to{ transform:rotate(360deg); } }

/* 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);
}
.bottom-nav .wrap{display:flex; justify-content:space-between; gap:4px}
.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)}

  @media (max-width:600px){
    .teams{gap:8px; font-size:12px}
    .league-title{font-size:14px}
    .teams .score{font-size:12px; padding:.01rem .09rem;}
  }
</style>
</head>
<body>
  <div class="container">
    <!-- Header -->
    <header class="card header-bar px-4 py-3">
      <h1 class="text-xl md:text-2xl brand font-extrabold">LiveCube</h1>
      <div class="flex items-center gap-2">
        <a href="search_teams.php" class="px-3 py-2 rounded-md text-black" style="background:#4CAF50">بازگشت</a>
      </div>
    </header>

    <!-- Team title + mode -->
    <section class="card mt-4 p-4">
      <div class="chips">
            <span class="chip chip-title flex items-center gap-2">
              <?php if($team_logo_url): ?>
                <img src="<?=h($team_logo_url)?>" alt="" style="width:28px;height:28px;border-radius:50%;object-fit:cover;">
              <?php endif; ?>
              <?=h($team_name_fa)?>
            </span>
        <div class="flex items-center gap-2">
<a href="<?=$base?>&amp;mode=future" class="chip <?=($mode==='future'?'chip-live':'')?> mode-link">بازی‌های آینده</a>
<a href="<?=$base?>&amp;mode=past"   class="chip <?=($mode==='past'  ?'chip-live':'')?> mode-link">نتایج گذشته</a>
        </div>
      </div>

      <?php if (!$fixtures): ?>
        <p class="text-center py-6" style="color:var(--muted)">موردی یافت نشد.</p>
      <?php else: ?>
        <?php foreach ($fixtures as $m): ?>
          <div class="match">
            <div class="league-title"><?=h($m['league'])?></div>
            <div class="teams">
              <span><?=h($m['home'])?></span>
                <span class="score"><?=h($m['score'] ? convertToPersianNumbers($m['score']) : 'vs')?></span>
              <span><?=h($m['away'])?></span>
            </div>
              <?php
                  $ts = $m['ts_j'] ?? ($m['ts'] ?? '');
                  [$d, $t] = array_pad(explode(' ', trim($ts), 2), 2, '');
                  $d = convertToPersianNumbers(str_replace('-', '/', $d));
                  $t = convertToPersianNumbers($t);
                ?>
                <div class="minute">📆 <span class="date"><?=$d?></span> 🕚 <span class="date"><?=$t?></span></div>

          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
  
  <div id="loading" class="loading-overlay" aria-hidden="true">
  <div class="loading-box">
    <div class="spinner"></div>
    <div>در حال دریافت اطلاعات…</div>
  </div>
</div>
<script>
  (function(){
    const overlay = document.getElementById('loading');
    document.addEventListener('click', function(e){
      const a = e.target.closest('a.mode-link');
      if(!a) return;
      e.preventDefault();
      overlay.classList.add('show');
      setTimeout(function(){ window.location.href = a.href; }, 30);
    });
  })();
</script>
<?php $active='calendar'; include __DIR__.'/parts/bottom-nav.php'; ?>

</body>
</html>
