<?php
// restaurantadmin/includes/header.php
if (!ob_get_level()) ob_start(); // buffer output so header() redirects work after HTML has been sent
if (!isset($_SESSION)) session_start();

$allowed_roles = ['restaurant_admin','staff','waiter'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', $allowed_roles)) {
    header("Location: login.php"); exit;
}

include_once("config/db.php");

// Self-migration: orders.table_label stores the human origin of each order
// ("Table 5" / "ICT Office") — needed by orders, dashboard, history & poll.
$__c = @$conn->query("SHOW COLUMNS FROM orders LIKE 'table_label'");
if ($__c && $__c->num_rows === 0) @$conn->query("ALTER TABLE orders ADD COLUMN table_label VARCHAR(120) NULL DEFAULT NULL AFTER table_number");

$uid  = (int)$_SESSION['user_id'];
$role = $_SESSION['role'];

// Fetch user + restaurant
$u_stmt = $conn->prepare("SELECT u.*,r.name as restaurant_name,r.id as restaurant_id,r.logo as restaurant_logo,r.status as restaurant_status
    FROM users u
    LEFT JOIN restaurants r ON u.restaurant_id=r.id
    WHERE u.id=?");
$u_stmt->bind_param("i",$uid); $u_stmt->execute();
$__user = $u_stmt->get_result()->fetch_assoc();
if (!$__user || !$__user['restaurant_id']) { session_destroy(); header("Location: login.php"); exit; }
if (!$__user['restaurant_status']) {
    session_destroy();
    header("Location: login.php?err=inactive"); exit;
}

$__name      = $__user['name'];
$__email     = $__user['email'];
$__rid       = (int)$__user['restaurant_id'];
$__rest_name = $__user['restaurant_name'];
$__initials  = strtoupper(substr($__name,0,1)).(strpos($__name,' ')!==false?strtoupper(substr(strrchr($__name,' '),1,1)):'');

// Unread notifications for this restaurant
$notif_stmt = $conn->prepare("SELECT COUNT(*) FROM notifications WHERE restaurant_id=? AND is_read=0");
$notif_stmt->bind_param("i",$__rid); $notif_stmt->execute();
$__unread_notifs = $notif_stmt->get_result()->fetch_row()[0];

// Pending orders count
$pend_stmt = $conn->prepare("SELECT COUNT(*) FROM orders WHERE restaurant_id=? AND order_status='pending'");
$pend_stmt->bind_param("i",$__rid); $pend_stmt->execute();
$__pending_orders = $pend_stmt->get_result()->fetch_row()[0];

$__page_title = $page_title ?? 'Dashboard';
$__active     = $active_nav ?? 'dashboard';
$is_admin     = ($role === 'restaurant_admin');

// Restaurant Dabil wallet balance
$_wbal = $conn->query("SELECT COALESCE(balance,0) FROM wallets WHERE restaurant_id={$__rid} AND wallet_type='restaurant' LIMIT 1")->fetch_row();
$__wallet_balance = $_wbal ? (float)$_wbal[0] : 0.00;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?php echo htmlspecialchars($__page_title); ?> — <?php echo htmlspecialchars($__rest_name); ?></title>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --primary:#225AE3;--primary-dark:#1a47b8;--primary-light:#4f79ea;
  --primary-bg:#EEF3FD;--bg:#F5F7F8;--white:#FFFFFF;
  --text:#0F172A;--text-muted:#64748B;--text-light:#94A3B8;
  --border:#E2E8F0;--border-dark:#CBD5E1;
  --success:#10B981;--success-bg:#F0FDF4;
  --error:#EF4444;--error-bg:#FEF2F2;
  --warning:#F59E0B;--warning-bg:#FFFBEB;
  --info:#06B6D4;--info-bg:#ECFEFF;
  --purple:#8B5CF6;--purple-bg:#F5F3FF;
  --sidebar-w:268px;--topbar-h:64px;
  --radius:12px;--radius-lg:16px;
  --shadow-sm:0 1px 3px rgba(0,0,0,.07);
  --shadow-md:0 4px 16px rgba(0,0,0,.08);
  --shadow-lg:0 8px 30px rgba(34,90,227,.14);
  --font:'Plus Jakarta Sans',sans-serif;
}
body{font-family:var(--font);background:var(--bg);color:var(--text);min-height:100vh}
a{text-decoration:none;color:inherit}
button{font-family:var(--font)}
img{max-width:100%}

/* ── SIDEBAR ── */
.sidebar{position:fixed;top:0;left:0;width:var(--sidebar-w);height:100vh;background:var(--white);border-right:1px solid var(--border);display:flex;flex-direction:column;z-index:200;transition:transform .3s cubic-bezier(.4,0,.2,1)}
.sidebar-brand{padding:0 20px;height:var(--topbar-h);display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--border);flex-shrink:0}
.brand-icon{width:36px;height:36px;background:var(--primary);border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0;overflow:hidden}
.brand-icon img{width:100%;height:100%;object-fit:cover}
.brand-icon svg{width:18px;height:18px;stroke:#fff;fill:none}
.brand-texts{flex:1;min-width:0}
.brand-name{font-size:.95rem;font-weight:800;letter-spacing:-0.02em;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.brand-sub{font-size:.65rem;color:var(--text-muted);font-weight:500}

.sidebar-scroll{flex:1;overflow-y:auto;padding:14px 10px}
.sidebar-scroll::-webkit-scrollbar{width:3px}
.sidebar-scroll::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px}
.nav-section{margin-bottom:22px}
.nav-label{font-size:.63rem;font-weight:700;text-transform:uppercase;letter-spacing:.14em;color:var(--text-light);padding:0 12px;margin-bottom:5px;display:flex;align-items:center;gap:6px}
.nav-item{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;cursor:pointer;transition:all .15s;color:var(--text-muted);font-size:.845rem;font-weight:500;margin-bottom:2px;position:relative}
.nav-item:hover{background:var(--bg);color:var(--text)}
.nav-item.active{background:var(--primary-bg);color:var(--primary);font-weight:700}
.nav-item.active::before{content:'';position:absolute;left:0;top:22%;bottom:22%;width:3px;background:var(--primary);border-radius:0 3px 3px 0;margin-left:-10px}
.nav-item svg{width:17px;height:17px;flex-shrink:0}
.nav-badge{margin-left:auto;font-size:.62rem;padding:2px 7px;border-radius:20px;font-weight:700;color:#fff}
.nav-badge.red{background:var(--error)}
.nav-badge.blue{background:var(--primary)}
.nav-badge.green{background:var(--success)}
.nav-badge.orange{background:var(--warning)}

.sidebar-footer{border-top:1px solid var(--border);padding:14px 10px;flex-shrink:0}
.user-pill{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;background:var(--bg)}
.avatar{width:33px;height:33px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;color:#fff;flex-shrink:0}
.user-details{flex:1;overflow:hidden}
.user-details .uname{font-size:.8rem;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.user-details .urole{font-size:.68rem;color:var(--text-muted)}

/* ── TOPBAR ── */
.topbar{position:fixed;top:0;left:var(--sidebar-w);right:0;height:var(--topbar-h);background:var(--white);border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;padding:0 24px;z-index:100;transition:left .3s}
.topbar-left{display:flex;align-items:center;gap:10px}
.hamburger{display:none;background:none;border:none;cursor:pointer;padding:7px;border-radius:8px;color:var(--text-muted)}
.hamburger svg{width:20px;height:20px;stroke:currentColor;fill:none}
.page-label{font-size:.95rem;font-weight:700;letter-spacing:-0.01em}
.topbar-right{display:flex;align-items:center;gap:10px}

/* Notification Bell */
.notif-btn{position:relative;width:38px;height:38px;border-radius:10px;background:var(--bg);border:1.5px solid var(--border);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s}
.notif-btn:hover{background:var(--primary-bg);border-color:rgba(34,90,227,.3)}
.notif-btn svg{width:18px;height:18px;stroke:var(--text-muted);fill:none}
.notif-dot{position:absolute;top:6px;right:6px;width:8px;height:8px;background:var(--error);border-radius:50%;border:2px solid var(--white);display:none}
.notif-dot.show{display:block;animation:pulse 2s infinite}
@keyframes pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.3)}}

/* Sound Alert Toggle */
.sound-btn{position:relative;width:38px;height:38px;border-radius:10px;background:var(--bg);border:1.5px solid var(--border);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s}
.sound-btn:hover{background:var(--primary-bg);border-color:rgba(34,90,227,.3)}
.sound-btn svg{width:18px;height:18px;stroke:var(--text-muted);fill:none;transition:stroke .2s}
.sound-btn.on svg{stroke:var(--primary)}
.sound-btn.muted svg{stroke:var(--error)}
.sound-btn.ring{animation:ringShake .5s ease}
@keyframes ringShake{0%,100%{transform:rotate(0)}20%{transform:rotate(-12deg)}40%{transform:rotate(10deg)}60%{transform:rotate(-8deg)}80%{transform:rotate(6deg)}}

/* Notification Dropdown */
.notif-dropdown{position:absolute;top:calc(var(--topbar-h) + 6px);right:70px;width:340px;background:var(--white);border:1px solid var(--border);border-radius:16px;box-shadow:0 12px 40px rgba(0,0,0,.12);z-index:300;display:none;max-height:420px;overflow:hidden;flex-direction:column}
.notif-dropdown.open{display:flex}
.notif-header{padding:16px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-shrink:0}
.notif-header h4{font-size:.9rem;font-weight:800}
.notif-mark-all{font-size:.75rem;color:var(--primary);font-weight:600;cursor:pointer;background:none;border:none;font-family:var(--font)}
.notif-list{overflow-y:auto;flex:1}
.notif-item{display:flex;gap:12px;padding:13px 18px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .15s}
.notif-item:hover{background:var(--bg)}
.notif-item.unread{background:var(--primary-bg)}
.notif-item:last-child{border-bottom:none}
.notif-icon{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.notif-icon svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round}
.notif-content .ntitle{font-size:.82rem;font-weight:700;margin-bottom:2px}
.notif-content .ntime{font-size:.7rem;color:var(--text-muted)}
.notif-content .nmsg{font-size:.77rem;color:var(--text-muted);margin-top:2px;line-height:1.4}
.notif-empty{padding:40px 20px;text-align:center;color:var(--text-muted);font-size:.85rem}

/* Order alert pulse (for staff) */
.order-alert{display:none;position:fixed;bottom:24px;right:24px;background:var(--primary);color:#fff;border-radius:16px;padding:14px 20px;box-shadow:0 8px 30px rgba(34,90,227,.4);z-index:400;cursor:pointer;max-width:300px;animation:slideUp .4s ease}
.order-alert.show{display:flex;align-items:center;gap:12px}
@keyframes slideUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:none}}

/* ── LAYOUT ── */
.layout{display:flex;min-height:100vh}
.main-content{margin-left:var(--sidebar-w);margin-top:var(--topbar-h);flex:1;min-width:0;max-width:100%;padding:28px;min-height:calc(100vh - var(--topbar-h))}

/* ── CARDS ── */
.card{background:var(--white);border-radius:var(--radius-lg);border:1px solid var(--border);box-shadow:var(--shadow-sm)}
.card-header{padding:18px 22px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap}
.card-header h3{font-size:.95rem;font-weight:700}
.card-body{padding:20px 22px}

/* ── BUTTONS ── */
.btn{display:inline-flex;align-items:center;justify-content:center;gap:7px;border-radius:10px;border:none;cursor:pointer;font-family:var(--font);font-weight:600;transition:all .2s;white-space:nowrap}
.btn-primary{background:var(--primary);color:#fff;box-shadow:var(--shadow-lg)}
.btn-primary:hover{background:var(--primary-dark);transform:translateY(-1px)}
.btn-secondary{background:var(--bg);color:var(--text);border:1.5px solid var(--border)}
.btn-secondary:hover{background:var(--border)}
.btn-danger{background:var(--error);color:#fff}
.btn-danger:hover{background:#dc2626;transform:translateY(-1px)}
.btn-success{background:var(--success);color:#fff}
.btn-success:hover{background:#059669;transform:translateY(-1px)}
.btn-warning{background:var(--warning);color:#fff}
.btn-warning:hover{background:#d97706;transform:translateY(-1px)}
.btn-sm{padding:7px 12px;font-size:.78rem}
.btn-md{padding:10px 18px;font-size:.875rem}
.btn-lg{padding:13px 24px;font-size:.9rem}
.btn-block{width:100%}
.btn svg{width:15px;height:15px;stroke:currentColor;fill:none}

/* ── BADGES ── */
.badge{padding:3px 10px;border-radius:20px;font-size:.7rem;font-weight:700;display:inline-flex;align-items:center;gap:4px}
.badge-success{background:var(--success-bg);color:var(--success)}
.badge-warning{background:var(--warning-bg);color:var(--warning)}
.badge-error{background:var(--error-bg);color:var(--error)}
.badge-primary{background:var(--primary-bg);color:var(--primary)}
.badge-info{background:var(--info-bg);color:var(--info)}
.badge-purple{background:var(--purple-bg);color:var(--purple)}
.badge-muted{background:var(--bg);color:var(--text-muted)}

/* ── TABLE ── */
.data-table{width:100%;border-collapse:collapse}
.data-table th{text-align:left;padding:10px 16px;font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);background:var(--bg);border-bottom:1px solid var(--border)}
.data-table td{padding:12px 16px;font-size:.84rem;border-bottom:1px solid var(--border)}
.data-table tr:last-child td{border-bottom:none}
.data-table tbody tr:hover td{background:var(--bg)}
.table-scroll{width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}
@media(max-width:768px){.table-scroll .data-table{min-width:640px}}

/* ── ALERTS ── */
.alert{padding:12px 16px;border-radius:10px;font-size:.82rem;font-weight:500;display:flex;align-items:center;gap:10px;margin-bottom:18px}
.alert svg{width:16px;height:16px;stroke:currentColor;fill:none;flex-shrink:0}
.alert-success{background:var(--success-bg);color:var(--success);border:1px solid #BBF7D0}
.alert-error{background:var(--error-bg);color:var(--error);border:1px solid #FECACA}
.alert-warning{background:var(--warning-bg);color:var(--warning);border:1px solid #FDE68A}
.alert-info{background:var(--primary-bg);color:var(--primary);border:1px solid rgba(34,90,227,.2)}

/* ── FORM ── */
.form-group{margin-bottom:18px}
.form-group label{display:block;font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);margin-bottom:7px}
.form-control{width:100%;height:46px;border:1.5px solid var(--border);border-radius:10px;background:var(--bg);padding:0 14px;font-size:.875rem;color:var(--text);font-family:var(--font);outline:none;transition:all .2s}
.form-control:focus{border-color:var(--primary);background:var(--white);box-shadow:0 0 0 3px rgba(34,90,227,.1)}
.form-control::placeholder{color:var(--text-light)}
textarea.form-control{height:auto;padding:12px 14px;resize:vertical;min-height:80px}
select.form-control{cursor:pointer}

/* ── MODAL ── */
.modal-backdrop{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:500;backdrop-filter:blur(3px);align-items:center;justify-content:center;padding:20px}
.modal-backdrop.open{display:flex}
.modal{background:var(--white);border-radius:20px;width:100%;max-width:520px;box-shadow:0 20px 60px rgba(0,0,0,.2);animation:modalIn .25s ease;max-height:90vh;display:flex;flex-direction:column}
.modal-lg{max-width:680px}
.modal-header{padding:20px 24px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-shrink:0}
.modal-header h3{font-size:1rem;font-weight:800}
.modal-close{background:none;border:none;cursor:pointer;width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--text-muted);transition:background .2s}
.modal-close:hover{background:var(--bg)}
.modal-close svg{width:18px;height:18px;stroke:currentColor;fill:none}
.modal-body{padding:24px;overflow-y:auto;flex:1}
.modal-footer{padding:16px 24px;border-top:1px solid var(--border);display:flex;gap:10px;justify-content:flex-end;flex-shrink:0}
@keyframes modalIn{from{opacity:0;transform:translateY(14px) scale(.98)}to{opacity:1;transform:none}}

/* ── OVERLAY ── */
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:199;backdrop-filter:blur(2px)}
.overlay.active{display:block}

/* ── GRID HELPERS ── */
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.grid-4{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
@media(max-width:900px){.grid-4{grid-template-columns:repeat(2,1fr)}.grid-3{grid-template-columns:1fr 1fr}}
@media(max-width:600px){.grid-2,.grid-3,.grid-4{grid-template-columns:1fr}}

/* ── MOBILE ── */
@media(max-width:1024px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .topbar{left:0}
  .main-content{margin-left:0}
  .hamburger{display:flex}
  .notif-dropdown{right:12px;width:calc(100vw - 24px)}
}
@media(max-width:640px){
  .main-content{padding:20px 14px}
  .page-label{display:none}
}

/* ── ANIMATIONS ── */
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
@keyframes spin{to{transform:rotate(360deg)}}
.anim-up{animation:fadeUp .4s ease both}

/* ── Responsive patch: fluid inline grids, tables & modals on small screens ── */
img,video,canvas{max-width:100%}
@media(max-width:900px){
  [style*="grid-template-columns:repeat(4"]{grid-template-columns:repeat(2,1fr)!important}
}
@media(max-width:768px){
  [style*="grid-template-columns:repeat(3"]{grid-template-columns:repeat(2,1fr)!important}
  .data-table{font-size:.82rem}
  .data-table th,.data-table td{padding:10px 12px;white-space:nowrap}
}
@media(max-width:560px){
  [style*="grid-template-columns:repeat(4"],
  [style*="grid-template-columns:repeat(3"],
  [style*="grid-template-columns:repeat(2"]{grid-template-columns:1fr!important}
  .modal-footer{flex-wrap:wrap}
  .modal-footer .btn,.modal-footer button{flex:1 1 auto}
}

/* ── Restaurant admin mobile hardening ── */
html,body{max-width:100%;overflow-x:hidden}
[style*="display:grid"]>*,[style*="display:flex"]>*{min-width:0}
@media(max-width:1024px){
  [style*="grid-template-columns:1fr 3"]{grid-template-columns:1fr!important}
  [style*="grid-template-columns:auto 1fr"]{grid-template-columns:1fr!important}
}
@media(max-width:560px){
  [style*="grid-template-columns:1fr 1fr"]{grid-template-columns:1fr!important}
}
</style>
</head>
<body>

<div class="overlay" id="overlay" onclick="closeSidebar()"></div>

<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-brand">
    <div class="brand-icon">
      <?php if($__user['restaurant_logo']): ?>
        <img src="uploads/logos/<?php echo htmlspecialchars($__user['restaurant_logo']); ?>" alt="">
      <?php else: ?>
        <svg viewBox="0 0 24 24" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
      <?php endif; ?>
    </div>
    <div class="brand-texts">
      <div class="brand-name"><?php echo htmlspecialchars($__rest_name); ?></div>
      <div class="brand-sub">Restaurant Portal</div>
    </div>
  </div>

  <div class="sidebar-scroll">
    <div class="nav-section">
      <div class="nav-label">Overview</div>
      <a href="dashboard.php" class="nav-item <?php echo $__active==='dashboard'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/></svg>
        Dashboard
      </a>
      <a href="analytics.php" class="nav-item <?php echo $__active==='analytics'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9M13 17V5M8 17v-4"/></svg>
        Analytics
      </a>

          <a href="broadcast.php" class="nav-item <?php echo $__active==='broadcast'?'active':''; ?>">
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
    <line x1="22" y1="2" x2="11" y2="13"/>
    <polygon points="22 2 15 22 11 13 2 9 22 2"/>
  </svg>
  Broadcast
</a>
    </div>

    <div class="nav-section">
      <div class="nav-label">Orders</div>
      <a href="orders.php" class="nav-item <?php echo $__active==='orders'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/><path d="M9 12h6M9 16h4"/></svg>
        Live Orders
        <?php if($__pending_orders>0): ?><span class="nav-badge red"><?php echo $__pending_orders; ?></span><?php endif; ?>
      </a>
      <a href="order_history.php" class="nav-item <?php echo $__active==='order_history'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
        Order History
      </a>
    </div>

    <div class="nav-section">
      <div class="nav-label">Menu</div>
      <a href="menu.php" class="nav-item <?php echo $__active==='menu'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M4 6h16M4 10h16M4 14h16M4 18h7"/></svg>
        Menu Items
      </a>
      <a href="categories.php" class="nav-item <?php echo $__active==='categories'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M3 3h7v7H3zM14 3h7v7h-7zM14 14h7v7h-7zM3 14h7v7H3z"/></svg>
        Categories
      </a>
      <a href="menu_qr.php" class="nav-item <?php echo $__active==='menu_qr'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" 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>
        Menu QR Codes
      </a>
    </div>

    <div class="nav-section">
      <div class="nav-label">Tables & QR</div>
      <a href="tables.php" class="nav-item <?php echo $__active==='tables'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><rect x="3" y="8" width="18" height="8" rx="2"/><path d="M6 8V6a1 1 0 011-1h10a1 1 0 011 1v2M8 16v2M16 16v2"/></svg>
        Tables & QR Codes
      </a>
      <a href="qr_scans.php" class="nav-item <?php echo $__active==='qr_scans'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" 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>
        QR Scan Activity
      </a>
    </div>

    <?php if($is_admin): ?>
    <div class="nav-section">
      <div class="nav-label">Team</div>
      <a href="staff.php" class="nav-item <?php echo $__active==='staff'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
        Staff Management
      </a>
      <a href="shifts.php" class="nav-item <?php echo $__active==='shifts'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
        Shifts
      </a>
    </div>
    <?php endif; ?>

    <div class="nav-section">
      <div class="nav-label">Finance</div>
      <a href="payments.php" class="nav-item <?php echo $__active==='payments'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M7 20V4l10 16V4M4 10h16M4 14h16"/></svg>
        Payments
      </a>
      <?php if($is_admin): ?>
      <a href="wallet.php" class="nav-item <?php echo $__active==='wallet'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
        <?php echo htmlspecialchars($__rest_name); ?> Wallet
        <span class="nav-badge green" style="font-size:.58rem;padding:2px 6px">₦<?php echo number_format($__wallet_balance,0); ?></span>
      </a>
      <?php endif; ?>
    </div>

    <div class="nav-section">
      <div class="nav-label">Notifications</div>
      <a href="notifications.php" class="nav-item <?php echo $__active==='notifications'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>
        Notifications
        <?php if($__unread_notifs>0): ?><span class="nav-badge red"><?php echo $__unread_notifs; ?></span><?php endif; ?>
      </a>
    </div>
    

    

    <?php if($is_admin): ?>
    <div class="nav-section">
      <div class="nav-label">Settings</div>
      <a href="settings.php" class="nav-item <?php echo $__active==='settings'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
        Restaurant Settings
      </a>
      <a href="feedback.php" class="nav-item <?php echo $__active==='feedback'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>
        Customer Feedback
      </a>
    </div>
    <?php endif; ?>

    <div class="nav-section">
      <a href="profile.php" class="nav-item <?php echo $__active==='profile'?'active':''; ?>">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        My Profile
      </a>
      <a href="logout.php" class="nav-item" style="color:var(--error)">
        <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
        Logout
      </a>
    </div>
  </div>

  <div class="sidebar-footer">
    <?php if($is_admin): ?>
    <a href="wallet.php" style="display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;background:linear-gradient(135deg,#225AE3,#4f79ea);margin-bottom:10px;text-decoration:none;transition:opacity .2s" onmouseover="this.style.opacity='.9'" onmouseout="this.style.opacity='1'">
      <div style="width:30px;height:30px;border-radius:8px;background:rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
      </div>
      <div style="flex:1;overflow:hidden">
        <div style="font-size:.62rem;font-weight:600;color:rgba(255,255,255,.75);text-transform:uppercase;letter-spacing:.08em"><?php echo htmlspecialchars($__rest_name); ?> Wallet</div>
        <div style="font-size:.92rem;font-weight:800;color:#fff">₦<?php echo number_format($__wallet_balance,2); ?></div>
      </div>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.6)" stroke-width="2" stroke-linecap="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg>
    </a>
    <?php endif; ?>
    <div class="user-pill">
      <div class="avatar"><?php echo $__initials; ?></div>
      <div class="user-details">
        <div class="uname"><?php echo htmlspecialchars($__name); ?></div>
        <div class="urole"><?php echo ucfirst(str_replace('_',' ',$role)); ?></div>
      </div>
    </div>
  </div>
</aside>

<!-- Topbar -->
<header class="topbar">
  <div class="topbar-left">
    <button class="hamburger" onclick="toggleSidebar()">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
    </button>
    <span class="page-label"><?php echo htmlspecialchars($__page_title); ?></span>
  </div>
  <div class="topbar-right">
    <!-- Order Alert Sound Toggle -->
    <div class="sound-btn" id="soundBtn" onclick="toggleSound()" title="Order alert sound">
      <svg id="soundOnIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 010 7.07M18.36 5.64a9 9 0 010 12.72"/></svg>
      <svg id="soundOffIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><path d="M11 5 6 9H2v6h4l5 4V5z"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>
    </div>

    <!-- Notification Bell -->
    <div style="position:relative">
      <div class="notif-btn" id="notifBtn" onclick="toggleNotifDropdown()">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>
        <div class="notif-dot <?php echo $__unread_notifs>0?'show':''; ?>" id="notifDot"></div>
      </div>
      <!-- Notification Dropdown -->
      <div class="notif-dropdown" id="notifDropdown">
        <div class="notif-header">
          <h4>Notifications <?php if($__unread_notifs>0): ?><span style="color:var(--error);font-size:.78rem">(<?php echo $__unread_notifs; ?> new)</span><?php endif; ?></h4>
          <button class="notif-mark-all" onclick="markAllRead()">Mark all read</button>
        </div>
        <div class="notif-list" id="notifList">
          <div class="notif-empty">Loading…</div>
        </div>
      </div>
    </div>

    <!-- Pending orders chip -->
    <?php if($__pending_orders>0): ?>
    <a href="orders.php" style="display:flex;align-items:center;gap:7px;background:var(--error-bg);border:1.5px solid rgba(239,68,68,.3);border-radius:24px;padding:6px 12px;font-size:.78rem;font-weight:700;color:var(--error)">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
      <?php echo $__pending_orders; ?> pending
    </a>
    <?php endif; ?>

    <!-- Wallet shortcut (admin only) -->
    <?php if($is_admin): ?>
    <a href="wallet.php" style="display:flex;align-items:center;gap:7px;background:var(--success-bg);border:1.5px solid rgba(16,185,129,.25);border-radius:24px;padding:6px 12px;text-decoration:none;transition:all .2s" onmouseover="this.style.background='var(--success)';this.style.borderColor='var(--success)';this.querySelectorAll('svg,span').forEach(e=>e.style.cssText='stroke:#fff;color:#fff')" onmouseout="this.style.background='var(--success-bg)';this.style.borderColor='rgba(16,185,129,.25)';this.querySelectorAll('svg,span').forEach(e=>e.style.cssText='')">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" stroke-linecap="round"><path d="M21 12V7H5a2 2 0 010-4h15a1 1 0 011 1v4"/><path d="M3 5v14a2 2 0 002 2h16v-5"/><path d="M18 12a2 2 0 000 4h4v-4z"/></svg>
      <span style="font-size:.78rem;font-weight:700;color:var(--success)">₦<?php echo number_format($__wallet_balance,0); ?></span>
    </a>
    <?php endif; ?>

    <div class="topbar-avatar" style="width:36px;height:36px;border-radius:50%;background:var(--primary);display:flex;align-items:center;justify-content:center;font-size:.72rem;font-weight:800;color:#fff;cursor:pointer" onclick="window.location='profile.php'">
      <?php echo $__initials; ?>
    </div>
  </div>
</header>

<!-- Order Alert Toast (for staff) -->
<div class="order-alert" id="orderAlert" onclick="window.location='orders.php'">
  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9"/><circle cx="12" cy="19" r="1"/></svg>
  <div>
    <div style="font-weight:700;font-size:.85rem" id="alertTitle">New Order!</div>
    <div style="font-size:.75rem;opacity:.85" id="alertMsg">A customer just placed an order</div>
  </div>
</div>

<div class="layout">
<main class="main-content">

<script>
const RESTAURANT_ID = <?php echo $__rid; ?>;
const USER_ROLE = '<?php echo $role; ?>';

/* ── Sidebar ── */
function toggleSidebar(){ document.getElementById('sidebar').classList.toggle('open'); document.getElementById('overlay').classList.toggle('active'); }
function closeSidebar(){ document.getElementById('sidebar').classList.remove('open'); document.getElementById('overlay').classList.remove('active'); }

/* ── Modal helpers ── */
function openModal(id){ var el=document.getElementById(id); if(!el) return; if(el.parentNode!==document.body){ document.body.appendChild(el); } el.classList.add('open'); }
function closeModal(id){ document.getElementById(id).classList.remove('open'); }
document.addEventListener('click', function(e){
  document.querySelectorAll('.modal-backdrop').forEach(m=>{ if(e.target===m) m.classList.remove('open'); });
  if(!e.target.closest('#notifBtn') && !e.target.closest('#notifDropdown')) {
    document.getElementById('notifDropdown').classList.remove('open');
  }
});

/* ── Notifications ── */
function toggleNotifDropdown(){
  const d = document.getElementById('notifDropdown');
  d.classList.toggle('open');
  if(d.classList.contains('open')) loadNotifications();
}
function loadNotifications(){
  fetch('ajax/notifications.php?rid='+RESTAURANT_ID)
    .then(r=>r.json())
    .then(data=>{
      const list = document.getElementById('notifList');
      if(!data.length){ list.innerHTML='<div class="notif-empty">No notifications yet</div>'; return; }
      const typeMap = {
        qr_scan:    {icon:'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 M9 9h6v6H9z', bg:'var(--primary-bg)', stroke:'var(--primary)'},
        new_order:  {icon:'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2 M9 3h6v4H9z', bg:'var(--warning-bg)', stroke:'var(--warning)'},
        payment_received:{icon:'M7 20V4l10 16V4M4 10h16M4 14h16', bg:'var(--success-bg)', stroke:'var(--success)'},
        order_ready:{icon:'M22 11.08V12a10 10 0 11-5.93-9.14 M22 4 12 14.01 9 11.01', bg:'var(--success-bg)', stroke:'var(--success)'},
      };
      list.innerHTML = data.map(n=>{
        const t = typeMap[n.type]||typeMap['new_order'];
        const ago = timeAgo(n.created_at);
        return `<div class="notif-item ${n.is_read=='0'?'unread':''}" onclick="markRead(${n.id},this,'${n.related_id}','${n.type}')">
          <div class="notif-icon" style="background:${t.bg}"><svg viewBox="0 0 24 24" stroke="${t.stroke}"><path d="${t.icon}"/></svg></div>
          <div class="notif-content">
            <div class="ntitle">${n.title}</div>
            <div class="nmsg">${n.message||''}</div>
            <div class="ntime">${ago}</div>
          </div>
        </div>`;
      }).join('');
    }).catch(()=>{ document.getElementById('notifList').innerHTML='<div class="notif-empty">Could not load notifications</div>'; });
}
function markRead(id, el, relatedId, type){
  el.classList.remove('unread');
  fetch('ajax/notifications.php?action=read&id='+id);
  if(type==='new_order'||type==='order_ready') window.location='orders.php';
  if(type==='qr_scan') window.location='qr_scans.php';
}
function markAllRead(){
  fetch('ajax/notifications.php?action=read_all&rid='+RESTAURANT_ID)
    .then(()=>{ document.querySelectorAll('.notif-item.unread').forEach(el=>el.classList.remove('unread')); document.getElementById('notifDot').classList.remove('show'); });
}
function timeAgo(dateStr){
  const d = new Date(dateStr.replace(' ','T'));
  const s = Math.floor((Date.now()-d)/1000);
  if(s<60) return 'just now';
  if(s<3600) return Math.floor(s/60)+'m ago';
  if(s<86400) return Math.floor(s/3600)+'h ago';
  return Math.floor(s/86400)+'d ago';
}

/* ── Order Alert Sound ──
   Synthesized via the Web Audio API — no audio file/asset needed.
   Preference is remembered per-browser in localStorage. Browsers block
   audio until a user gesture, so we "prime" the AudioContext on first
   click/keypress/touch anywhere on the page. */
let __soundEnabled = localStorage.getItem('dabil_sound_enabled') !== '0';
let __audioCtx = null;

function updateSoundIcon(){
  const btn = document.getElementById('soundBtn');
  const on  = document.getElementById('soundOnIcon');
  const off = document.getElementById('soundOffIcon');
  if(__soundEnabled){
    on.style.display='block'; off.style.display='none';
    btn.classList.add('on'); btn.classList.remove('muted');
    btn.title='Order alert sound: ON (click to mute)';
  } else {
    on.style.display='none'; off.style.display='block';
    btn.classList.remove('on'); btn.classList.add('muted');
    btn.title='Order alert sound: muted (click to enable)';
  }
}
function ensureAudioCtx(){
  if(!__audioCtx){
    try{ __audioCtx = new (window.AudioContext||window.webkitAudioContext)(); }catch(e){ return null; }
  }
  if(__audioCtx.state==='suspended') __audioCtx.resume();
  return __audioCtx;
}
function toggleSound(){
  __soundEnabled = !__soundEnabled;
  localStorage.setItem('dabil_sound_enabled', __soundEnabled ? '1' : '0');
  updateSoundIcon();
  if(__soundEnabled){ ensureAudioCtx(); playChime(true); }
}
/* Two-tone "new order" chime (or a single soft tone for the confirmation/test play) */
function playChime(soft){
  const ctx = ensureAudioCtx();
  if(!ctx) return;
  const now = ctx.currentTime;
  const notes = soft ? [[880, now, .12]] : [[880, now, .16],[1175, now+.18, .24]];
  notes.forEach(([freq,start,dur])=>{
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type='sine'; osc.frequency.value=freq;
    gain.gain.setValueAtTime(0.0001, start);
    gain.gain.exponentialRampToValueAtTime(0.35, start+0.02);
    gain.gain.exponentialRampToValueAtTime(0.0001, start+dur);
    osc.connect(gain); gain.connect(ctx.destination);
    osc.start(start); osc.stop(start+dur+0.02);
  });
}
function playOrderChime(){
  if(!__soundEnabled) return;
  playChime(false);
  const btn = document.getElementById('soundBtn');
  btn.classList.remove('ring'); void btn.offsetWidth; btn.classList.add('ring');
}
updateSoundIcon();
['click','touchstart','keydown'].forEach(ev=>document.addEventListener(ev, ()=>ensureAudioCtx(), {once:true, passive:true}));

/* ── Real-time order polling (every 20s) ── */
let lastOrderCount = <?php echo $__pending_orders; ?>;
let lastNotifCount = <?php echo $__unread_notifs; ?>;
let lastOrderId    = 0;

function updateOrderBadge(pendingCount) {
  // Update pending badge in the sidebar Orders nav link
  const badges = document.querySelectorAll('.nav-badge.red[data-type="orders"]');
  badges.forEach(b => {
    if (pendingCount > 0) { b.textContent = pendingCount; b.style.display=''; }
    else                  { b.style.display='none'; }
  });
}

setInterval(()=>{
  fetch('ajax/poll.php?rid='+RESTAURANT_ID)
    .then(r=>r.json())
    .then(d=>{
      // New pending order → chime + toast
      if(d.pending_orders > lastOrderCount || (d.last_order_id && d.last_order_id > lastOrderId && d.pending_orders > 0)){
        const diff = Math.max(1, d.pending_orders - lastOrderCount);
        let msg = 'Tap to view and manage orders';
        if (d.latest_pending) {
          const lp = d.latest_pending;
          msg = `${lp.customer_name||'Guest'} — ${lp.item_count} item${lp.item_count!==1?'s':''}`;
          if (lp.table_label)       msg += ` · ${lp.table_label}`;
          else if (lp.table_number) msg += ` · Table ${lp.table_number}`;
        }
        document.getElementById('alertTitle').textContent = `${diff} New Order${diff>1?'s':''}!`;
        document.getElementById('alertMsg').textContent   = msg;
        document.getElementById('orderAlert').classList.add('show');
        setTimeout(()=>document.getElementById('orderAlert').classList.remove('show'), 7000);
        playOrderChime();
      }
      lastOrderCount = d.pending_orders;
      if (d.last_order_id) lastOrderId = d.last_order_id;
      updateOrderBadge(d.pending_orders);

      // New notification dot
      if(d.unread_notifs > lastNotifCount){
        document.getElementById('notifDot').classList.add('show');
        lastNotifCount = d.unread_notifs;
      }
    }).catch(()=>{});
}, 20000);
</script>
