<?php
$logo = setting('logo_path', 'assets/img/default-logo.png');
$logoSrc = str_starts_with($logo, 'assets/') ? base_url($logo) : file_url($logo);
$shopName = setting('shop_name_ar', 'فخر الأصالة العمانية');
$shopNameEn = setting('shop_name_en', '');
$screenMsg = setting('queue_screen_message', 'أهلاً بكم');
$servingRow = $snap['serving'][0] ?? null;
$waitingRows = $snap['waiting'] ?? [];
$skippedRows = $snap['skipped'] ?? [];
$totals = $snap['totals'] ?? [];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= e($shopName) ?> - شاشة الطابور</title>
<style>
:root{--bg:#f6f1eb;--card:#ffffff;--line:#e8ddd3;--text:#1f2937;--muted:#6b7280;--brand:#5e3b23;--brand2:#a66e3f;--soft:#faf7f2}
*{box-sizing:border-box}
body{margin:0;font-family:Tahoma,Arial,sans-serif;background:linear-gradient(180deg,#f7f3ef,#f1ebe4);color:var(--text)}
.tv-shell{min-height:100vh;padding:22px;display:grid;grid-template-rows:auto 1fr;gap:18px}
.tv-top{background:linear-gradient(90deg,var(--brand),var(--brand2));color:#fff;border-radius:28px;padding:20px 24px;display:flex;align-items:center;justify-content:space-between;gap:18px;box-shadow:0 16px 34px rgba(94,59,35,.18)}
.tv-brand{display:flex;align-items:center;gap:16px;min-width:0}
.tv-brand img{width:72px;height:72px;border-radius:22px;background:#fff;padding:8px;object-fit:contain;box-shadow:0 8px 24px rgba(0,0,0,.18)}
.tv-brand h1{margin:0;font-size:34px;line-height:1.1}
.tv-brand p{margin:4px 0 0;font-size:16px;color:#f7eee4}
.tv-msg{font-size:18px;color:#fff7ee;text-align:left}
.tv-grid{display:grid;grid-template-columns:1.3fr .7fr;gap:18px}
.tv-card{background:linear-gradient(180deg,#fff,#fbf7f2);border:1px solid #eadfce;border-radius:28px;padding:22px;box-shadow:0 12px 30px rgba(56,34,15,.06)}
.tv-hero{display:grid;gap:14px;align-content:center;text-align:center;background:linear-gradient(135deg,#5e3b23,#a66e3f);color:#fff;border:none}
.tv-hero .caption{color:#f9efe2;font-size:22px}
.tv-number{font-size:clamp(96px,16vw,180px);font-weight:900;line-height:1}
.tv-time{font-size:20px;color:#fff4e8}
.tv-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}
.tv-stat{background:#fff;border:1px solid #efe4d6;border-radius:20px;padding:18px;text-align:center}
.tv-stat .l{font-size:16px;color:#786452}
.tv-stat .v{font-size:42px;font-weight:900;color:#5f3f27;line-height:1.1;margin-top:8px}
.tv-list{display:grid;gap:12px}
.tv-row{display:flex;align-items:center;justify-content:space-between;gap:12px;background:#fff;border:1px solid #efe4d6;border-radius:18px;padding:16px}
.tv-row strong{font-size:34px;color:#5f3f27}
.tv-row .meta{display:grid;gap:4px}
.tv-pill{display:inline-flex;align-items:center;justify-content:center;padding:8px 14px;border-radius:999px;background:#fff4e7;border:1px solid #efd9be;color:#8a5b36;font-size:13px;font-weight:700}
.tv-empty{padding:26px;text-align:center;background:#fffaf4;border:1px dashed #dec5a5;border-radius:18px;color:#7a6858}
.tv-bottom{display:grid;grid-template-columns:1fr 1fr;gap:18px}
@media (max-width:1200px){.tv-grid{grid-template-columns:1fr}.tv-bottom,.tv-stats{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="tv-shell">
  <div class="tv-top">
    <div class="tv-brand">
      <img src="<?= e($logoSrc) ?>" alt="logo">
      <div>
        <h1><?= e($shopName) ?></h1>
        <?php if ($shopNameEn): ?><p><?= e($shopNameEn) ?></p><?php endif; ?>
      </div>
    </div>
    <div class="tv-msg"><?= e($screenMsg) ?></div>
  </div>

  <div class="tv-grid">
    <div class="tv-card tv-hero">
      <div class="caption">الرقم الجاري خدمته</div>
      <div class="tv-number" id="servingNo"><?= e($servingRow['ticket_no'] ?? '---') ?></div>
      <div class="tv-time" id="servingTime"><?= !empty($servingRow['called_at']) ? e($servingRow['called_at']) : 'بانتظار الاستدعاء' ?></div>
      <div class="tv-stats">
        <div class="tv-stat"><div class="l">المنتظرون</div><div class="v" id="waitingCount"><?= (int)($totals['waiting'] ?? count($waitingRows)) ?></div></div>
        <div class="tv-stat"><div class="l">المتخطون</div><div class="v" id="skippedCount"><?= (int)($totals['skipped'] ?? count($skippedRows)) ?></div></div>
        <div class="tv-stat"><div class="l">عدد العملاء</div><div class="v" id="issuedCount"><?= (int)($totals['issued'] ?? 0) ?></div></div>
      </div>
    </div>

    <div class="tv-card">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
        <h3 style="margin:0">قائمة الانتظار</h3>
        <span class="tv-pill">مباشر</span>
      </div>
      <div class="tv-list" id="waitingBody">
        <?php foreach(array_slice($waitingRows,0,8) as $r): ?>
          <div class="tv-row">
            <div class="meta"><strong><?= e($r['ticket_no']) ?></strong></div>
            <span class="tv-pill">#<?= e($r['seq_no']) ?></span>
          </div>
        <?php endforeach; ?>
        <?php if(empty($waitingRows)): ?><div class="tv-empty">لا يوجد انتظار حاليًا</div><?php endif; ?>
      </div>
    </div>
  </div>

  <div class="tv-bottom">
    <div class="tv-card">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
        <h3 style="margin:0">الأرقام المتخطاة</h3>
        <span class="tv-pill">للمتابعة</span>
      </div>
      <div class="tv-list" id="skippedBody">
        <?php foreach(array_slice($skippedRows,0,6) as $r): ?>
          <div class="tv-row">
            <div class="meta"><strong><?= e($r['ticket_no']) ?></strong></div>
            <span class="tv-pill">متخطى</span>
          </div>
        <?php endforeach; ?>
        <?php if(empty($skippedRows)): ?><div class="tv-empty">لا يوجد أرقام متخطاة</div><?php endif; ?>
      </div>
    </div>
    <div class="tv-card">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
        <h3 style="margin:0">الوقت الحالي</h3>
        <span class="tv-pill">تحديث تلقائي</span>
      </div>
      <div style="display:grid;place-items:center;min-height:220px">
        <div style="text-align:center">
          <div id="clock" style="font-size:62px;font-weight:900;color:#5f3f27;line-height:1"></div>
          <div id="dateLine" style="margin-top:12px;color:#7a6858;font-size:24px"></div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
let lastServed = <?= json_encode($servingRow['ticket_no'] ?? '') ?>;
const queuePollMs = parseInt(<?= json_encode(setting('queue_poll_ms','2000')) ?>,10) || 2000;
const queueSoundEnabled = <?= json_encode(setting('queue_sound_enabled','1') === '1') ?>;
function esc(s){return String(s ?? '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));}
function rowWaiting(r){return `<div class="tv-row"><div class="meta"><strong>${esc(r.ticket_no)}</strong></div><span class="tv-pill">#${esc(r.seq_no)}</span></div>`}
function rowSkipped(r){return `<div class="tv-row"><div class="meta"><strong>${esc(r.ticket_no)}</strong></div><span class="tv-pill">متخطى</span></div>`}
function speak(text){
  if ('speechSynthesis' in window && queueSoundEnabled) {
    const utter = new SpeechSynthesisUtterance(text);
    utter.lang = 'en-US';
    utter.rate = .95;
    window.speechSynthesis.cancel();
    window.speechSynthesis.speak(utter);
  }
}
async function refreshTV(){
  try{
    const res = await fetch('<?= e(base_url('?page=queue_snapshot')) ?>',{headers:{'Accept':'application/json','X-Requested-With':'XMLHttpRequest'}});
    const d = await res.json();
    const serving = (d.serving && d.serving.length) ? d.serving[0] : null;
    const currentNo = serving ? serving.ticket_no : '---';
    document.getElementById('servingNo').textContent = currentNo;
    document.getElementById('servingTime').textContent = serving && serving.called_at ? serving.called_at : 'بانتظار الاستدعاء';
    document.getElementById('waitingBody').innerHTML = (d.waiting||[]).length ? (d.waiting||[]).slice(0,8).map(rowWaiting).join('') : '<div class="tv-empty">لا يوجد انتظار حاليًا</div>';
    document.getElementById('skippedBody').innerHTML = (d.skipped||[]).length ? (d.skipped||[]).slice(0,6).map(rowSkipped).join('') : '<div class="tv-empty">لا يوجد أرقام متخطاة</div>';
    if (d.totals) {
      document.getElementById('waitingCount').textContent = parseInt(d.totals.waiting || 0, 10);
      document.getElementById('skippedCount').textContent = parseInt(d.totals.skipped || 0, 10);
      document.getElementById('issuedCount').textContent = parseInt(d.totals.issued || 0, 10);
    }
    if (currentNo !== '---' && currentNo !== lastServed) {
      lastServed = currentNo;
      speak(`Now serving ticket number ${currentNo}`);
    }
  }catch(e){console.error(e);}
}
function updateClock(){
  const now = new Date();
  const time = now.toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',second:'2-digit'});
  const date = now.toLocaleDateString('ar-OM',{weekday:'long', year:'numeric', month:'long', day:'numeric'});
  document.getElementById('clock').textContent = time;
  document.getElementById('dateLine').textContent = date;
}
setInterval(refreshTV, queuePollMs);
setInterval(updateClock, 1000);
updateClock();
</script>
</body>
</html>
