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

$order_id = (int)($_GET['id'] ?? 0);
if (!$order_id) { header("Location: orders.php"); exit; }

$stmt = $conn->prepare(
    "SELECT o.*, r.name AS restaurant_name, r.address AS restaurant_address, r.logo AS restaurant_logo
     FROM orders o
     LEFT JOIN restaurants r ON o.restaurant_id = r.id
     WHERE o.id = ? AND o.user_id = ?"
);
$stmt->bind_param("ii", $order_id, $uid);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();
if (!$order) { header("Location: orders.php"); exit; }

$items_stmt = $conn->prepare(
    "SELECT oi.*, mi.image AS item_image
     FROM order_items oi
     LEFT JOIN menu_items mi ON oi.menu_item_id = mi.id
     WHERE oi.order_id = ?"
);
$items_stmt->bind_param("i", $order_id);
$items_stmt->execute();
$order_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$subtotal = 0;
foreach ($order_items as $it) { $subtotal += (float)$it['price'] * (int)$it['quantity']; }
$total   = (float)$order['total_amount'];
$service = max(0, $total - $subtotal);
$item_count = array_sum(array_map(fn($i) => (int)$i['quantity'], $order_items));

// ── Reorder data ──────────────────────────────────────────────────────────────
// Pull the restaurant's CURRENT menu so the reorder sheet can (a) confirm which
// previously-ordered items are still available (and at what price) and (b) offer
// other dishes the customer can add to the same order.
$menu_img = function ($img) {
    if ($img && file_exists(__DIR__ . '/../restaurantadmin/uploads/menu/' . $img)) {
        return '../restaurantadmin/uploads/menu/' . $img;
    }
    return '';
};

$menu_by_id = [];
if (!empty($order['restaurant_id'])) {
    $mstmt = $conn->prepare("SELECT id, name, price, image, is_available FROM menu_items WHERE restaurant_id=? ORDER BY name ASC");
    $mstmt->bind_param("i", $order['restaurant_id']);
    $mstmt->execute();
    foreach ($mstmt->get_result()->fetch_all(MYSQLI_ASSOC) as $m) {
        $menu_by_id[(int)$m['id']] = $m;
    }
}

// Previously ordered items, mapped to the live menu where possible.
$reorder_prev = [];
$prev_ids = [];
foreach ($order_items as $it) {
    $mid       = (int)$it['menu_item_id'];
    $available = $mid && isset($menu_by_id[$mid]) && (int)$menu_by_id[$mid]['is_available'] === 1;
    $reorder_prev[] = [
        'id'        => $mid,
        'name'      => $it['item_name'],
        'price'     => $available ? (float)$menu_by_id[$mid]['price'] : (float)$it['price'],
        'qty'       => max(1, (int)$it['quantity']),
        'img'       => $available ? $menu_img($menu_by_id[$mid]['image']) : '',
        'available' => $available,
    ];
    if ($mid) $prev_ids[$mid] = true;
}

// Other available dishes the customer can add (not already in this order).
$reorder_more = [];
foreach ($menu_by_id as $mid => $m) {
    if ((int)$m['is_available'] !== 1 || isset($prev_ids[$mid])) continue;
    $reorder_more[] = [
        'id'    => $mid,
        'name'  => $m['name'],
        'price' => (float)$m['price'],
        'img'   => $menu_img($m['image']),
    ];
}

$can_reorder = !empty(array_filter($reorder_prev, fn($i) => $i['available'])) || !empty($reorder_more);

$order_label = '#' . str_pad($order_id, 4, '0', STR_PAD_LEFT);

$badge = [
    'pending'   => ['Pending',   'var(--warning)', 'var(--warning-bg)'],
    'confirmed' => ['Confirmed', 'var(--primary)', 'var(--primary-bg)'],
    'preparing' => ['Preparing', '#7C3AED',        '#F3E8FF'],
    'ready'     => ['Ready',     'var(--primary)', 'var(--primary-bg)'],
    'completed' => ['Completed', 'var(--success)', 'var(--success-bg)'],
    'cancelled' => ['Cancelled', 'var(--error)',   'var(--error-bg)'],
][$order['order_status']] ?? [ucfirst($order['order_status']), 'var(--text-muted)', 'var(--bg)'];

$pay_label = $order['payment_method'] === 'paystack' ? 'Card · Paystack' : 'Wallet';
$logo_path = $order['restaurant_logo'] ? '../restaurantadmin/uploads/logos/' . $order['restaurant_logo'] : null;
$has_logo  = $logo_path && file_exists(dirname(__FILE__) . '/' . $logo_path);
// Active = still trackable (matches the live tracker in orders.php).
// Completed, cancelled and refunded orders are not trackable.
$is_active = in_array($order['order_status'], ['pending', 'confirmed', 'preparing', 'ready'], true);
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.od-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-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.sub-topbar .icon-btn { color: var(--primary); }

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

.od-head-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.od-thumb { width: 52px; height: 52px; border-radius: 14px; overflow: hidden; flex-shrink: 0; background: linear-gradient(135deg, var(--primary-bg), #dce8fb); display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--primary); font-size: 1.1rem; }
.od-thumb img { width: 100%; height: 100%; object-fit: cover; }
.od-badge { font-size: .72rem; font-weight: 800; padding: 5px 12px; border-radius: 20px; flex-shrink: 0; }
.od-rname { font-size: 1.35rem; font-weight: 800; letter-spacing: -.02em; }
.od-rmeta { font-size: .82rem; color: var(--text-muted); margin-top: 3px; }

.od-loc { display: flex; gap: 12px; align-items: flex-start; }
.od-loc .l-ic { width: 34px; height: 34px; border-radius: 10px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.od-loc .l-label { font-size: .66rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin-bottom: 3px; }
.od-loc .l-val { font-size: .9rem; color: var(--text); line-height: 1.45; }

.od-sum-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px; }
.od-sum-head h3 { font-size: 1.02rem; font-weight: 800; }
.od-sum-head .cnt { font-size: .82rem; font-weight: 700; color: var(--primary); }
.od-item { display: flex; align-items: center; gap: 14px; padding: 14px 0; border-top: 1px solid var(--border); }
.od-item:first-of-type { border-top: none; }
.od-qty { width: 38px; height: 38px; border-radius: 11px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: .82rem; flex-shrink: 0; }
.od-item .it-name { font-weight: 700; font-size: .9rem; }
.od-item .it-sub { font-size: .76rem; color: var(--text-muted); margin-top: 2px; }
.od-item .it-price { font-weight: 800; font-size: .9rem; margin-left: auto; flex-shrink: 0; }

.od-tot-row { display: flex; justify-content: space-between; font-size: .86rem; color: var(--text-muted); padding: 6px 0; }
.od-tot-row.grand { border-top: 1px solid var(--border); margin-top: 8px; padding-top: 14px; }
.od-tot-row.grand .gl { font-size: 1rem; font-weight: 800; color: var(--text); }
.od-tot-row.grand .gv { font-size: 1.25rem; font-weight: 800; color: var(--primary); letter-spacing: -.02em; }

.od-pay { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); border-radius: 16px; padding: 18px; color: #fff; margin-bottom: 14px; box-shadow: 0 8px 22px rgba(34,90,227,.28); }
.od-pay .p-label { font-size: .66rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; opacity: .8; margin-bottom: 4px; }
.od-pay .p-val { font-size: 1.05rem; font-weight: 800; }

.od-actions { display: flex; flex-direction: column; gap: 10px; }
.od-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; }
.od-btn.primary { background: var(--primary); color: #fff; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.od-btn.primary:active { background: var(--primary-dark); }
.od-btn.ghost { background: #fff; color: var(--primary); border: 1.5px solid var(--border); }
</style>

<div class="od-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="orders.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">Order History</span>
    </div>
    <a href="help_center.php" class="icon-btn" title="Help">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 115.83 1c0 2-3 2-3 4"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </a>
  </div>

  <!-- Restaurant + status -->
  <div class="od-card">
    <div class="od-head-top">
      <div class="od-thumb">
        <?php if ($has_logo): ?><img src="<?php echo htmlspecialchars($logo_path); ?>" alt=""><?php else: echo htmlspecialchars(strtoupper(substr($order['restaurant_name'] ?? 'R',0,1))); endif; ?>
      </div>
      <span class="od-badge" style="color:<?php echo $badge[1]; ?>;background:<?php echo $badge[2]; ?>"><?php echo $badge[0]; ?></span>
    </div>
    <div class="od-rname"><?php echo htmlspecialchars($order['restaurant_name'] ?? 'Restaurant'); ?></div>
    <div class="od-rmeta"><?php echo date('M j, Y · g:i A', strtotime($order['created_at'])); ?> · Order <?php echo $order_label; ?></div>
  </div>

  <!-- Location / table -->
  <div class="od-card">
    <div class="od-loc">
      <span class="l-ic"><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg></span>
      <div>
        <div class="l-label"><?php echo $order['table_number'] ? 'Dine-in location' : 'Restaurant'; ?></div>
        <div class="l-val">
          <?php echo htmlspecialchars($order['restaurant_address'] ?: ($order['restaurant_name'] ?? 'In-restaurant order')); ?>
          <?php if ($order['table_number']): ?><br><strong>Table <?php echo htmlspecialchars($order['table_number']); ?></strong><?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Order summary -->
  <div class="od-card">
    <div class="od-sum-head">
      <h3>Order Summary</h3>
      <span class="cnt"><?php echo $item_count; ?> Item<?php echo $item_count === 1 ? '' : 's'; ?></span>
    </div>
    <?php if (empty($order_items)): ?>
      <p style="font-size:.84rem;color:var(--text-muted);padding-top:10px">No item breakdown is available for this order.</p>
    <?php else: foreach ($order_items as $it): ?>
      <div class="od-item">
        <span class="od-qty"><?php echo (int)$it['quantity']; ?>x</span>
        <div>
          <div class="it-name"><?php echo htmlspecialchars($it['item_name']); ?></div>
          <div class="it-sub">₦<?php echo number_format((float)$it['price'], 2); ?> each</div>
        </div>
        <span class="it-price">₦<?php echo number_format((float)$it['price'] * (int)$it['quantity'], 2); ?></span>
      </div>
    <?php endforeach; endif; ?>
  </div>

  <!-- Totals -->
  <div class="od-card">
    <div class="od-tot-row"><span>Subtotal</span><span>₦<?php echo number_format($subtotal, 2); ?></span></div>
    <?php if ($service > 0): ?><div class="od-tot-row"><span>Service &amp; charges</span><span>₦<?php echo number_format($service, 2); ?></span></div><?php endif; ?>
    <div class="od-tot-row grand"><span class="gl">Total</span><span class="gv">₦<?php echo number_format($total, 2); ?></span></div>
  </div>

  <!-- Payment method -->
  <div class="od-pay">
    <div class="p-label">Payment Method</div>
    <div class="p-val"><?php echo $pay_label; ?> · <?php echo ucfirst($order['payment_status']); ?></div>
  </div>

  <!-- Actions -->
  <div class="od-actions">
    <?php if ($is_active): ?>
      <!-- Primary: jump straight to the live tracker for THIS order -->
      <a href="orders.php?id=<?php echo $order_id; ?>" class="od-btn primary">
        <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="M5 12h14"/><path d="M12 5l7 7-7 7"/></svg>
        Track Your Order
      </a>
      <a href="order_detail.php?id=<?php echo $order_id; ?>" class="od-btn ghost" onclick="location.reload();return false;">
        <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="M23 4v6h-6"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
        Refresh Status
      </a>
    <?php endif; ?>
    <?php if ($can_reorder): ?>
    <button type="button" class="od-btn ghost" onclick="openReorder()">
      <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="M3 2l1.5 4.5M7 13h10l3-7H6"/><circle cx="9" cy="20" r="1.5"/><circle cx="17" cy="20" r="1.5"/></svg>
      Reorder Items
    </button>
    <?php else: ?>
    <a href="restaurants.php" class="od-btn ghost">
      <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="M3 2l1.5 4.5M7 13h10l3-7H6"/><circle cx="9" cy="20" r="1.5"/><circle cx="17" cy="20" r="1.5"/></svg>
      Browse Restaurants
    </a>
    <?php endif; ?>
  </div>
</div>

<?php if ($can_reorder): ?>
<style>
.ro-overlay { position: fixed; inset: 0; background: rgba(15,23,42,.5); z-index: 800; opacity: 0; pointer-events: none; transition: opacity .25s; backdrop-filter: blur(2px); }
.ro-overlay.open { opacity: 1; pointer-events: auto; }
.ro-sheet { position: fixed; left: 0; right: 0; bottom: 0; z-index: 801; background: var(--bg, #F4F7FC); border-radius: 24px 24px 0 0; max-width: 600px; margin: 0 auto; max-height: 90vh; display: flex; flex-direction: column; transform: translateY(100%); transition: transform .3s cubic-bezier(.22,1,.36,1); box-shadow: 0 -8px 30px rgba(15,23,42,.18); }
.ro-overlay.open .ro-sheet { transform: translateY(0); }
.ro-grip { width: 40px; height: 5px; border-radius: 3px; background: var(--border-dark, #cbd5e1); margin: 10px auto 4px; flex-shrink: 0; }
.ro-head { padding: 8px 20px 14px; flex-shrink: 0; }
.ro-head h2 { font-size: 1.2rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.ro-head p { font-size: .82rem; color: var(--text-muted); margin-top: 3px; }
.ro-close { position: absolute; top: 14px; right: 16px; width: 32px; height: 32px; border-radius: 50%; border: none; background: var(--border, #E7EDF6); color: var(--text-muted); display: flex; align-items: center; justify-content: center; cursor: pointer; }
.ro-body { overflow-y: auto; padding: 0 16px 8px; -webkit-overflow-scrolling: touch; }
.ro-group-label { font-size: .68rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin: 14px 4px 8px; }
.ro-row { display: flex; align-items: center; gap: 12px; background: #fff; border: 1.5px solid var(--border); border-radius: 14px; padding: 12px; margin-bottom: 8px; transition: border-color .15s, box-shadow .15s; }
.ro-row.sel { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(34,90,227,.08); }
.ro-row.dim { opacity: .55; }
.ro-thumb { width: 46px; height: 46px; border-radius: 11px; overflow: hidden; flex-shrink: 0; background: var(--primary-bg); display: flex; align-items: center; justify-content: center; color: var(--primary); }
.ro-thumb img { width: 100%; height: 100%; object-fit: cover; }
.ro-info { flex: 1; min-width: 0; }
.ro-name { font-weight: 700; font-size: .9rem; line-height: 1.25; }
.ro-price { font-size: .8rem; color: var(--text-muted); margin-top: 2px; }
.ro-unavail { font-size: .72rem; font-weight: 700; color: var(--error); margin-top: 2px; }
.ro-check { width: 26px; height: 26px; border-radius: 8px; border: 2px solid var(--border-dark, #cbd5e1); flex-shrink: 0; display: flex; align-items: center; justify-content: center; color: #fff; background: #fff; cursor: pointer; transition: all .15s; }
.ro-row.sel .ro-check { background: var(--primary); border-color: var(--primary); }
.ro-check svg { opacity: 0; transition: opacity .15s; }
.ro-row.sel .ro-check svg { opacity: 1; }
.ro-step { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.ro-step-btn { width: 30px; height: 30px; border-radius: 9px; border: 1.5px solid var(--border); background: #fff; color: var(--primary); display: flex; align-items: center; justify-content: center; cursor: pointer; }
.ro-step-btn:active { background: var(--bg); }
.ro-qty { font-weight: 800; font-size: .9rem; min-width: 18px; text-align: center; }
.ro-add-btn { border: 1.5px solid var(--primary); background: var(--primary-bg); color: var(--primary); font-weight: 700; font-size: .82rem; font-family: var(--font); padding: 8px 14px; border-radius: 10px; cursor: pointer; flex-shrink: 0; }
.ro-foot { flex-shrink: 0; padding: 14px 16px calc(env(safe-area-inset-bottom) + 16px); background: #fff; border-top: 1px solid var(--border); }
.ro-foot-row { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 12px; }
.ro-foot-row .fl { font-size: .85rem; color: var(--text-muted); font-weight: 600; }
.ro-foot-row .fv { font-size: 1.25rem; font-weight: 800; color: var(--primary); letter-spacing: -.02em; }
.ro-cta { width: 100%; height: 54px; border: none; border-radius: 14px; background: var(--primary); color: #fff; font-family: var(--font); font-weight: 700; font-size: .98rem; display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.ro-cta:active { background: var(--primary-dark); }
.ro-cta:disabled { background: var(--border-dark, #cbd5e1); box-shadow: none; cursor: not-allowed; }
.ro-empty { text-align: center; font-size: .82rem; color: var(--text-muted); padding: 14px 8px; }
</style>

<div class="ro-overlay" id="reorderOverlay" aria-hidden="true" onclick="if(event.target===this)closeReorder()">
  <div class="ro-sheet" role="dialog" aria-modal="true" aria-label="Reorder items">
    <div class="ro-grip"></div>
    <button type="button" class="ro-close" onclick="closeReorder()" aria-label="Close">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
    </button>
    <div class="ro-head">
      <h2>What would you like to reorder?</h2>
      <p>Pick the items you want again from <?php echo htmlspecialchars($order['restaurant_name'] ?? 'this restaurant'); ?>, or add something new.</p>
    </div>
    <div class="ro-body" id="reorderBody"></div>
    <div class="ro-foot">
      <div class="ro-foot-row">
        <span class="fl"><span id="roCount">0</span> item(s) selected</span>
        <span class="fv">₦<span id="roTotal">0.00</span></span>
      </div>
      <button type="button" class="ro-cta" id="roContinue" onclick="reorderContinue()" disabled>
        Continue to Checkout
        <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="M5 12h14"/><path d="M12 5l7 7-7 7"/></svg>
      </button>
    </div>
  </div>
</div>

<script>
(function () {
  const RID = <?php echo (int)$order['restaurant_id']; ?>;
  const PREV = <?php echo json_encode($reorder_prev, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
  const MORE = <?php echo json_encode($reorder_more, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;

  // selection model: { menuItemId: {name, price, qty, img} }
  const sel = {};
  PREV.forEach(it => { if (it.available && it.id) sel[it.id] = { name: it.name, price: it.price, qty: it.qty, img: it.img }; });

  const fmt = n => Number(n).toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
  const thumb = it => it.img ? `<img src="${esc(it.img)}" alt="">` : `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg>`;

  function row(it, isPrev) {
    const on = !!sel[it.id];
    const qty = on ? sel[it.id].qty : 0;
    if (isPrev && !it.available) {
      return `<div class="ro-row dim">
        <div class="ro-thumb">${thumb(it)}</div>
        <div class="ro-info"><div class="ro-name">${esc(it.name)}</div><div class="ro-unavail">No longer on the menu</div></div>
      </div>`;
    }
    const control = on
      ? `<div class="ro-step">
           <button type="button" class="ro-step-btn" onclick="roQty(${it.id},-1)" aria-label="Less"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="5" y1="12" x2="19" y2="12"/></svg></button>
           <span class="ro-qty" id="roq-${it.id}">${qty}</span>
           <button type="button" class="ro-step-btn" onclick="roQty(${it.id},1)" aria-label="More"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></button>
         </div>`
      : `<button type="button" class="ro-add-btn" onclick="roAdd(${it.id})">Add</button>`;
    return `<div class="ro-row ${on ? 'sel' : ''}" id="ror-${it.id}">
      <div class="ro-check" onclick="roToggle(${it.id})"><svg width="14" height="14" 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></div>
      <div class="ro-thumb">${thumb(it)}</div>
      <div class="ro-info"><div class="ro-name">${esc(it.name)}</div><div class="ro-price">₦${fmt(it.price)} each</div></div>
      ${control}
    </div>`;
  }

  // keep a lookup of every selectable item
  const ALL = {};
  PREV.forEach(it => { if (it.available && it.id) ALL[it.id] = it; });
  MORE.forEach(it => { ALL[it.id] = it; });

  function render() {
    let html = '';
    const prevSel = PREV.filter(it => it.available);
    if (PREV.length) {
      html += `<div class="ro-group-label">From your last order</div>`;
      html += PREV.map(it => row(it, true)).join('');
    }
    if (MORE.length) {
      html += `<div class="ro-group-label">Add from the menu</div>`;
      html += MORE.map(it => row(it, false)).join('');
    }
    if (!prevSel.length && !MORE.length) {
      html += `<p class="ro-empty">These items aren't on the menu right now.</p>`;
    }
    document.getElementById('reorderBody').innerHTML = html;
    updateFoot();
  }

  function updateFoot() {
    let count = 0, total = 0;
    Object.values(sel).forEach(i => { count += i.qty; total += i.price * i.qty; });
    document.getElementById('roCount').textContent = count;
    document.getElementById('roTotal').textContent = fmt(total);
    document.getElementById('roContinue').disabled = count === 0;
  }

  window.roToggle = function (id) {
    if (sel[id]) { delete sel[id]; } else { const it = ALL[id]; sel[id] = { name: it.name, price: it.price, qty: 1, img: it.img }; }
    render();
  };
  window.roAdd = function (id) { const it = ALL[id]; sel[id] = { name: it.name, price: it.price, qty: 1, img: it.img }; render(); };
  window.roQty = function (id, d) {
    if (!sel[id]) return;
    sel[id].qty += d;
    if (sel[id].qty <= 0) { delete sel[id]; render(); return; }
    const q = document.getElementById('roq-' + id); if (q) q.textContent = sel[id].qty;
    updateFoot();
  };

  window.openReorder = function () { render(); const o = document.getElementById('reorderOverlay'); if (o.parentNode !== document.body) document.body.appendChild(o); o.classList.add('open'); o.setAttribute('aria-hidden', 'false'); document.body.style.overflow = 'hidden'; };
  window.closeReorder = function () { const o = document.getElementById('reorderOverlay'); o.classList.remove('open'); o.setAttribute('aria-hidden', 'true'); document.body.style.overflow = ''; };

  window.reorderContinue = function () {
    const cart = {};
    Object.keys(sel).forEach(id => { const i = sel[id]; cart[id] = { name: i.name, price: i.price, qty: i.qty, img: i.img || '' }; });
    if (!Object.keys(cart).length) return;
    sessionStorage.setItem('dabil_cart', JSON.stringify({ cart, rid: RID }));
    window.location.href = 'checkout.php?rid=' + RID;
  };
})();
</script>
<?php endif; ?>

<?php
// Thank-you modal after submitting restaurant / Dabil feedback (?fb=rest|dabil|both)
$__fb_rest_name = $order['restaurant_name'] ?? '';
include("includes/feedback_thanks.php");
?>

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