<?php $title='شاشة الانتظار'; include __DIR__ . '/../layout/header.php'; ?>
<style>
.qs-shell{display:grid;grid-template-columns:1.12fr .88fr;gap:18px}
.qs-card{background:linear-gradient(180deg,#fff,#fbf7f2);border:1px solid #eadfce;border-radius:24px;padding:20px;box-shadow:0 12px 30px rgba(56,34,15,.06)}
.qs-hero{position:relative;overflow:hidden;background:linear-gradient(135deg,#5e3b23,#a66e3f);color:#fff;border:none}
.qs-hero:before{content:"";position:absolute;inset:auto -60px -60px auto;width:220px;height:220px;border-radius:999px;background:rgba(255,255,255,.08)}
.qs-brand{display:flex;align-items:center;justify-content:center;gap:14px;margin-bottom:8px}
.qs-brand img{width:64px;height:64px;border-radius:20px;background:#fff;padding:6px;object-fit:contain;box-shadow:0 8px 22px rgba(0,0,0,.16)}
.qs-brand-text{display:grid;gap:3px}
.qs-brand-text strong{font-size:20px;line-height:1.1}
.qs-brand-text span,.qs-hero .muted{color:#f7eee4}
.qs-big{font-size:clamp(58px,8vw,104px);font-weight:900;line-height:1.04;margin:10px 0}
.qs-status{display:inline-flex;align-items:center;gap:8px;background:rgba(255,255,255,.14);border:1px solid rgba(255,255,255,.18);padding:8px 14px;border-radius:999px}
.qs-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
.qs-list,.skip-list{display:grid;gap:10px}
.qs-row,.skip-card{display:flex;align-items:center;justify-content:space-between;gap:12px;background:#fff;border:1px solid #efe4d6;border-radius:18px;padding:14px}
.qs-row strong,.skip-card strong{font-size:20px;color:#5f3f27}
.qs-meta{display:grid;gap:4px}
.qs-muted{font-size:12px;color:#8a7662}
.qs-actions{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
.qs-actions form{margin:0}
.report-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:12px}
.report-box{background:#fff;border:1px solid #efe4d6;border-radius:18px;padding:16px;text-align:center}
.report-box .v{font-size:28px;font-weight:800;color:#5f3f27}
.qs-tag{display:inline-flex;align-items:center;justify-content:center;padding:7px 11px;border-radius:999px;background:#fff4e7;border:1px solid #efd9be;color:#8a5b36;font-size:12px;font-weight:700}
.qs-topline{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}
.qs-row-phone{color:#7a6858;font-size:13px}
.qs-row.empty,.skip-card.empty{justify-content:center;text-align:center;color:#7a6858;background:#fffaf4}
@media (max-width:1100px){.qs-shell{grid-template-columns:1fr}.qs-grid,.qs-actions,.report-grid{grid-template-columns:1fr}}
</style>
<?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'] ?? [];
$recentRows = $snap['recent'] ?? [];
$totals = $snap['totals'] ?? [];
$price = (float)setting('queue_service_price', setting('queue_ticket_price','0'));
$currency = setting('queue_currency','ر.ع');
$doneCount = (int)($totals['done'] ?? 0);
?>
<div class="qs-shell">
  <div>
    <div class="qs-card qs-hero">
      <div class="qs-brand">
        <img src="<?= e($logoSrc) ?>" alt="logo">
        <div class="qs-brand-text">
          <strong><?= e($shopName) ?></strong>
          <?php if ($shopNameEn): ?><span><?= e($shopNameEn) ?></span><?php endif; ?>
        </div>
      </div>
      <div class="muted" style="text-align:center;margin-bottom:6px"><?= e($screenMsg) ?></div>
      <div class="muted" style="text-align:center">الرقم الجاري خدمته</div>
      <div id="servingNo" class="qs-big" style="text-align:center"><?= e($servingRow['ticket_no'] ?? '---') ?></div>
      <div style="display:flex;justify-content:center;margin-bottom:8px">
        <div class="qs-status"><span>⏱</span><span id="servingTime"><?= !empty($servingRow['called_at']) ? e($servingRow['called_at']) : 'بانتظار الاستدعاء' ?></span></div>
      </div>
    </div>

    <div class="qs-grid" style="margin-top:18px">
      <div class="qs-card">
        <div class="qs-topline">
          <h3 style="margin:0">قائمة الانتظار</h3>
          <span class="qs-tag" id="waitingCount"><?= count($waitingRows) ?> عميل</span>
        </div>
        <div id="waitingBody" class="qs-list" style="margin-top:12px">
          <?php foreach($waitingRows as $r): ?>
            <div class="qs-row">
              <div class="qs-meta">
                <strong><?= e($r['ticket_no']) ?></strong>
                <div class="qs-muted">تسلسل #<?= e($r['seq_no']) ?></div>
              </div>
              <div class="qs-row-phone"><?= e($r['customer_phone'] ?: 'بدون رقم') ?></div>
            </div>
          <?php endforeach; ?>
          <?php if(empty($waitingRows)): ?><div class="qs-row empty">لا يوجد انتظار حاليًا</div><?php endif; ?>
        </div>
      </div>

      <div class="qs-card">
        <div class="qs-topline">
          <h3 style="margin:0">الأرقام المتخطاة</h3>
          <span class="qs-tag">يمكن استدعاؤها في أي وقت</span>
        </div>
        <div id="skippedList" class="skip-list">
          <?php foreach($skippedRows as $r): ?>
            <div class="skip-card">
              <div class="qs-meta">
                <strong><?= e($r['ticket_no']) ?></strong>
                <div class="qs-muted">تم التخطي</div>
              </div>
              <form method="post" action="<?= e(base_url('?page=queue_recall')) ?>">
                <input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>">
                <input type="hidden" name="id" value="<?= e($r['id']) ?>">
                <button class="btn light">استدعاء مرة أخرى</button>
              </form>
            </div>
          <?php endforeach; ?>
          <?php if(empty($skippedRows)): ?><div class="skip-card empty">لا يوجد أرقام متخطاة</div><?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div>
    <div class="qs-card">
      <h3 class="section-title" style="margin-top:0">التحكم</h3>
      <div class="qs-actions">
        <form method="post" action="<?= e(base_url('?page=queue_call_next')) ?>"><input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>"><button class="btn" style="width:100%">استدعاء التالي</button></form>
        <form method="post" action="<?= e(base_url('?page=queue_done')) ?>"><input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>"><button class="btn secondary" style="width:100%">إنهاء الحالي</button></form>
        <form method="post" action="<?= e(base_url('?page=queue_skip')) ?>"><input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>"><button class="btn light" style="width:100%">تخطي الحالي</button></form>
        <form method="post" action="<?= e(base_url('?page=queue_open_day')) ?>" onsubmit="return confirm('سيتم إغلاق الجلسة الحالية وفتح يوم جديد. هل أنت متأكد؟')"><input type="hidden" name="_csrf" value="<?= e(csrf_token()) ?>"><button class="btn danger" style="width:100%">فتح يوم جديد</button></form>
      </div>
      <div class="muted" style="margin-top:12px">عند استدعاء رقم متخطى يتم إعادة الرقم الحالي إلى قائمة الانتظار تلقائيًا إن وجد.</div>
    </div>

    <div class="qs-card" style="margin-top:18px">
      <div class="qs-topline">
        <h3 style="margin:0">ملخص اليوم</h3>
        <span class="qs-tag">تشغيلي ومالي</span>
      </div>
      <div class="report-grid" style="margin-top:12px">
        <div class="report-box"><div class="muted">عدد العملاء</div><div class="v" id="issuedCount"><?= e((string)($totals['issued'] ?? 0)) ?></div></div>
        <div class="report-box"><div class="muted">المبلغ المحصل</div><div class="v" id="collectedAmount"><?= e(number_format($doneCount * $price,3)) ?> <?= e($currency) ?></div></div>
        <div class="report-box"><div class="muted">سعر الخدمة</div><div class="v"><?= e(number_format($price,3)) ?> <?= e($currency) ?></div></div>
        <div class="report-box"><div class="muted">المتبقي الآن</div><div class="v" id="remainingCount"><?= e((string)($totals['waiting'] ?? 0)) ?></div></div>
      </div>
      <div class="responsive-actions" style="margin-top:14px">
        <a class="btn light" href="<?= e(base_url('?page=queue_settings')) ?>">إعدادات الأسعار والطابور</a>
        <a class="btn light" href="<?= e(base_url('?page=queue_reports')) ?>">تقارير من تاريخ إلى تاريخ</a>
      </div>
    </div>

    <div class="qs-card" style="margin-top:18px">
      <div class="qs-topline"><h3 class="section-title" style="margin:0">آخر الحركات الظاهرة</h3><span class="qs-tag">مباشر</span></div>
      <div id="recentList" class="qs-list">
        <?php foreach($recentRows as $r): ?>
          <div class="qs-row"><strong><?= e($r['ticket_no']) ?></strong><span class="qs-tag"><?= e($r['ticket_status']) ?></span></div>
        <?php endforeach; ?>
        <?php if(empty($recentRows)): ?><div class="qs-row empty">لا توجد حركات ظاهرة</div><?php endif; ?>
      </div>
    </div>
  </div>
</div>
<script>
let lastServed = <?= json_encode($servingRow['ticket_no'] ?? '') ?>;
const csrfToken = <?= json_encode(csrf_token()) ?>;
const recallAction = <?= json_encode(base_url('?page=queue_recall')) ?>;
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="qs-row"><div class="qs-meta"><strong>${esc(r.ticket_no)}</strong><div class="qs-muted">تسلسل #${esc(r.seq_no)}</div></div><div class="qs-row-phone">${esc(r.customer_phone||'بدون رقم')}</div></div>`}
function rowRecent(r){return `<div class="qs-row"><strong>${esc(r.ticket_no)}</strong><span class="qs-tag">${esc(r.ticket_status)}</span></div>`}
function rowSkip(r){return `<div class="skip-card"><div class="qs-meta"><strong>${esc(r.ticket_no)}</strong><div class="qs-muted">تم التخطي</div></div><form method="post" action="${recallAction}"><input type="hidden" name="_csrf" value="${csrfToken}"><input type="hidden" name="id" value="${esc(r.id)}"><button class="btn light">استدعاء مرة أخرى</button></form></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 refreshScreen(){
  try {
    const res = await fetch('<?= e(base_url('?page=queue_snapshot')) ?>', {headers:{'X-Requested-With':'XMLHttpRequest','Accept':'application/json'}});
    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.map(rowWaiting).join('') : '<div class="qs-row empty">لا يوجد انتظار حاليًا</div>';
    document.getElementById('waitingCount').textContent = `${(d.waiting||[]).length} عميل`;
    document.getElementById('skippedList').innerHTML = (d.skipped||[]).length ? d.skipped.map(rowSkip).join('') : '<div class="skip-card empty">لا يوجد أرقام متخطاة</div>';
    document.getElementById('recentList').innerHTML = (d.recent||[]).length ? d.recent.map(rowRecent).join('') : '<div class="qs-row empty">لا توجد حركات ظاهرة</div>';
    if (d.totals) {
      const issued = parseInt(d.totals.issued || 0, 10);
      const done = parseInt(d.totals.done || 0, 10);
      const waiting = parseInt(d.totals.waiting || 0, 10);
      document.getElementById('issuedCount').textContent = issued;
      document.getElementById('remainingCount').textContent = waiting;
      document.getElementById('collectedAmount').textContent = `${(done * <?= json_encode($price) ?>).toFixed(3)} <?= e($currency) ?>`;
    }
    if (currentNo !== '---' && currentNo !== lastServed) {
      lastServed = currentNo;
      speak(`Now serving ticket number ${currentNo}`);
    }
  } catch(e) { console.error(e); }
}
setInterval(refreshScreen, queuePollMs);
</script>
<?php include __DIR__ . '/../layout/footer.php'; ?>
