<?php
session_start();
$page_title = 'Live Orders';
$active_nav = 'orders';
$success = "";

// ── Handle status update (AJAX or form POST) — runs BEFORE any HTML output so
//    the AJAX response is clean JSON and the inline action buttons work. ───────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id'], $_POST['new_status'])) {
    require_once __DIR__ . '/config/db.php';
    $allowed_roles = ['restaurant_admin','staff','waiter'];
    if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', $allowed_roles)) {
        if (isset($_POST['ajax'])) { header('Content-Type: application/json'); http_response_code(403); echo json_encode(['ok'=>false]); exit; }
    } else {
        $uid = (int)$_SESSION['user_id'];
        $ctx = $conn->prepare("SELECT u.name AS uname, r.id AS rid, r.name AS rname FROM users u LEFT JOIN restaurants r ON u.restaurant_id=r.id WHERE u.id=? LIMIT 1");
        $ctx->bind_param("i", $uid); $ctx->execute();
        $ctxr = $ctx->get_result()->fetch_assoc();
        $__rid       = (int)($ctxr['rid'] ?? 0);
        $__name      = (string)($ctxr['uname'] ?? '');
        $__rest_name = (string)($ctxr['rname'] ?? '');

    $oid = (int)$_POST['order_id'];
    $ns  = $_POST['new_status'];
    $allowed = ['pending','accepted','preparing','ready','served','completed','cancelled'];

    if (in_array($ns, $allowed) && $__rid) {
        // Ensure the status column actually supports the panel's 'accepted'/'served'
        // words (older databases shipped without them, which silently broke updates).
        $coltype = '';
        if ($ct = @$conn->query("SELECT COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='orders' AND COLUMN_NAME='order_status'")) {
            $coltype = (string)($ct->fetch_row()[0] ?? '');
        }
        if ($coltype && strpos($coltype, "'accepted'") === false) {
            @$conn->query("ALTER TABLE `orders` MODIFY COLUMN `order_status` ENUM('pending','accepted','confirmed','preparing','ready','served','completed','cancelled') NOT NULL DEFAULT 'pending'");
        }
        // When accepting: also record who accepted (assigned_to)
        if ($ns === 'accepted') {
            $stmt = $conn->prepare(
                "UPDATE orders SET order_status=?, assigned_to=?, updated_at=NOW()
                 WHERE id=? AND restaurant_id=?"
            );
            $stmt->bind_param("siii", $ns, $uid, $oid, $__rid);
        } else {
            $stmt = $conn->prepare(
                "UPDATE orders SET order_status=?, updated_at=NOW()
                 WHERE id=? AND restaurant_id=?"
            );
            $stmt->bind_param("sii", $ns, $oid, $__rid);
        }
        $stmt->execute();

        // Notifications (restaurant-side — unchanged)
        if ($ns === 'ready') {
            $n = $conn->prepare(
                "INSERT INTO notifications(restaurant_id,type,title,message,related_id)
                 VALUES(?,'order_ready','Order Ready','Order #".str_pad($oid,4,'0',STR_PAD_LEFT)." is ready for pickup',?)"
            );
            $n->bind_param("ii", $__rid, $oid); $n->execute();
        }
        if ($ns === 'accepted') {
            $n = $conn->prepare(
                "INSERT INTO notifications(restaurant_id,type,title,message,related_id)
                 VALUES(?,'new_order','Order Accepted','Order #".str_pad($oid,4,'0',STR_PAD_LEFT)." accepted by ".htmlspecialchars($__name)."',?)"
            );
            $n->bind_param("ii", $__rid, $oid); $n->execute();
        }

        // Notify the customer in-app (bell icon / notifications.php) about
        // this status change — previously nothing told the customer except
        // the order page's own 8s poll, which only works while that exact
        // page is open. This persists, so it's still there when they check
        // the bell later, even if they'd left the order screen entirely.
        $cust_lookup = $conn->prepare("SELECT user_id FROM orders WHERE id=? AND restaurant_id=?");
        $cust_lookup->bind_param("ii", $oid, $__rid);
        $cust_lookup->execute();
        $cust_row = $cust_lookup->get_result()->fetch_assoc();
        $cust_uid = $cust_row ? (int)$cust_row['user_id'] : 0;

        // Respect the customer's own "Order Updates" toggle
        // (customer/notification_preferences.php) when that column exists —
        // defaults to notifying if the migration adding it hasn't run yet.
        $wants_notif = true;
        if ($cust_uid && ($pref_stmt = $conn->prepare("SELECT notify_order_updates FROM users WHERE id=?"))) {
            $pref_stmt->bind_param("i", $cust_uid);
            $pref_stmt->execute();
            $pref_row = $pref_stmt->get_result()->fetch_assoc();
            if ($pref_row && $pref_row['notify_order_updates'] !== null) {
                $wants_notif = (bool)$pref_row['notify_order_updates'];
            }
        }

        if ($cust_uid && $wants_notif) {
            $order_label = '#' . str_pad($oid, 4, '0', STR_PAD_LEFT);
            $rest_name   = htmlspecialchars($__rest_name);
            $cust_copy = [
                'accepted'  => ['Order accepted',     "$rest_name has accepted your order $order_label."],
                'preparing' => ['Order being prepared', "$rest_name is now preparing your order $order_label."],
                'ready'     => ['Order ready!',        "Your order $order_label at $rest_name is ready to be served."],
                'served'    => ['Order served',        "Your order $order_label has been served. Bon appétit!"],
                'completed' => ['Order completed',     "Your order $order_label at $rest_name is complete. Thanks for dining with us!"],
                'cancelled' => ['Order cancelled',     "Your order $order_label at $rest_name was cancelled."],
            ];
            if (isset($cust_copy[$ns])) {
                [$cn_title, $cn_msg] = $cust_copy[$ns];
                $cn = $conn->prepare(
                    "INSERT INTO customer_notifications (user_id, restaurant_id, type, title, message, is_read, created_at)
                     VALUES (?, ?, 'order_update', ?, ?, 0, NOW())"
                );
                $cn->bind_param("iiss", $cust_uid, $__rid, $cn_title, $cn_msg);
                $cn->execute();

                // Web push to the customer's devices (non-fatal).
                try {
                    $wp = __DIR__ . '/../customer/includes/webpush.php';
                    if (is_file($wp)) {
                        require_once $wp;
                        dabil_push_to_user($conn, $cust_uid, $cn_title, $cn_msg, 'orders.php');
                    }
                } catch (\Throwable $pe) { /* ignore push failures */ }
            }
        }

        // Fetch acceptor name for AJAX response
        $acceptor_name = null;
        if ($ns === 'accepted') {
            $an = $conn->prepare("SELECT name FROM users WHERE id=? LIMIT 1");
            $an->bind_param("i", $uid); $an->execute();
            $an_row = $an->get_result()->fetch_assoc();
            $acceptor_name = $an_row['name'] ?? null;
        }

        if (isset($_POST['ajax'])) {
            header('Content-Type: application/json');
            echo json_encode([
                'ok'           => true,
                'status'       => $ns,
                'accepted_by'  => $acceptor_name,
                'acceptor_uid' => $uid,
            ]);
            exit;
        }
        $success = "Order #".str_pad($oid,4,'0',STR_PAD_LEFT)." updated to ".ucfirst($ns).".";
    }
    }
}

include("includes/header.php");

$status_filter = $_GET['status'] ?? 'active';
$detail_id     = (int)($_GET['id'] ?? 0);

// Detail view
$detail_order = null; $detail_items = null;
if ($detail_id) {
    $ds = $conn->prepare(
        "SELECT o.*, u.name AS customer_name, u.email AS customer_email, u.phone AS customer_phone,
                u2.name AS accepted_by_name
         FROM orders o
         LEFT JOIN users u  ON o.user_id      = u.id
         LEFT JOIN users u2 ON o.assigned_to  = u2.id
         WHERE o.id=? AND o.restaurant_id=?"
    );
    $ds->bind_param("ii", $detail_id, $__rid); $ds->execute();
    $detail_order = $ds->get_result()->fetch_assoc();
    if ($detail_order) {
        $di = $conn->prepare("SELECT * FROM order_items WHERE order_id=?");
        $di->bind_param("i", $detail_id); $di->execute();
        $detail_items = $di->get_result();
    }
}

// Order list
$q = "SELECT o.*, u.name AS customer_name, u2.name AS accepted_by_name,
      (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) AS item_count,
      (SELECT GROUP_CONCAT(item_name ORDER BY id SEPARATOR ', ') FROM order_items WHERE order_id=o.id) AS item_names
      FROM orders o
      LEFT JOIN users u  ON o.user_id     = u.id
      LEFT JOIN users u2 ON o.assigned_to = u2.id
      WHERE o.restaurant_id=?";
$params = [$__rid]; $types = "i";
if ($status_filter === 'active') {
    $q .= " AND o.order_status NOT IN('completed','cancelled')";
} elseif ($status_filter !== 'all') {
    $q .= " AND o.order_status=?"; $params[] = $status_filter; $types .= "s";
}
$q .= " ORDER BY FIELD(o.order_status,'pending','accepted','preparing','ready','served','completed','cancelled'), o.created_at DESC";
$os = $conn->prepare($q); $os->bind_param($types, ...$params); $os->execute();
$orders = $os->get_result();

// Status → badge class
$sc_class = [
    'pending'   => 'badge-warning',
    'accepted'  => 'badge-primary',
    'preparing' => 'badge-purple',
    'ready'     => 'badge-success',
    'served'    => 'badge-info',
    'completed' => 'badge-success',
    'cancelled' => 'badge-error',
];

// Next status map (full new flow)
$next_map = [
    'pending'   => ['accepted',   'Accept Order'],
    'accepted'  => ['preparing',  'Start Preparing'],
    'preparing' => ['ready',      'Mark Ready'],
    'ready'     => ['served',     'Mark Served'],
    'served'    => ['completed',  'Complete'],
];
?>

<style>
.orders-layout{display:grid;grid-template-columns:<?php echo $detail_order?'1fr 360px':'1fr'; ?>;gap:20px;align-items:start}
@media(max-width:1024px){.orders-layout{grid-template-columns:1fr}.order-detail-panel{position:static!important;order:-1}}
.table-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
.table-scroll .data-table{min-width:640px}
.customer-tag{display:inline-flex;align-items:center;gap:5px;background:var(--primary-bg);border-radius:20px;padding:2px 8px 2px 4px;font-size:.7rem;font-weight:700;color:var(--primary)}
.accept-by-tag{display:inline-flex;align-items:center;gap:4px;background:var(--success-bg);border-radius:20px;padding:2px 8px 2px 4px;font-size:.7rem;font-weight:700;color:var(--success)}
@keyframes newOrderPulse{0%{box-shadow:0 0 0 0 rgba(245,158,11,.4)}70%{box-shadow:0 0 0 10px rgba(245,158,11,0)}100%{box-shadow:0 0 0 0 rgba(245,158,11,0)}}
.row-pending{animation:newOrderPulse 2s 3}
</style>

<?php if ($success): ?>
<div class="alert alert-success" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
  <?php echo $success; ?>
</div>
<?php endif; ?>

<!-- Page header -->
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:20px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Live Orders</h1>
    <p style="color:var(--text-muted);font-size:.85rem">
      Real-time order management — <?php echo htmlspecialchars($__rest_name); ?>
    </p>
  </div>
  <!-- Status filter tabs -->
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <?php foreach(['active'=>'Active','pending'=>'Pending','accepted'=>'Accepted','preparing'=>'Preparing','ready'=>'Ready','served'=>'Served','completed'=>'Completed','all'=>'All'] as $k=>$l): ?>
    <a href="orders.php?status=<?php echo $k; ?>"
       class="btn btn-sm <?php echo $status_filter===$k?'btn-primary':'btn-secondary'; ?>">
      <?php echo $l; ?>
    </a>
    <?php endforeach; ?>
  </div>
</div>

<div class="orders-layout">

  <!-- Orders Table -->
  <div class="card">
    <?php if ($orders->num_rows === 0): ?>
    <div style="padding:56px;text-align:center;color:var(--text-muted)">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block">
        <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"/>
      </svg>
      <p style="font-weight:700;margin-bottom:4px">No orders</p>
      <p style="font-size:.82rem">New orders will appear here automatically</p>
    </div>
    <?php else: ?>
    <div class="table-scroll">
    <table class="data-table">
      <thead>
        <tr>
          <th>Order</th>
          <th>Customer</th>
          <th>Table</th>
          <th>Items</th>
          <th>Amount</th>
          <th>Status</th>
          <th>Accepted By</th>
          <th>Time</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
      <?php while ($o = $orders->fetch_assoc()):
        $is_active_row = $detail_order && $detail_order['id'] == $o['id'];
        $row_class     = $o['order_status'] === 'pending' ? 'class="row-pending"' : '';
      ?>
        <tr <?php echo $row_class; ?> style="<?php echo $is_active_row?'background:var(--primary-bg)':''; ?>">
          <td>
            <a href="orders.php?id=<?php echo $o['id']; ?>&status=<?php echo $status_filter; ?>"
               style="font-weight:700;color:var(--primary)">#<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?></a>
          </td>
          <td>
            <div style="font-size:.83rem;font-weight:700"><?php echo htmlspecialchars($o['customer_name'] ?? 'Guest'); ?></div>
          </td>
          <td style="font-size:.82rem"><?php echo $o['table_number'] ? 'T-'.$o['table_number'] : '—'; ?></td>
          <td style="font-size:.78rem;max-width:160px">
            <div style="font-weight:600;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:160px" title="<?php echo htmlspecialchars($o['item_names']??''); ?>">
              <?php echo htmlspecialchars($o['item_names'] ?? '—'); ?>
            </div>
            <div style="color:var(--text-muted);font-size:.7rem"><?php echo $o['item_count']; ?> item<?php echo $o['item_count']!=1?'s':''; ?></div>
          </td>
          <td style="font-weight:700">₦<?php echo number_format($o['total_amount'],0); ?></td>
          <td>
            <span class="badge <?php echo $sc_class[$o['order_status']]??'badge-muted'; ?>"
                  id="badge-<?php echo $o['id']; ?>">
              <?php echo ucfirst($o['order_status']); ?>
            </span>
          </td>
          <td>
            <?php if ($o['accepted_by_name']): ?>
            <span class="accept-by-tag" id="acceptor-<?php echo $o['id']; ?>">
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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>
              <?php echo htmlspecialchars($o['accepted_by_name']); ?>
            </span>
            <?php else: ?>
            <span style="color:var(--text-light);font-size:.75rem" id="acceptor-<?php echo $o['id']; ?>">—</span>
            <?php endif; ?>
          </td>
          <td style="font-size:.75rem;color:var(--text-muted);white-space:nowrap">
            <?php echo date('g:i A',strtotime($o['created_at'])); ?>
          </td>
          <td>
            <?php if (!in_array($o['order_status'],['completed','cancelled'])): ?>
            <div style="display:flex;gap:5px;flex-wrap:wrap" id="btns-<?php echo $o['id']; ?>">
              <?php if (isset($next_map[$o['order_status']])):
                [$next_status, $next_label] = $next_map[$o['order_status']];
              ?>
              <button onclick="updateStatus(<?php echo $o['id']; ?>,'<?php echo $next_status; ?>',this)"
                      class="btn btn-success btn-sm" style="font-size:.72rem">
                <?php echo $next_label; ?>
              </button>
              <?php endif; ?>
            </div>
            <?php else: ?>
            <span style="font-size:.72rem;color:var(--text-light)" id="btns-<?php echo $o['id']; ?>">Closed</span>
            <?php endif; ?>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Order Detail Panel -->
  <?php if ($detail_order): ?>
  <div class="card order-detail-panel" style="position:sticky;top:90px">
    <div class="card-header">
      <div>
        <div style="font-size:.78rem;color:var(--text-muted);margin-bottom:2px">Order Detail</div>
        <h3>#<?php echo str_pad($detail_order['id'],4,'0',STR_PAD_LEFT); ?></h3>
      </div>
      <span class="badge <?php echo $sc_class[$detail_order['order_status']]??'badge-muted'; ?>">
        <?php echo ucfirst($detail_order['order_status']); ?>
      </span>
    </div>
    <div class="card-body" style="padding:16px 20px">

      <!-- Customer info -->
      <div style="background:var(--bg);border-radius:10px;padding:12px 14px;margin-bottom:14px">
        <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Customer</div>
        <div style="font-weight:700;font-size:.9rem;margin-bottom:2px"><?php echo htmlspecialchars($detail_order['customer_name'] ?? 'Guest'); ?></div>
        <?php if ($detail_order['customer_email']): ?>
        <div style="font-size:.75rem;color:var(--text-muted)"><?php echo htmlspecialchars($detail_order['customer_email']); ?></div>
        <?php endif; ?>
        <?php if ($detail_order['customer_phone']): ?>
        <div style="font-size:.75rem;color:var(--text-muted)"><?php echo htmlspecialchars($detail_order['customer_phone']); ?></div>
        <?php endif; ?>
        <?php if ($detail_order['table_number']): ?>
        <div style="font-size:.78rem;color:var(--primary);font-weight:700;margin-top:6px;display:flex;align-items:center;gap:4px">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <rect x="2" y="7" width="20" height="14" rx="2"/><path d="M6 7V4M18 7V4"/>
          </svg>
          Table <?php echo htmlspecialchars($detail_order['table_number']); ?>
        </div>
        <?php endif; ?>
      </div>

      <!-- Accepted By -->
      <?php if ($detail_order['accepted_by_name']): ?>
      <div style="background:var(--success-bg);border-radius:10px;padding:10px 14px;margin-bottom:14px;display:flex;align-items:center;gap:10px">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2.5" 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>
        <div>
          <div style="font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--success);margin-bottom:1px">Accepted By</div>
          <div style="font-size:.85rem;font-weight:700;color:var(--text)"><?php echo htmlspecialchars($detail_order['accepted_by_name']); ?></div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Items -->
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:8px">Items Ordered</div>
      <?php while ($item = $detail_items->fetch_assoc()): ?>
      <div style="display:flex;align-items:center;justify-content:space-between;padding:9px 0;border-bottom:1px solid var(--border)">
        <div>
          <div style="font-size:.84rem;font-weight:600"><?php echo htmlspecialchars($item['item_name']); ?></div>
          <div style="font-size:.72rem;color:var(--text-muted)">×<?php echo $item['quantity']; ?> @ ₦<?php echo number_format($item['price'],0); ?></div>
        </div>
        <div style="font-weight:700;color:var(--primary)">₦<?php echo number_format($item['price']*$item['quantity'],0); ?></div>
      </div>
      <?php endwhile; ?>

      <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 0;font-weight:800">
        <span>Total</span>
        <span style="color:var(--primary);font-size:1.05rem">₦<?php echo number_format($detail_order['total_amount'],0); ?></span>
      </div>

      <!-- Print Receipt -->
      <button onclick="printReceipt(<?php echo $detail_order['id']; ?>)"
              class="btn btn-secondary btn-md"
              style="width:100%;justify-content:center;margin-bottom:10px">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
          <polyline points="6 9 6 2 18 2 18 9"/>
          <path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/>
          <rect x="6" y="14" width="12" height="8"/>
        </svg>
        Print Receipt
      </button>

      <?php if ($detail_order['note']): ?>
      <div style="background:var(--warning-bg);border:1px solid #FDE68A;border-radius:8px;padding:10px 12px;margin-bottom:10px;font-size:.8rem;color:var(--warning)">
        <strong>Note:</strong> <?php echo htmlspecialchars($detail_order['note']); ?>
      </div>
      <?php endif; ?>

      <!-- Quick status update -->
      <?php if (!in_array($detail_order['order_status'],['completed','cancelled'])): ?>
      <div style="display:flex;flex-direction:column;gap:8px;margin-top:6px">
        <?php if (isset($next_map[$detail_order['order_status']])):
          [$nst, $nlabel] = $next_map[$detail_order['order_status']];
        ?>
        <form method="POST">
          <input type="hidden" name="order_id"   value="<?php echo $detail_order['id']; ?>">
          <input type="hidden" name="new_status" value="<?php echo $nst; ?>">
          <button class="btn btn-success btn-block btn-md"><?php echo $nlabel; ?></button>
        </form>
        <?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
  <?php endif; ?>

</div>

<script>
// Status badge class map — all statuses
const classMap = {
  pending:   'badge-warning',
  accepted:  'badge-primary',
  preparing: 'badge-purple',
  ready:     'badge-success',
  served:    'badge-info',
  completed: 'badge-success',
  cancelled: 'badge-error',
};

// Status display labels
const NEXT_LABELS = {
  pending:   'Accept Order',
  accepted:  'Start Preparing',
  preparing: 'Mark Ready',
  ready:     'Mark Served',
  served:    'Complete',
};
const NEXT_STATUS = {
  pending:   'accepted',
  accepted:  'preparing',
  preparing: 'ready',
  ready:     'served',
  served:    'completed',
};

function updateStatus(orderId, newStatus, btn) {
  btn.disabled = true;
  const origText = btn.textContent;
  btn.textContent = '…';

  const fd = new FormData();
  fd.append('order_id',  orderId);
  fd.append('new_status', newStatus);
  fd.append('ajax', '1');

  fetch('orders.php', {method:'POST', body:fd})
    .then(r => r.json())
    .then(d => {
      if (!d.ok) { btn.disabled=false; btn.textContent=origText; return; }

      const status = d.status;

      // Update badge
      const badge = document.getElementById('badge-' + orderId);
      if (badge) {
        badge.className = 'badge ' + (classMap[status] || 'badge-muted');
        badge.textContent = status.charAt(0).toUpperCase() + status.slice(1);
      }

      // Update accepted_by cell
      if (status === 'accepted' && d.accepted_by) {
        const cell = document.getElementById('acceptor-' + orderId);
        if (cell) {
          cell.className   = 'accept-by-tag';
          cell.innerHTML   = `<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" 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> ${d.accepted_by}`;
        }
      }

      // Update action buttons
      const btnContainer = document.getElementById('btns-' + orderId);
      if (btnContainer) {
        if (status === 'completed' || status === 'cancelled') {
          btnContainer.innerHTML = '<span style="font-size:.72rem;color:var(--text-light)">Closed</span>';
        } else {
          const nextSt = NEXT_STATUS[status];
          const nextLb = NEXT_LABELS[status];
          let html = '';
          if (nextSt && nextLb) {
            html += `<button onclick="updateStatus(${orderId},'${nextSt}',this)" class="btn btn-success btn-sm" style="font-size:.72rem">${nextLb}</button>`;
          }
          btnContainer.innerHTML = html;
        }
      }

      // Play a soft chime for the restaurant staff too
      playChime(false);
    })
    .catch(() => { btn.disabled=false; btn.textContent=origText; });
}

function printReceipt(orderId) {
  const url = window.location.pathname.replace(/\/[^/]+$/, '/') + 'ajax/receipt.php'
            + '?order_id=' + orderId + '&rid=<?php echo $__rid; ?>';
  fetch(url)
    .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
    .then(data => {
      if (!data.ok) { alert('Receipt error: ' + (data.msg || 'Unknown error')); return; }
      const o = data.order, items = data.items, rest = data.restaurant;
      const itemRows = items.map(i =>
        `<tr><td style="padding:5px 0;font-size:13px">${i.item_name}</td><td style="text-align:center">${i.quantity}</td><td style="text-align:right">&#8358;${Number(i.price*i.quantity).toLocaleString('en-NG',{minimumFractionDigits:0})}</td></tr>`
      ).join('');
      const html = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Receipt #${String(o.id).padStart(4,'0')}</title>
        <style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:'Courier New',monospace;width:300px;margin:0 auto;padding:16px;font-size:13px}
        .c{text-align:center}.d{border:none;border-top:1px dashed #000;margin:10px 0}.b{font-weight:bold}
        table{width:100%;border-collapse:collapse}.tr td{font-weight:bold;font-size:14px;padding:6px 0;border-top:1px dashed #000}
        @media print{@page{margin:6mm}body{width:100%}}</style></head><body>
        <div class="c b" style="font-size:16px">${rest.name}</div>
        ${rest.address?`<div class="c" style="font-size:11px">${rest.address}</div>`:''}
        ${rest.phone?`<div class="c" style="font-size:11px">${rest.phone}</div>`:''}
        <hr class="d"><div class="c b" style="font-size:14px">RECEIPT</div><hr class="d">
        <table><tr><td>Order #</td><td style="text-align:right;font-weight:bold">#${String(o.id).padStart(4,'0')}</td></tr>
        <tr><td>Date</td><td style="text-align:right">${o.created_at}</td></tr>
        <tr><td>Customer</td><td style="text-align:right">${o.customer_name||'Guest'}</td></tr>
        ${o.table_number?`<tr><td>Table</td><td style="text-align:right">${o.table_number}</td></tr>`:''}
        ${o.accepted_by?`<tr><td>Served by</td><td style="text-align:right">${o.accepted_by}</td></tr>`:''}
        </table><hr class="d">
        <table><thead><tr><th style="text-align:left;border-bottom:1px dashed #000">Item</th><th style="text-align:center;border-bottom:1px dashed #000">Qty</th><th style="text-align:right;border-bottom:1px dashed #000">Total</th></tr></thead>
        <tbody>${itemRows}</tbody>
        <tfoot><tr class="tr"><td colspan="2">TOTAL</td><td style="text-align:right">&#8358;${Number(o.total_amount).toLocaleString('en-NG',{minimumFractionDigits:2})}</td></tr></tfoot></table>
        ${o.note?`<hr class="d"><div style="font-size:11px"><strong>Note:</strong> ${o.note}</div>`:''}
        <div class="c" style="margin-top:12px;font-size:11px"><hr class="d">Powered by Dabil<br>Thank you for your order!</div>
        <script>window.onload=function(){window.print()}<\/script></body></html>`;
      const win = window.open('','_blank','width=400,height=650,scrollbars=yes');
      if (!win) { alert('Pop-up blocked! Allow pop-ups and try again.'); return; }
      win.document.write(html); win.document.close();
    })
    .catch(err => alert('Receipt error: ' + err.message));
}
</script>

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