<?php
require_once(__DIR__ . "/includes/auth.php");

// ---- Actions ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';

    // Acknowledge a "Call Server" request ("On my way")
    if ($act === 'ack_call') {
        $cid = (int)($_POST['call_id'] ?? 0);
        if ($cid && ($a = $conn->prepare("UPDATE service_calls SET status='ack', acked_by=?, acked_at=NOW() WHERE id=? AND restaurant_id=? AND status='open'"))) {
            $a->bind_param("iii", $__staff_id, $cid, $__rest_id); $a->execute();
        }
        $_SESSION['staff_flash'] = "On your way — the customer has been noted.";
        header("Location: waiter.php"); exit;
    }

    $oid = (int)($_POST['order_id'] ?? 0);
    $own = $conn->prepare("SELECT id, order_status, assigned_to FROM orders WHERE id=? AND restaurant_id=?");
    $own->bind_param("ii", $oid, $__rest_id); $own->execute();
    $ord = $own->get_result()->fetch_assoc();
    if ($ord) {
        if ($act === 'claim' && $ord['order_status'] === 'ready' && empty($ord['assigned_to'])) {
            $u = $conn->prepare("UPDATE orders SET assigned_to=?, updated_at=NOW() WHERE id=? AND (assigned_to IS NULL OR assigned_to=0)");
            $u->bind_param("ii", $__staff_id, $oid); $u->execute();
        } elseif ($act === 'hand' && $ord['order_status'] === 'ready' && (int)$ord['assigned_to'] === $__staff_id) {
            $u = $conn->prepare("UPDATE orders SET order_status='completed', updated_at=NOW() WHERE id=?");
            $u->bind_param("i", $oid); $u->execute();
        }
    }
    header("Location: waiter.php"); exit;
}

// ---- Data ----
// Claimable: ready & unassigned
$cl = $conn->prepare("SELECT o.*, u.name AS customer_name, rt.label AS loc_label,
                             (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) item_count
                      FROM orders o
                      LEFT JOIN users u ON u.id = o.user_id
                      LEFT JOIN restaurant_tables rt ON rt.restaurant_id = o.restaurant_id AND rt.table_number = o.table_number
                      WHERE o.restaurant_id=? AND o.order_status='ready' AND (o.assigned_to IS NULL OR o.assigned_to=0)
                      ORDER BY o.created_at ASC");
$cl->bind_param("i", $__rest_id); $cl->execute();
$claimable = $cl->get_result()->fetch_all(MYSQLI_ASSOC);

// Rushed orders surface to the top.
usort($claimable, function ($a, $b) {
    $r = ((int)($b['is_rushed'] ?? 0)) <=> ((int)($a['is_rushed'] ?? 0));
    return $r !== 0 ? $r : (strtotime($a['created_at']) <=> strtotime($b['created_at']));
});
$rush_count = 0; foreach ($claimable as $o) { if (!empty($o['is_rushed'])) $rush_count++; }

// Mine: ready & assigned to me
$mine_q = $conn->prepare("SELECT o.*, u.name AS customer_name, rt.label AS loc_label,
                                 (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) item_count
                          FROM orders o
                          LEFT JOIN users u ON u.id = o.user_id
                          LEFT JOIN restaurant_tables rt ON rt.restaurant_id = o.restaurant_id AND rt.table_number = o.table_number
                          WHERE o.restaurant_id=? AND o.order_status='ready' AND o.assigned_to=?
                          ORDER BY o.created_at ASC");
$mine_q->bind_param("ii", $__rest_id, $__staff_id); $mine_q->execute();
$mine = $mine_q->get_result()->fetch_all(MYSQLI_ASSOC);

function w_elapsed($created) {
    $mins = max(0, (int)floor((time() - strtotime($created)) / 60));
    $cls  = $mins < 10 ? 'ok' : ($mins <= 15 ? 'warn' : 'late');
    return [$mins, $cls];
}
$waiting = count($claimable);
$hot = 0; foreach ($claimable as $o) { if ((time() - strtotime($o['created_at'])) > 15 * 60) $hot++; }

// Open "Call Server" assistance requests (defensive — needs service_calls table)
$calls = [];
if ($cq = $conn->prepare("SELECT * FROM service_calls WHERE restaurant_id=? AND status='open' ORDER BY created_at ASC")) {
    $cq->bind_param("i", $__rest_id); $cq->execute();
    $calls = $cq->get_result()->fetch_all(MYSQLI_ASSOC);
}
$max_call_id = 0; foreach ($calls as $c) { $max_call_id = max($max_call_id, (int)$c['id']); }
$flash = $_SESSION['staff_flash'] ?? ''; unset($_SESSION['staff_flash']);

$page_title = 'Staff Portal';
$active_nav = 'orders';
include("includes/header.php");
?>

<style>
.wp-stats{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:22px}
.wp-stat{background:#fff;border:1px solid var(--border);border-radius:16px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:16px}
.wp-stat .l{font-size:.66rem;font-weight:800;letter-spacing:.08em;color:var(--text-light);margin-bottom:8px}
.wp-stat .v{font-size:1.4rem;font-weight:800;letter-spacing:-.02em}
.wp-stat .v.blue{color:var(--primary)}.wp-stat .v.red{color:var(--error)}

.ord-card{background:#fff;border:1px solid var(--border);border-radius:18px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:16px;margin-bottom:14px}
.ord-card.urgent{border-color:#FAD4D4}
.ord-top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:8px}
.tag{font-size:.66rem;font-weight:800;letter-spacing:.04em;padding:4px 10px;border-radius:20px}
.tag.urgent{background:var(--error-bg);color:var(--error)}
.tag.ready{background:var(--bg);color:var(--text-muted)}
.tag.mine{background:var(--primary-bg);color:var(--primary)}
.timer{font-size:.82rem;font-weight:800;display:flex;align-items:center;gap:4px}
.timer.ok{color:var(--text-muted)}.timer.warn{color:var(--warning)}.timer.late{color:var(--error)}
.ord-title{font-size:1.4rem;font-weight:800;letter-spacing:-.02em;line-height:1.1}
.ord-meta{font-size:.82rem;color:var(--text-muted);margin:2px 0 14px}
.btn{width:100%;border:none;border-radius:12px;font-family:var(--font);font-weight:700;font-size:.92rem;cursor:pointer;padding:13px;display:flex;align-items:center;justify-content:center;gap:8px}
.btn-primary{background:var(--primary);color:#fff}.btn-primary:active{background:var(--primary-dark)}
.btn-danger{background:var(--error);color:#fff}
.mine-card{background:var(--primary-bg);border:1.5px solid #C9D9F8;border-radius:18px;padding:16px;margin-bottom:14px}
.mine-card .m-check{width:26px;height:26px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.sec-label{font-size:.7rem;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--text-light);margin:18px 2px 12px}
.empty{text-align:center;color:var(--text-muted);font-size:.86rem;padding:28px 20px;background:#fff;border:1px dashed var(--border);border-radius:14px}
.ord-card.rushed{border-color:var(--error);box-shadow:0 0 0 2px rgba(220,38,38,.16),0 6px 20px rgba(220,38,38,.12)}
.tag.rush{background:var(--error);color:#fff}
.escalation{display:flex;align-items:center;gap:10px;background:var(--error);color:#fff;border-radius:14px;padding:13px 16px;margin-bottom:18px;font-weight:700;font-size:.86rem;box-shadow:0 8px 22px rgba(220,38,38,.3)}
.escalation svg{flex-shrink:0}
/* Call-server assistance alert */
.call-alert{background:#fff;border:1.5px solid var(--primary);border-radius:18px;box-shadow:0 12px 30px rgba(34,90,227,.18);padding:14px 16px;margin-bottom:18px}
.call-alert .ca-title{display:flex;align-items:center;gap:9px;font-weight:800;font-size:.92rem;color:var(--primary);margin-bottom:6px}
.call-alert .ca-bell{width:30px;height:30px;border-radius:50%;background:var(--primary-bg);color:var(--primary);display:flex;align-items:center;justify-content:center;flex-shrink:0;animation:ring 1.4s ease-in-out infinite}
@keyframes ring{0%,60%,100%{transform:rotate(0)}10%,30%,50%{transform:rotate(-12deg)}20%,40%{transform:rotate(12deg)}}
.ca-row{display:flex;align-items:center;gap:12px;padding:12px 0;border-top:1px solid var(--border)}
.ca-row .ca-meta{flex:1;min-width:0}
.ca-row .ca-name{font-weight:800;font-size:.98rem;letter-spacing:-.01em}
.ca-row .ca-sub{font-size:.78rem;color:var(--text-muted);margin-top:2px}
.ca-row .ca-btn{flex-shrink:0;border:none;background:var(--primary);color:#fff;font-family:var(--font);font-weight:700;font-size:.84rem;padding:11px 16px;border-radius:12px;cursor:pointer;display:flex;align-items:center;gap:6px}
.ca-row .ca-btn:active{background:var(--primary-dark)}
.toast{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}
</style>

<div class="page-head">
  <h1>Staff Portal</h1>
  <p>Welcome back, <?php echo htmlspecialchars(explode(' ', $__name)[0]); ?></p>
</div>

<?php if ($flash): ?><div class="banner ok"><?php echo htmlspecialchars($flash); ?></div><?php endif; ?>

<?php if ($rush_count > 0): ?>
<div class="escalation">
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
  Kitchen Escalation — <?php echo $rush_count; ?> rushed order<?php echo $rush_count === 1 ? '' : 's'; ?> to deliver now.
</div>
<?php endif; ?>

<?php if (!empty($calls)): ?>
<div class="call-alert">
  <div class="ca-title">
    <span class="ca-bell"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg></span>
    <?php echo count($calls); ?> customer<?php echo count($calls) === 1 ? '' : 's'; ?> calling for assistance
  </div>
  <?php foreach ($calls as $c):
    [$csrc, $csec] = order_source_label(['table_number' => $c['table_number'], 'loc_label' => $c['table_label']]);
    $cmins = max(0, (int)floor((time() - strtotime($c['created_at'])) / 60));
  ?>
  <div class="ca-row">
    <div class="ca-meta">
      <div class="ca-name"><?php echo htmlspecialchars($csrc); ?><?php echo $csec ? ' · ' . htmlspecialchars($csec) : ''; ?></div>
      <div class="ca-sub"><?php echo htmlspecialchars($c['customer_name'] ?: 'A customer'); ?> · <?php echo $cmins; ?>m ago</div>
    </div>
    <form method="POST"><input type="hidden" name="action" value="ack_call"><input type="hidden" name="call_id" value="<?php echo (int)$c['id']; ?>">
      <button class="ca-btn" type="submit"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>On my way</button>
    </form>
  </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="wp-stats">
  <div class="wp-stat"><div class="l">WAITING</div><div class="v blue"><?php echo $waiting; ?> Order<?php echo $waiting==1?'':'s'; ?></div></div>
  <div class="wp-stat"><div class="l">HOT ZONE</div><div class="v red"><?php echo $hot; ?> Priorit<?php echo $hot==1?'y':'ies'; ?></div></div>
</div>

<?php // My deliveries first
if ($mine): ?>
  <div class="sec-label">My Deliveries</div>
  <?php foreach ($mine as $o):
    [$src, $sec] = order_source_label($o);
    $cust = trim((string)($o['customer_name'] ?? ''));
  ?>
  <div class="mine-card">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">
      <span class="tag mine">MY DELIVERY</span>
      <span class="m-check"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>
    </div>
    <div class="ord-title">For <?php echo htmlspecialchars($src); ?></div>
    <div class="ord-meta"><?php if ($cust): ?><?php echo htmlspecialchars($cust); ?> · <?php endif; ?><?php if ($sec): ?><?php echo htmlspecialchars($sec); ?> · <?php endif; ?>Order #<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?> · <?php echo (int)$o['item_count']; ?> item<?php echo $o['item_count']==1?'':'s'; ?></div>
    <form method="POST"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="hand"><button class="btn btn-primary" type="submit">Hand to customer</button></form>
  </div>
  <?php endforeach; ?>
<?php endif; ?>

<div class="sec-label">Ready to Claim</div>
<?php if (!$claimable): ?>
  <div class="empty">No orders waiting to be claimed right now.</div>
<?php else: foreach ($claimable as $o):
  [$mins, $cls] = w_elapsed($o['created_at']);
  $rushed = !empty($o['is_rushed']);
  $urgent = $rushed || $mins > 15;
  if ($rushed) $cls = 'late';
  [$src, $sec] = order_source_label($o);
  $cust = trim((string)($o['customer_name'] ?? ''));
?>
<div class="ord-card <?php echo $rushed ? 'rushed' : ($urgent ? 'urgent' : ''); ?>">
  <div class="ord-top">
    <span class="tag <?php echo $rushed ? 'rush' : ($urgent ? 'urgent' : 'ready'); ?>"><?php echo $rushed ? 'RUSH' : ($urgent ? 'URGENT' : 'READY'); ?></span>
    <span class="timer <?php echo $cls; ?>"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2M9 2h6"/></svg><?php echo $mins; ?>m</span>
  </div>
  <div class="ord-title"><?php echo htmlspecialchars($src); ?></div>
  <div class="ord-meta"><?php if ($sec): ?><?php echo htmlspecialchars($sec); ?> · <?php endif; ?><?php if ($cust): ?><?php echo htmlspecialchars($cust); ?> · <?php endif; ?>Order #<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?> · <?php echo (int)$o['item_count']; ?> item<?php echo $o['item_count']==1?'':'s'; ?></div>
  <form method="POST"><input type="hidden" name="order_id" value="<?php echo $o['id']; ?>"><input type="hidden" name="action" value="claim">
    <button class="btn <?php echo $urgent ? 'btn-danger' : 'btn-primary'; ?>" type="submit">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3 8-8"/><path d="M20 12v6a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h9"/></svg>
      <?php echo $urgent ? 'Claim Rush Order' : 'Claim Order'; ?>
    </button>
  </form>
</div>
<?php endforeach; endif; ?>

<div class="toast" id="wToast"></div>
<script>
(function(){
  function toast(m){const t=document.getElementById('wToast');t.textContent=m;t.style.opacity='1';clearTimeout(window._w);window._w=setTimeout(()=>t.style.opacity='0',2600);}

  // Ask once so we can raise a real device notification when a table calls.
  if ('Notification' in window && Notification.permission === 'default') {
    try { Notification.requestPermission(); } catch (e) {}
  }

  let lastMax = <?php echo (int)$max_call_id; ?>;

  // Poll for new "Call Server" requests (faster than the full refresh).
  setInterval(function(){
    fetch('ajax/service_calls.php').then(r=>r.json()).then(d=>{
      if (!d || !Array.isArray(d.calls)) return;
      if (d.maxId > lastMax) {
        const fresh = d.calls.filter(c => c.id > lastMax);
        lastMax = d.maxId;
        fresh.forEach(c => {
          const where = c.src + (c.sec ? ' · ' + c.sec : '');
          if ('Notification' in window && Notification.permission === 'granted') {
            try { new Notification('🔔 Customer needs assistance', { body: where + ' — ' + c.name, icon: '../assets/img/noticon.png?v=2', badge: '../assets/img/noticon.png?v=2' }); } catch (e) {}
          }
        });
        toast('New assistance request from ' + (fresh[0] ? fresh[0].src : 'a table'));
        setTimeout(()=>location.reload(), 1400);
      }
    }).catch(()=>{});
  }, 12000);

  // Safety refresh to keep order timers/queues current.
  setTimeout(function(){ location.reload(); }, 30000);
})();
</script>

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