<?php
session_start();
$page_title = 'My Order';
$active_nav = 'orders';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

// Active orders = anything still in progress, PLUS orders that were just
// served (completed) within the last 6 hours — so a guest can still call the
// server after their meal arrives (e.g. for the bill or anything else) until
// the dining session naturally ends.
$active_stmt = $conn->prepare(
    "SELECT o.*, r.name AS restaurant_name, r.address AS restaurant_address
     FROM orders o LEFT JOIN restaurants r ON o.restaurant_id = r.id
     WHERE o.user_id = ?
       AND ( o.order_status IN ('pending','confirmed','preparing','ready')
             OR (o.order_status = 'completed' AND o.updated_at >= (NOW() - INTERVAL 6 HOUR)) )
     ORDER BY o.created_at DESC"
);
$active_stmt->bind_param("i", $uid);
$active_stmt->execute();
$active = $active_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Which one are we tracking?
$sel_id = (int)($_GET['id'] ?? 0);
$order = null;
foreach ($active as $a) { if ($a['id'] == $sel_id) { $order = $a; break; } }
if (!$order && !empty($active)) { $order = $active[0]; }

$has_active = (bool)$order;

if ($has_active) {
    $order_id = (int)$order['id'];
    $items_stmt = $conn->prepare("SELECT * FROM order_items WHERE order_id=?");
    $items_stmt->bind_param("i", $order_id);
    $items_stmt->execute();
    $order_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $order_label = '#' . str_pad($order_id, 4, '0', STR_PAD_LEFT);
    $stage_index_map = ['pending'=>0,'confirmed'=>0,'preparing'=>1,'ready'=>2,'completed'=>3];
    $current_stage = $stage_index_map[$order['order_status']] ?? 0;
    $est_time = date('g:i A', strtotime($order['created_at']) + 20 * 60);

    $is_dinein = !empty($order['table_number']);
    $claimed   = !empty($order['assigned_to']);   // a waiter/runner has taken it

    $ready_desc = $claimed
        ? ($is_dinein ? 'On its way to your table' : 'Ready for pickup')
        : "Estimated around $est_time";

    $stages = [
        ['label' => 'Confirmed',      'desc' => "Order $order_label received"],
        ['label' => 'Preparing',      'desc' => 'The kitchen is making your meal'],
        ['label' => 'Ready',          'desc' => $ready_desc],
        ['label' => 'Served',         'desc' => 'Enjoy your meal!'],
    ];
    $hero = [
        0 => ['Order confirmed', "We'll let you know as it progresses"],
        1 => ['Being prepared', "Estimated serving around $est_time"],
        2 => $claimed
              ? ($is_dinein ? ['On its way', 'Your order is being brought to your table'] : ['Ready for pickup', 'Your order is ready — please collect it'])
              : ['Ready to be served', $is_dinein ? 'A server will bring it over shortly' : 'Almost ready for pickup'],
        3 => ['Served', 'Enjoy your meal!'],
    ][$current_stage];
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.or-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 18px; }
.sub-topbar-left { display: flex; align-items: center; gap: 12px; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; text-decoration: none; -webkit-tap-highlight-color: transparent; transition: background .15s; }
.sub-topbar .sub-back:active { background: #E3EBFB; }
.sub-topbar .icon-btn { color: var(--primary); }

/* ---- Empty state (simple) ---- */
.or-empty { text-align: center; padding: 70px 24px 40px; }
.or-empty .ee-ic { width: 84px; height: 84px; border-radius: 50%; background: var(--primary-bg); display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: var(--primary); }
.or-empty h3 { font-size: 1.15rem; font-weight: 800; margin-bottom: 8px; }
.or-empty p { font-size: .88rem; color: var(--text-muted); line-height: 1.55; max-width: 280px; margin: 0 auto 22px; }
.or-empty .cta { display: inline-flex; align-items: center; gap: 8px; background: var(--primary); color: #fff; font-weight: 700; padding: 13px 24px; border-radius: 14px; box-shadow: 0 6px 18px rgba(34,90,227,.3); text-decoration: none; }
.or-empty .hist-link { display: block; margin-top: 18px; color: var(--primary); font-weight: 700; font-size: .88rem; text-decoration: none; }

/* ---- Tracker ---- */
.or-switch { display: flex; gap: 8px; margin-bottom: 16px; overflow-x: auto; scrollbar-width: none; }
.or-switch::-webkit-scrollbar { display: none; }
.or-switch a { padding: 8px 14px; border-radius: 20px; font-size: .78rem; font-weight: 700; white-space: nowrap; border: 1.5px solid var(--border); background: #fff; color: var(--text-muted); text-decoration: none; flex-shrink: 0; }
.or-switch a.active { background: var(--primary); color: #fff; border-color: var(--primary); }

.or-hero { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); border-radius: 20px; padding: 24px 22px; color: #fff; box-shadow: 0 10px 26px rgba(34,90,227,.28); margin-bottom: 18px; }
.or-hero .oh-rest { font-size: .8rem; opacity: .85; margin-bottom: 6px; }
.or-hero .oh-title { font-size: 1.4rem; font-weight: 800; letter-spacing: -.02em; margin-bottom: 4px; }
.or-hero .oh-sub { font-size: .85rem; opacity: .9; }

.or-card { background: #fff; border: 1px solid var(--border); border-radius: 18px; box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 20px; margin-bottom: 16px; }

.stepper { position: relative; }
.step { display: flex; gap: 16px; position: relative; padding-bottom: 26px; }
.step:last-child { padding-bottom: 0; }
.step .s-line { position: absolute; left: 17px; top: 36px; bottom: -2px; width: 2px; background: var(--border); }
.step:last-child .s-line { display: none; }
.step .s-dot { width: 36px; height: 36px; border-radius: 50%; flex-shrink: 0; display: flex; align-items: center; justify-content: center; background: var(--bg); color: var(--text-light); border: 2px solid var(--border); z-index: 1; }
.step .s-dot svg { stroke: currentColor; fill: none; }
.step .s-body { padding-top: 6px; }
.step .s-label { font-weight: 800; font-size: .95rem; color: var(--text); }
.step .s-desc { font-size: .78rem; color: var(--text-muted); margin-top: 2px; }
/* states */
.step.done .s-dot { background: var(--success); border-color: var(--success); color: #fff; }
.step.done .s-line { background: var(--success); }
.step.active .s-dot { background: var(--primary); border-color: var(--primary); color: #fff; box-shadow: 0 0 0 5px var(--primary-bg); }
.step.active .s-label { color: var(--primary); }
.step.pending .s-label { color: var(--text-light); }

.or-sum-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
.or-sum-head h3 { font-size: 1rem; font-weight: 800; }
.or-item { display: flex; align-items: center; gap: 12px; padding: 10px 0; border-top: 1px solid var(--border); font-size: .88rem; }
.or-item:first-of-type { border-top: none; }
.or-item .q { width: 30px; height: 30px; border-radius: 9px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: .76rem; flex-shrink: 0; }
.or-item .nm { flex: 1; font-weight: 600; }
.or-item .pr { font-weight: 700; }
.or-total { display: flex; justify-content: space-between; border-top: 1.5px solid var(--border); margin-top: 10px; padding-top: 12px; }
.or-total .tl { font-weight: 800; }
.or-total .tv { font-weight: 800; color: var(--primary); font-size: 1.1rem; }

.or-actions { display: flex; flex-direction: column; gap: 10px; }
.or-btn { display: flex; align-items: center; justify-content: center; gap: 8px; height: 54px; border-radius: 14px; font-weight: 700; font-size: .95rem; border: none; cursor: pointer; font-family: var(--font); text-decoration: none; }
.or-btn.call { background: var(--primary); color: #fff; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.or-btn.call:active { background: var(--primary-dark); }
.or-btn.ghost { background: #fff; color: var(--primary); border: 1.5px solid var(--border); }
</style>

<div class="or-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="dashboard.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      </a>
      <span class="sub-title">My Order</span>
    </div>
    <a href="order_history.php" class="icon-btn" title="Order history">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v5h5"/><path d="M3.05 13A9 9 0 106 5.3L3 8"/><path d="M12 7v5l4 2"/></svg>
    </a>
  </div>

  <?php if (!$has_active): ?>
    <div class="or-empty">
      <div class="ee-ic"><svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L4 6v14a2 2 0 002 2h12a2 2 0 002-2V6l-2-4"/><path d="M4 6h16"/><path d="M9 10a3 3 0 006 0"/></svg></div>
      <h3>No active orders</h3>
      <p>When you place an order, you'll be able to track it here from confirmed to served.</p>
      <a href="scan.php" class="cta">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/><rect x="7" y="7" width="10" height="10" rx="1"/></svg>
        Scan &amp; Order
      </a>
      <a href="order_history.php" class="hist-link">View order history</a>
    </div>

  <?php else: ?>
    <?php if (count($active) > 1): ?>
    <div class="or-switch">
      <?php foreach ($active as $a): ?>
        <a href="orders.php?id=<?php echo (int)$a['id']; ?>" class="<?php echo $a['id']==$order_id?'active':''; ?>">#<?php echo str_pad($a['id'],4,'0',STR_PAD_LEFT); ?></a>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="or-hero">
      <div class="oh-rest"><?php echo htmlspecialchars($order['restaurant_name'] ?? 'Your order'); ?> · <?php echo $order_label; ?></div>
      <div class="oh-title" id="heroTitle"><?php echo $hero[0]; ?></div>
      <div class="oh-sub" id="heroSub"><?php echo $hero[1]; ?></div>
    </div>

    <div class="or-card">
      <div class="stepper" id="stepper">
        <?php foreach ($stages as $i => $st):
          $cls = $i < $current_stage ? 'done' : ($i === $current_stage ? 'active' : 'pending');
        ?>
        <div class="step <?php echo $cls; ?>" data-step="<?php echo $i; ?>">
          <span class="s-line"></span>
          <span class="s-dot">
            <svg width="17" height="17" viewBox="0 0 24 24" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          </span>
          <div class="s-body">
            <div class="s-label"><?php echo $st['label']; ?></div>
            <div class="s-desc"><?php echo htmlspecialchars($st['desc']); ?></div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <?php if (!empty($order_items)): ?>
    <div class="or-card">
      <div class="or-sum-head"><h3>Order Summary</h3></div>
      <?php $sum = 0; foreach ($order_items as $it): $line = (float)$it['price'] * (int)$it['quantity']; $sum += $line; ?>
      <div class="or-item">
        <span class="q"><?php echo (int)$it['quantity']; ?>x</span>
        <span class="nm"><?php echo htmlspecialchars($it['item_name']); ?></span>
        <span class="pr">₦<?php echo number_format($line, 2); ?></span>
      </div>
      <?php endforeach; ?>
      <div class="or-total"><span class="tl">Total</span><span class="tv">₦<?php echo number_format((float)$order['total_amount'], 2); ?></span></div>
    </div>
    <?php endif; ?>

    <div class="or-actions">
      <button class="or-btn call" id="callServer" data-order="<?php echo $order_id; ?>">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/></svg>
        Call Server
      </button>
      <a href="order_history.php" class="or-btn ghost">View Order History</a>
    </div>
  <?php endif; ?>
</div>

<?php if ($has_active): ?>
<div class="os-toast" id="orToast" style="position:fixed;bottom:calc(env(safe-area-inset-bottom) + 80px);left:50%;transform:translateX(-50%);background:#0F172A;color:#fff;padding:11px 20px;border-radius:30px;font-size:.82rem;font-weight:600;box-shadow:0 6px 20px rgba(0,0,0,.25);z-index:700;opacity:0;pointer-events:none;transition:opacity .25s;max-width:86%;text-align:center"></div>

<script>
(function () {
  const ORDER_ID = <?php echo $order_id; ?>;
  const IS_DINEIN = <?php echo $is_dinein ? 'true' : 'false'; ?>;
  const STAGE_INDEX = {pending:0, confirmed:0, preparing:1, ready:2, completed:3};
  const HERO = {
    0:['Order confirmed',"We'll let you know as it progresses"],
    1:['Being prepared','Your meal is being made'],
    3:['Served','Enjoy your meal!']
  };
  function heroFor(idx, claimed){
    if (idx === 2) {
      if (claimed) return IS_DINEIN ? ['On its way','Your order is being brought to your table'] : ['Ready for pickup','Your order is ready — please collect it'];
      return ['Ready to be served', IS_DINEIN ? 'A server will bring it over shortly' : 'Almost ready for pickup'];
    }
    return HERO[idx] || HERO[0];
  }
  let current = <?php echo $current_stage; ?>;
  let claimedState = <?php echo (!empty($order['assigned_to'])) ? 'true' : 'false'; ?>;

  function toast(m){const t=document.getElementById('orToast');t.textContent=m;t.style.opacity='1';clearTimeout(window._or);window._or=setTimeout(()=>t.style.opacity='0',2600);}

  function applyStage(idx, claimed){
    document.querySelectorAll('#stepper .step').forEach(step => {
      const i = +step.dataset.step;
      step.classList.remove('done','active','pending');
      step.classList.add(i < idx ? 'done' : (i === idx ? 'active' : 'pending'));
    });
    const h = heroFor(idx, claimed);
    document.getElementById('heroTitle').textContent = h[0];
    document.getElementById('heroSub').textContent = h[1];
    const rd = document.querySelector('#stepper .step[data-step="2"] .s-desc');
    if (rd) rd.textContent = claimed ? (IS_DINEIN ? 'On its way to your table' : 'Ready for pickup') : rd.textContent;
  }

  // Call server
  const cs = document.getElementById('callServer');
  if (cs) cs.addEventListener('click', function () {
    cs.disabled = true;
    const fd = new FormData(); fd.append('order_id', cs.dataset.order);
    fetch('call_server.php', { method:'POST', body: fd }).then(r=>r.json()).then(d=>{
      toast(d.ok ? 'A server has been notified — someone will be with you shortly.' : (d.error || "Couldn't reach the restaurant."));
    }).catch(()=>toast('Network error. Please try again.')).finally(()=>{ setTimeout(()=>cs.disabled=false, 4000); });
  });

  // Live polling
  setInterval(function () {
    fetch('order_status.php?id=' + ORDER_ID).then(r=>r.json()).then(d=>{
      if (d.error || !d.order_status) return;
      if (d.order_status === 'cancelled') { toast('This order was cancelled.'); setTimeout(()=>location.href='order_history.php', 1500); return; }
      const idx = STAGE_INDEX[d.order_status];
      if (idx === undefined) return;
      const claimed = !!d.accepted_by;
      const stageChanged = idx !== current;
      const justClaimed  = idx === 2 && claimed && !claimedState && !stageChanged;
      if (stageChanged || claimed !== claimedState) {
        current = idx; claimedState = claimed; applyStage(idx, claimed);
        if (justClaimed) toast(IS_DINEIN ? 'Your order is on its way to your table!' : 'Your order is ready for pickup!');
        else if (d.order_status === 'completed') toast('Your meal has been served — enjoy! You can still call the server if you need anything.');
        else if (stageChanged) toast('Order update: ' + d.order_status.charAt(0).toUpperCase() + d.order_status.slice(1));
        // Note: we intentionally do NOT navigate away when completed — the
        // served order stays on screen so "Call Server" remains available.
      }
    }).catch(()=>{});
  }, 8000);
})();
</script>
<?php endif; ?>

<?php include("includes/footer.php"); ?>
