<?php

require_once 'functions.php';
require_once 'persiantranslate.php';
require_once __DIR__ . '/../BOT/LiveMrMD/admin/config.php';
date_default_timezone_set('Asia/Tehran');

function getFeaturedTeamIds(PDO $db): array {
    $stmt = $db->query("SELECT team_id FROM featured_teams WHERE is_active = 1");
    return array_map('intval', array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'team_id'));
}
$featuredTeams = getFeaturedTeamIds($db);
if (!is_array($featuredTeams) || empty($featuredTeams)) { $featuredTeams = []; }

if (isset($_GET['date'])) {
    header("Content-Type: text/html; charset=utf-8");

    $date = $_GET['date']; // YYYY-MM-DD (میلادی)
    $apiDate = str_replace('-', '', $date); // YYYYMMDD
    $apiUrl = "https://prod-public-api.livescore.com/v1/api/app/date/soccer/{$apiDate}/3.30";

    $json = @file_get_contents($apiUrl);
    if (!$json) {
        echo "<div class='text-red-500'>❌ خطا در دریافت اطلاعات.</div>";
        exit;
    }

    $data = json_decode($json);
    if (!isset($data->Stages)) {
        echo "<div class='text-gray-500'>هیچ بازی‌ای برای این تاریخ ثبت نشده است.</div>";
        exit;
    }

    date_default_timezone_set('Asia/Tehran');
    $tehran   = new DateTimeZone('Asia/Tehran');
    $today   = new DateTime('today', $tehran);
    $reqDate = new DateTime($date, $tehran);
    $isPast  = ($reqDate < $today);
    $isToday = ($reqDate->format('Y-m-d') === $today->format('Y-m-d'));

    $__printed = 0;
   foreach ($data->Stages as $stage) {
        if (empty($stage->Events)) continue;
        $leagueName = getleagues($stage->Snm ?? 'لیگ نامشخص');

        $eventsHtml = '';

        foreach ($stage->Events as $event) {
            $home = getTeamName($event->T1[0]->Nm ?? 'تیم میزبان');
            $away = getTeamName($event->T2[0]->Nm ?? 'تیم مهمان');

            $homeId = (int)($event->T1[0]->ID ?? 0);
            $awayId = (int)($event->T2[0]->ID ?? 0);
            if (!empty($featuredTeams)
                && !in_array($homeId, $featuredTeams, true)
                && !in_array($awayId, $featuredTeams, true)) {
                continue;
            }

            $homeLogo = 'https://lsm-static-prod.livescore.com/medium/' . ($event->T1[0]->Img ?? '');
            $awayLogo = 'https://lsm-static-prod.livescore.com/medium/' . ($event->T2[0]->Img ?? '');

            $status     = $event->Eps ?? '';
            $isFinished = in_array($status, ['FT','AET','PEN','FT_PEN','AP'], true);

            $matchTime = null;
            if (!empty($event->Esd)) {
                $matchTime = DateTime::createFromFormat('YmdHi', substr($event->Esd ?? '', 0, 12), $tehran);
            }
            // if ($matchTime) {
            //     $matchTime->modify('-1 hour'); // ✅ یک ساعت عقب
            // }
            $formattedTime = $matchTime
                ? convertToPersianNumbers($matchTime->format('H:i'))
                : '؟';

            if ($isFinished) {
                // نتیجه اصلی (۹۰ دقیقه + وقت اضافه)
                $score1 = isset($event->Tr1) ? convertToPersianNumbers("{$event->Tr1}") : '—';
                $score2 = isset($event->Tr2) ? convertToPersianNumbers("{$event->Tr2}") : '—';
            
                // اگر بازی به پنالتی رسیده، نتیجه پنالتی رو تو پرانتز نشون بده
                if (in_array($status, ['AP','PEN','FT_PEN'], true) && isset($event->Trp1) && isset($event->Trp2)) {
                    $score1 .= " (" . convertToPersianNumbers("{$event->Trp1}") . ")";
                    $score2 .= " (" . convertToPersianNumbers("{$event->Trp2}") . ")";
                }

            $eventsHtml .=
                "<div class='match-row text-gray-300'>"
              .   "<div class='grid grid-cols-12 items-center gap-2'>"
              .     "<span class='col-span-10 justify-self-start text-right'>"
              .       "<span class='inline-flex items-center gap-2'>"
              .         ($homeLogo ? "<img src='{$homeLogo}' class='w-5 h-5 rounded-full shrink-0' alt=''>" : "")
              .         "<span class='truncate'>{$home}</span>"
              .       "</span>"
              .     "</span>"
              .     "<span class='col-span-2 text-left'>{$score1}</span>"
              .   "</div>"
              .   "<div class='grid grid-cols-12 items-center gap-2 mb-2'>"
              .     "<span class='col-span-10 justify-self-start text-right'>"
              .       "<span class='inline-flex items-center gap-2'>"
              .         ($awayLogo ? "<img src='{$awayLogo}' class='w-5 h-5 rounded-full shrink-0' alt=''>" : "")
              .         "<span class='truncate'>{$away}</span>"
              .       "</span>"
              .     "</span>"
              .     "<span class='col-span-2 text-left'>{$score2}</span>"
              .   "</div>"
                . "<div class='match-details'>"
                .   "<a href='match_stats.php?eid={$event->Eid}' class='details-btn'>"
                .     "<span></span> جزئیات بازی"
                .   "</a>"
                . "</div>"
                . "</div>";

            } else {
                $formattedStatus = ($status === 'NS' && $matchTime)
                    ? $formattedTime
                    : (!empty($status) ? convertToPersianNumbers($status) : $formattedTime);

                $eventsHtml .=
                    "<div class='match-row grid grid-cols-12 items-center gap-2 text-gray-300'>"
                  .   "<span class='col-span-10 justify-self-start text-right'>"
                  .     "<span class='flex flex-col gap-1'>"
                  .       "<span class='flex items-center gap-3'>"
                  .         ($homeLogo ? "<img src='{$homeLogo}' class='w-5 h-5 rounded-full shrink-0' alt=''>" : "")
                  .         "<span class='truncate max-w-[80%]'>{$home}</span>"
                  .       "</span>"
                  .       "<span class='flex items-center gap-3'>"
                  .         ($awayLogo ? "<img src='{$awayLogo}' class='w-5 h-5 rounded-full shrink-0' alt=''>" : "")
                  .         "<span class='truncate max-w-[80%]'>{$away}</span>"
                  .       "</span>"
                  .     "</span>"
                  .   "</span>"
                  .   "<span class='col-span-2 text-left'>{$formattedStatus}</span>"
                  . "</div>";
            }
        }

        if ($eventsHtml !== '') {
            echo "<section class='league-box mb-6'>";
            echo "<header class='league-header px-4 py-3'>
                    <h3 class='text-base sm:text-lg font-bold text-[#4CAF50]'>🏆 " . getleagues($leagueName) . "</h3>
                  </header>
                  <div class='divide-y divide-[#1f2632]'>";
            echo $eventsHtml;
            echo "</div></section>";
            $__printed++;
        }
    }
if ($__printed === 0) {
    echo "<div class='mt-4 text-gray-300'>امروز بازی مهمی برگزار نمی‌شود.</div>";
}

    exit;
}
?>
 
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>تقویم بازی‌ها</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">
<script src="https://cdn.jsdelivr.net/npm/jalaali-js/dist/jalaali.min.js"></script>

  <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;
    filter: drop-shadow(0 2px 10px rgba(76,175,80,.25));
  }
  a.btn{ padding:.45rem .7rem; border-radius:8px; background:#4CAF50; color:#000 !important; text-decoration:none; }
    
    .league-box{
      background:#171c24; border:1px solid #2a2f3a; border-radius:6px;
      overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,.25);
    }
    .league-header{ background:#030903; border-bottom:1px solid #1f2632; }
    .match-row{ padding:.75rem 1rem; }
    .match-row:hover{ background:rgba(76, 175, 80, 0.06); }
    
    .match-details {
        margin-top: 10px;
        display: flex;
        justify-content: center;
    }
    .details-btn {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        background: linear-gradient(90deg, rgba(76,175,80,0.15), rgba(76,175,80,0.05));
        border: 1px solid var(--border);
        color: var(--text);
        text-decoration: none;
        font-family: 'Bai Jamjuree','Vazirmatn',sans-serif;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.2s ease;
    }
    .details-btn:hover {
        background: linear-gradient(90deg, rgba(76,175,80,0.3), rgba(76,175,80,0.15));
        transform: translateY(-1px);
        box-shadow: 0 3px 10px rgba(76,175,80,0.2);
    }
    .details-btn span {
        font-size: 15px;
    }
    
    /* 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)}

/* Jalali datepicker styles */

#jalaPicker .jp-header{
  display:flex; align-items:center; justify-content:space-between;
  margin-bottom:.5rem; user-select:none;
}
#jalaPicker .jp-header button{
  padding:.25rem .5rem; border:1px solid #2a2f3a; border-radius:6px; background:#0c121a;
}
#jalaPicker .jp-title{ font-weight:700; }
#jalaPicker .jp-grid{
  display:grid; grid-template-columns: repeat(7, 1fr); gap:.25rem;
}
#jalaPicker .jp-cell{
  text-align:center; padding:.45rem 0; border-radius:4px; cursor:pointer; user-select:none;
}
#jalaPicker .jp-cell.muted{ opacity:.35; cursor:default; }
#jalaPicker .jp-cell:hover{ background:rgba(76,175,80,.12); }
#jalaPicker .jp-cell.active{ background:#4CAF50; color:#000; font-weight:700; }
#jalaPicker .jp-weekday{ font-size:.8rem; opacity:.7; cursor:default; }

    @media (max-width: 480px) {
      input[type="date"]::-webkit-calendar-picker-indicator { filter: invert(1); }
    }
    #jalaPicker{
        right: 30;                
        left: 0;                     
        width: auto;
        min-width: 320px;            
        max-width: 100vw;            
        overflow-x: auto;            
        -webkit-overflow-scrolling: touch;
      }

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

    <section class="card px-4 py-4 mb-6 mt-4">

<!-- Toggle Gregorian / Jalali + inputs -->
<div class="mx-auto w-full max-w-2xl flex flex-col gap-3">

  <!-- Toggle buttons -->
  <div class="flex items-center gap-2">
      
    <button id="btnJala" type="button"
            class="px-4 h-10 rounded-lg border border-gray-700 text-gray-200 bg-[#0a0a12] data-[active=true]:bg-[#4CAF50] data-[active=true]:text-black"
            onclick="setCalendarMode('jala')">
      تقویم شمسی
    </button>
    <button id="btnGreg" type="button"
            class="px-4 h-10 rounded-lg border border-gray-700 text-gray-200 bg-[#0a0a12] data-[active=true]:bg-[#4CAF50] data-[active=true]:text-black"
            onclick="setCalendarMode('greg')">
      تقویم میلادی
    </button>
  </div>

<!-- Inputs row + anchored picker -->
<div class="flex items-stretch sm:items-end gap-3">
  <!-- ثابت: ظرف ورودی‌ها با عرض یکسان -->
  <div class="relative w-full sm:w-64 h-11">
    <!-- Gregorian (روی هم قرار می‌گیرند) -->
    <input type="date" id="matchDate"
           class="input-swap visible-swap absolute inset-0 border border-gray-700 bg-[#0a0a12] text-gray-300 rounded-lg px-3 w-full h-11 focus:ring-2 focus:ring-orange-400 focus:outline-none appearance-none text-[16px]" />

    <!-- Jalali -->
    <input type="text" id="matchDateFa" placeholder="۱۴۰۴-۰۵-۲۱ مثلا"
           class="input-swap hidden-swap absolute inset-0 border border-gray-700 bg-[#0a0a12] text-gray-300 rounded-lg px-3 w-full h-11 focus:ring-2 focus:ring-orange-400 focus:outline-none text-[16px]"
           inputmode="numeric" autocomplete="off" />

    <!-- Picker anchored -->
    <div id="jalaPicker"
         class="hidden absolute left-0 right-0 top-[calc(100%+6px)] z-50 text-gray-200 rounded-lg border border-gray-700 bg-[#0a0a12] shadow-xl p-3"></div>
  </div>

  <button id="showBtn" onclick="loadMatches()"
          class="bg-[#ccc] hover:bg-[#4CAF50] text-black font-medium rounded-lg transition-colors h-11 px-6 sm:px-8 min-w-[140px]">
    نمایش
  </button>
</div>
    </section>

    <div id="matchResults" class="mt-6"></div>
  </div>

<script>
  // ---- Calendar mode state ----
  let calendarMode = 'greg'; // 'greg' | 'jala'

  function setCalendarMode(mode) {
    calendarMode = mode === 'jala' ? 'jala' : 'greg';

    // toggle active style
    document.getElementById('btnGreg').dataset.active = calendarMode === 'greg';
    document.getElementById('btnJala').dataset.active = calendarMode === 'jala';

    // toggle inputs
    document.getElementById('matchDate').classList.toggle('hidden', calendarMode === 'jala');
    document.getElementById('matchDateFa').classList.toggle('hidden', calendarMode === 'greg');
  }

  // تبدیل ارقام فارسی/عربی به لاتین
  function normalizeDigits(str){
    if(!str) return str;
    const fa = '۰۱۲۳۴۵۶۷۸۹';
    const ar = '٠١٢٣٤٥٦٧٨٩';
    return str
      .replace(/[۰-۹]/g, d => String(fa.indexOf(d)))
      .replace(/[٠-٩]/g, d => String(ar.indexOf(d)));
  }

  // parse "yyyy-mm-dd" (jalali text)
  function parseJalaliInput(str){
    if(!str) return null;
    str = normalizeDigits(str.trim());
    const m = str.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
    if(!m) return null;
    const jy = +m[1], jm = +m[2], jd = +m[3];
    if(jm<1||jm>12||jd<1||jd>31) return null;
    return {jy, jm, jd};
  }

  function pad2(n){ return n.toString().padStart(2,'0'); }

  // بارگذاری مسابقات با درنظر گرفتن حالت تقویم
  function loadMatches() {
    let gDate; // yyyy-mm-dd

    if (calendarMode === 'greg') {
      gDate = document.getElementById('matchDate').value;
      if (!gDate) { alert("لطفاً تاریخ میلادی را انتخاب کنید."); return; }
    } else {
      const val = document.getElementById('matchDateFa').value;
      const j = parseJalaliInput(val);
      if (!j) { alert("تاریخ شمسی را به‌صورت yyyy-mm-dd وارد کنید (مثال: 1404-05-21)."); return; }
      // تبدیل با jalaali-js
      const g = jalaali.toGregorian(j.jy, j.jm, j.jd); // {gy, gm, gd}
      gDate = `${g.gy}-${pad2(g.gm)}-${pad2(g.gd)}`;
    }

    fetch(`calendar.php?date=${encodeURIComponent(gDate)}`)
      .then(r => r.text())
      .then(html => document.getElementById('matchResults').innerHTML = html)
      .catch(() => document.getElementById('matchResults').innerHTML =
        '<div class="text-red-500 mt-4">خطا در دریافت اطلاعات. لطفاً دوباره تلاش کنید.</div>');
  }

  document.addEventListener('DOMContentLoaded', function () {
    // پیش‌فرض: میلادی فعال
    setCalendarMode('jala');

    // امروز میلادی برای input نوع date
    const now = new Date();
    const gToday = now.toISOString().split('T')[0]; // yyyy-mm-dd
    document.getElementById('matchDate').value = gToday;

    // معادل شمسی امروز برای input شمسی
    const g = { gy: now.getFullYear(), gm: now.getMonth()+1, gd: now.getDate() };
    const j = jalaali.toJalaali(g.gy, g.gm, g.gd); // {jy,jm,jd}
    const jToday = `${j.jy}-${pad2(j.jm)}-${pad2(j.jd)}`;
    document.getElementById('matchDateFa').value = toPersianDigits(jToday);

    // بارگذاری بازی‌های امروز
    loadMatches();
  });
</script>

<script>
  // --- Jalali popup datepicker ---
  const jPicker = document.getElementById('jalaPicker');
  const jInput  = document.getElementById('matchDateFa');

  // نام ماه‌ها به فارسی
  const J_MONTHS = ['فروردین','اردیبهشت','خرداد','تیر','مرداد','شهریور','مهر','آبان','آذر','دی','بهمن','اسفند'];
  const J_WEEK  = ['ش','ی','د','س','چ','پ','ج']; // شروع از شنبه

  // حالت فعلی تقویم
  let jpState = { jy: 1400, jm: 1, jd: 1 };

  function pad2(n){ return n.toString().padStart(2,'0'); }

  function setFromInputOrToday(){
    // اگر ورودی معتبر داشتیم از همان مقدار شروع کن؛ وگرنه از امروز
    const v = normalizeDigits(jInput.value.trim());
    const m = v.match(/^(\d{4})-(\d{2})-(\d{2})$/);
    if (m) {
      jpState.jy = +m[1]; jpState.jm = +m[2]; jpState.jd = +m[3];
    } else {
      const now = new Date();
      const j = jalaali.toJalaali(now.getFullYear(), now.getMonth()+1, now.getDate());
      jpState = { jy: j.jy, jm: j.jm, jd: j.jd };
    }
  }

  function daysInJMonth(jy, jm){
    if (jm <= 6) return 31;
    if (jm <= 11) return 30;
    return jalaali.isLeapJalaaliYear(jy) ? 30 : 29;
  }

  // محاسبه روز هفته‌ی اولین روز ماه جلالی (شروع هفته: شنبه)
  function firstWeekdayIndex(jy, jm){
    const g = jalaali.toGregorian(jy, jm, 1);
    const jsDay = new Date(g.gy, g.gm-1, g.gd).getDay(); // 0=Sun ... 6=Sat
    // تبدیل به ایندکس با شروع شنبه (0=شنبه ... 6=جمعه)
    return (jsDay + 1) % 7;
  }

  function renderJalaliPicker(){
    const { jy, jm, jd } = jpState;
    const title = `${J_MONTHS[jm-1]} ${jy}`;
    const firstIdx = firstWeekdayIndex(jy, jm);
    const dim = daysInJMonth(jy, jm);

    // هدر + سرتیتر روزهای هفته
    let html = `
      <div class="jp-header">
        <button type="button" onclick="jpPrevMonth()">&larr;</button>
        <div class="jp-title">${title}</div>
        <button type="button" onclick="jpNextMonth()">&rarr;</button>
      </div>
      <div class="jp-grid">`;

    // روزهای هفته
    for (const w of J_WEEK) html += `<div class="jp-weekday">${w}</div>`;

    // خانه های خالی قبل از روز 1
    for (let i=0;i<firstIdx;i++) html += `<div></div>`;

    // روزهای ماه
    for (let d=1; d<=dim; d++){
      const isActive = (d===jd);
html += `<div class="jp-cell ${isActive?'active':''}" data-d="${d}">${toPersianDigits(d)}</div>`;
    }

    html += `</div>`;
    jPicker.innerHTML = html;

    // هندل انتخاب روز
    jPicker.querySelectorAll('.jp-cell[data-d]').forEach(el=>{
      el.addEventListener('click', ()=>{
        const day = +el.dataset.d;
        jpState.jd = day;
        // مقدار را در input بنویس
        jInput.value = toPersianDigits(`${jpState.jy}-${pad2(jpState.jm)}-${pad2(day)}`);

        hidePicker();
      });
    });
  }

function toPersianDigits(x){
  return String(x).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
}

  // ناوبری ماه قبل/بعد
function jpPrevMonth(){
  if (jpState.jm===1){ jpState.jm=12; jpState.jy--; } else { jpState.jm--; }
  const dim = daysInJMonth(jpState.jy, jpState.jm);
  if (jpState.jd>dim) jpState.jd = dim;
  renderJalaliPicker();
}
function jpNextMonth(){
  if (jpState.jm===12){ jpState.jm=1; jpState.jy++; } else { jpState.jm++; }
  const dim = daysInJMonth(jpState.jy, jpState.jm);
  if (jpState.jd>dim) jpState.jd = dim;
  renderJalaliPicker();
}

  function showPicker(){
    setFromInputOrToday();
    renderJalaliPicker();
    jPicker.classList.remove('hidden');
  }
  function hidePicker(){
    jPicker.classList.add('hidden');
  }

  // باز/بسته شدن با کلیک
  jInput.addEventListener('focus', showPicker);
  jInput.addEventListener('click', showPicker);

  // کلیک بیرون → بستن
document.addEventListener('click', (e)=>{
  if (calendarMode!=='jala') return;
  const within = jPicker.contains(e.target) || jInput.contains(e.target) || e.target.closest('.jp-header');
  if (!within) hidePicker();
});

  // وقتی حالت تقویم را عوض می‌کنی و وارد شمسی می‌شوی، آماده‌اش کن
  const _oldSetCalendarMode = setCalendarMode;
  setCalendarMode = function(mode){
    _oldSetCalendarMode(mode);
    if (mode==='jala'){ setFromInputOrToday(); renderJalaliPicker(); }
    else { hidePicker(); }
  }
</script>

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