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

require_once 'functions.php';
require_once 'persiantranslate.php';

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

function normalizeFa($s){
  $s = trim($s);
  return str_replace(['ي','ك','ۀ','ؤ','إ','أ','ٱ','‌','‏'], ['ی','ک','ه','و','ا','ا','ا','',''], $s);
}

// رومن‌سازی سادهٔ فارسی -> انگلیسی (fallback)
function fa_translit($s){
  $special = [
    'استقلال'=>'Esteghlal','پرسپولیس'=>'Persepolis','سپاهان'=>'Sepahan','تراکتور'=>'Tractor',
    'فولاد'=>'Foolad','ذوب آهن'=>'Zob Ahan','صنعت نفت'=>'Sanat Naft','گل گهر'=>'Gol Gohar',
    'ملوان'=>'Malavan','سایپا'=>'Saipa','نفت مسجدسلیمان'=>'Naft Masjed Soleyman','نساجی'=>'Nassaji',
    'مس رفسنجان'=>'Mes Rafsanjan','مس کرمان'=>'Mes Kerman','لیورپول'=>'Liverpool',
  ];
  $sN = normalizeFa($s);
  foreach ($special as $fa=>$en){ if (mb_strpos($sN,$fa)!==false) return $en; }

  $map = ['ا'=>'a','ب'=>'b','پ'=>'p','ت'=>'t','ث'=>'s','ج'=>'j','چ'=>'ch','ح'=>'h','خ'=>'kh','د'=>'d','ذ'=>'z','ر'=>'r','ز'=>'z','ژ'=>'zh','س'=>'s','ش'=>'sh','ص'=>'s','ض'=>'z','ط'=>'t','ظ'=>'z','ع'=>'','غ'=>'gh','ف'=>'f','ق'=>'gh','ک'=>'k','گ'=>'g','ل'=>'l','م'=>'m','ن'=>'n','و'=>'o','ه'=>'h','ی'=>'y','ء'=>''];
  $out = '';
  $len = mb_strlen($sN);
  for($i=0;$i<$len;$i++){ $ch = mb_substr($sN,$i,1); $out .= $map[$ch] ?? $ch; }
  return trim(preg_replace('/[^a-z0-9]+/i',' ', $out));
}

// اگر در persiantranslate.php مپ تیم‌ها هست (مثلاً $teamMap: en=>fa)
function fa_to_en_team($fa){
  $fa = normalizeFa($fa);
  $cands = [];
  if (isset($GLOBALS['teamMap']) && is_array($GLOBALS['teamMap'])) {
    foreach ($GLOBALS['teamMap'] as $en => $faName) {
      if (!$faName) continue;
      $faNameN = normalizeFa($faName);
      if ($faNameN === $fa || mb_strpos($faNameN, $fa) !== false) $cands[] = $en;
    }
  }
  return array_values(array_unique($cands));
}

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

// --- جستجو ---
$q = trim($_GET['q'] ?? '');
$queries = [];
if ($q !== '') $queries[] = $q;

if (preg_match('/[\x{0600}-\x{06FF}]/u', $q)) { // فارسی
  $roman = fa_translit($q);
  if ($roman && $roman !== $q) $queries[] = $roman;
  $mapCands = fa_to_en_team($q);
  if ($mapCands) $queries = array_merge($queries, $mapCands);
}

// --- NEW: هینت برای کلمات رایج حاوی «ی» ---
$qN = normalizeFa($q);
$hints = [
  'یونایتد'   => 'united',
  'سیتی'      => 'city',
  'لیورپول'   => 'liverpool',
  'لیدز'      => 'leeds',
  'یوونتوس'   => 'juventus',
  'لایپزیگ'   => 'leipzig',
  'بیلبائو'   => 'bilbao',
  'اینتر'     => 'inter',
  'لاتزیو'    => 'lazio',
  'رئال بتیس' => 'real betis',
];
foreach ($hints as $fa => $en) {
  if (mb_strpos($qN, $fa) !== false) $queries[] = $en;
}


if (!$queries) $queries[] = 'estegh'; // پیش‌فرض

$seen = [];
$teams = [];
foreach (array_unique($queries) as $qq) {
  $url = 'https://prod-cdn-search-api.livescore.com/api/v2/search/soccer?query='
       . rawurlencode($qq)
       . '&limit=200&locale=en&countryCode=FI&categories=true&stages=true&teams=true';
  $data = fetchJson($url);
  foreach (($data['Teams'] ?? $data['teams'] ?? []) as $t) {
    $id = (int)($t['ID'] ?? 0);
    if ($id && empty($seen[$id])) { $seen[$id]=1; $teams[] = $t; }
  }
}
?>
<!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&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:#4CAF50; }
body{
  margin:0; padding:16px 16px calc(16px + 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,.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(255,255,255,.06), rgba(255,255,255,.03));
    border:1px solid var(--border); border-radius:12px;
    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;
  }
  a.btn{ padding:.45rem .7rem; border-radius:8px; background:#4CAF50; color:#000 !important; text-decoration:none; }

.results .item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border: 1px solid var(--border);
  border-radius: 10px;
  background: linear-gradient(180deg, rgba(255,255,255,.05), rgba(255,255,255,.02));
}

.results .item:hover {
  border-color: rgba(76,175,80,.35);
  box-shadow: 0 12px 20px rgba(76,175,80,.06);
}

  .muted{ color:var(--muted); }
  .logo{ width:32px;height:32px;border-radius:50%;object-fit:cover; }
  .search-in{ background:transparent; outline:none; border-bottom:1px solid rgba(255,255,255,.2); color:#e8eef7; }
    .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-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);
}

</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>
    </header>

    <!-- Search box -->
    <section class="card mt-4 p-4">
      <form method="get" class="flex items-center gap-3">
        <i class="fas fa-search text-gray-200"></i>
        <input name="q" value="<?=h($q)?>" class="w-full px-2 py-2 search-in" placeholder="نام تیم مورد نظر خود را به فارسی یا لاتین وارد کنید!">
        <button class="btn">جستجو</button>
      </form>
    </section>

<section class="card mt-4 p-4">
  <div class="flex items-center justify-between mb-3">
    <div class="font-semibold">نتایج جستجو</div>
    <div class="text-sm muted"><?= $teams ? count($teams).' تیم' : 'بدون نتیجه' ?></div>
  </div>

  <div class="results">
    <?php if (!$teams): ?>
      <p class="text-center py-6 muted">چیزی پیدا نشد.</p>
    <?php else: ?>
      <ul class="grid gap-2">
        <?php
        $baseImg = 'https://lsm-static-prod.livescore.com/medium/';
        foreach ($teams as $t):
          $id      = (int)($t['ID'] ?? 0);
          $rawName = $t['Nm'] ?? '';
          $rawCo   = $t['CoNm'] ?? '';
          $img     = $t['Img'] ?? '';
          $name = getTeamName($rawName);
          $co   = getcountrys($rawCo);
          $logo = $img ? ($baseImg . $img) : '';
        ?>
          <li class="item">
            <?php if ($logo): ?>
              <img src="<?=h($logo)?>" alt="" class="logo">
            <?php endif; ?>
            <div class="flex-1">
                <div class="font-semibold"><?=h($name)?></div>
                <!--<div class="text-xs muted">ID: <?=h($id)?></div>-->
                <div class="text-xs muted"><?=h($co)?></div>
            </div>
            <a class="btn select-btn" href="team_fixtures.php?team_id=<?=$id?>&amp;team_name=<?=urlencode($name)?>&amp;team_logo=<?=urlencode($img)?>">انتخاب</a>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php endif; ?>
  </div>
</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.select-btn');
      if(!a) return;
      e.preventDefault();               // فعلاً نرو
      overlay.classList.add('show');    // لودینگ را نشان بده
      setTimeout(function(){            // یک تیک برای رندر
        window.location.href = a.href;  // سپس برو
      }, 30);
    });
  })();
</script>

<?php $active='predict'; include __DIR__.'/parts/bottom-nav.php'; ?>

</body>
</html>
