<?php
// ── Catch ALL errors — blank page is now impossible ──────────────────────────
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);

set_exception_handler(function($e) {
    ob_end_clean();
    http_response_code(500);
    echo '<div style="font-family:monospace;background:#fee;border:2px solid red;padding:20px;margin:20px;border-radius:8px">';
    echo '<strong>Checkout Error:</strong> ' . htmlspecialchars($e->getMessage());
    echo '<br><small>' . htmlspecialchars($e->getFile() . ':' . $e->getLine()) . '</small>';
    echo '</div>';
    exit;
});

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    if ($errno === E_ERROR || $errno === E_PARSE) {
        ob_end_clean();
        echo '<div style="font-family:monospace;background:#fee;border:2px solid red;padding:20px;margin:20px;border-radius:8px">';
        echo '<strong>PHP Error:</strong> ' . htmlspecialchars($errstr);
        echo '<br><small>' . htmlspecialchars("$errfile:$errline") . '</small>';
        echo '</div>';
        exit;
    }
    return false;
});

// ── Session ───────────────────────────────────────────────────────────────────
if (session_status() === PHP_SESSION_NONE) session_start();

// ── DB connection ─────────────────────────────────────────────────────────────
// Try both possible paths for the customer panel
if (!isset($conn)) {
    $db_paths = [
        __DIR__ . '/config/db.php',
        __DIR__ . '/../config/db.php',
        dirname(__DIR__) . '/config/db.php',
    ];
    foreach ($db_paths as $db_path) {
        if (file_exists($db_path)) { include_once($db_path); break; }
    }
}

if (!isset($conn) || !$conn) {
    ob_end_clean();
    die('<div style="font-family:monospace;background:#fee;border:2px solid red;padding:20px;margin:20px;border-radius:8px"><strong>Database connection failed.</strong> Check config/db.php path.</div>');
}

// ── Auth guard ────────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    header("Location: signin.php?redirect=" . urlencode($_SERVER['REQUEST_URI']));
    exit;
}
$uid = (int)$_SESSION['user_id'];

// ── Lightweight self-migrations (no-ops once applied) ────────────────────────
$__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");
$__c = @$conn->query("SHOW COLUMNS FROM menu_items LIKE 'stock_qty'");
if ($__c && $__c->num_rows === 0) @$conn->query("ALTER TABLE menu_items ADD COLUMN stock_qty INT NULL DEFAULT NULL AFTER is_available");

// ── Restaurant ID (from GET on load, from POST hidden field on submit) ────────
$rid = (int)($_GET['rid'] ?? $_POST['rid'] ?? 0);

// Table number, when the customer arrived via a table-specific QR
// (restaurantadmin/tables.php encodes &table= alongside &rid=) — prefills
// the form field below so they don't have to retype something we already know.
// &tt=loc marks a Location/Office QR (organizations) instead of a dine-in table.
$table_num_prefill = trim((string)($_GET['table'] ?? $_POST['table_number'] ?? ''));
$table_type        = ((($_GET['tt'] ?? $_POST['table_type'] ?? '')) === 'loc') ? 'loc' : '';
$table_qs_checkout = $table_num_prefill !== '' ? '&table=' . urlencode($table_num_prefill) . ($table_type === 'loc' ? '&tt=loc' : '') : '';

// ── Init variables ────────────────────────────────────────────────────────────
$error          = "";
$success        = 0;
$total          = 0.0;
$commission_amt = 0.0;
$restaurant_amt = 0.0;

// ── Fetch restaurant ──────────────────────────────────────────────────────────
$restaurant = null;
if ($rid) {
    $rs = $conn->prepare("SELECT * FROM restaurants WHERE id=? AND status=1");
    $rs->bind_param("i", $rid);
    $rs->execute();
    $restaurant = $rs->get_result()->fetch_assoc();
}

// ── Fetch spendable balance (personal wallet + organisation meal ticket) ──────
// Organisation staff are funded into a separate 'meal_ticket' wallet; both are
// spendable here. Meal-ticket funds are used first at checkout.
$cust_balance = 0.00; $mt_balance = 0.00;
if ($wbq = $conn->prepare("SELECT wallet_type, balance FROM wallets WHERE user_id=? AND wallet_type IN ('customer','meal_ticket')")) {
    $wbq->bind_param("i", $uid);
    $wbq->execute();
    $wbr = $wbq->get_result();
    while ($row = $wbr->fetch_assoc()) {
        if ($row['wallet_type'] === 'meal_ticket') $mt_balance = (float)$row['balance'];
        else                                       $cust_balance = (float)$row['balance'];
    }
}
$wallet_balance = $cust_balance + $mt_balance;

// ── Super admin & commission ──────────────────────────────────────────────────
$sa_res         = $conn->query("SELECT id FROM users WHERE role='super_admin' LIMIT 1");
$sa_row         = $sa_res ? $sa_res->fetch_assoc() : null;
$super_admin_id = $sa_row ? (int)$sa_row['id'] : 0;

$cr_res          = $conn->query("SELECT setting_value FROM platform_settings WHERE setting_key='commission_rate' LIMIT 1");
$cr_row          = $cr_res ? $cr_res->fetch_row() : null;
$commission_rate = $cr_row ? (float)$cr_row[0] : 5.00;

// ── Handle POST ───────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $restaurant) {

    $items_json = $_POST['items'] ?? '';
    $table_num  = trim($_POST['table_number'] ?? '');
    $note       = trim($_POST['note'] ?? '');
    $items      = json_decode($items_json, true);

    // Human-readable origin of the order — "Table 5" for dine-in QRs, or the
    // location/office name as-is for organization QRs ("ICT Office"). Stored on
    // the order so the kitchen/waiter always knows exactly where it came from.
    $table_label = $table_num !== '' ? ($table_type === 'loc' ? $table_num : 'Table ' . $table_num) : '';

    if (empty($items) || !is_array($items)) {
        $error = "Your cart is empty. Please go back and add items.";
    } else {
        // Build validated order items (also enforce tracked inventory limits)
        $order_items = [];
        foreach ($items as $item_id => $item_data) {
            $item_id = (int)$item_id;
            $ms = $conn->prepare("SELECT id, name, price, stock_qty FROM menu_items WHERE id=? AND restaurant_id=? AND is_available=1");
            $ms->bind_param("ii", $item_id, $rid);
            $ms->execute();
            $mi = $ms->get_result()->fetch_assoc();
            if (!$mi) continue;
            $qty   = max(1, (int)($item_data['qty'] ?? 1));
            if ($mi['stock_qty'] !== null && $qty > (int)$mi['stock_qty']) {
                $left  = (int)$mi['stock_qty'];
                $error = $left <= 0
                    ? "'{$mi['name']}' is sold out. Please remove it from your cart."
                    : "Only {$left} of '{$mi['name']}' left. Please reduce the quantity.";
                break;
            }
            $price = (float)$mi['price'];
            $total += $price * $qty;
            $order_items[] = [
                'id'    => (int)$mi['id'],
                'name'  => (string)$mi['name'],
                'qty'   => $qty,
                'price' => $price,
            ];
        }

        if ($error) {
            // fall through — error already set (e.g. insufficient stock)
        } elseif (empty($order_items)) {
            $error = "No valid items found. Some items may no longer be available.";

        } elseif ($wallet_balance < $total) {
            $shortfall = $total - $wallet_balance;
            $error = "INSUFFICIENT_BALANCE:"
                . number_format($total, 2) . ":"
                . number_format($wallet_balance, 2) . ":"
                . number_format($shortfall, 2);

        } else {
            // Get the restaurant wallet's user_id (the admin user after migration)
            $rw = $conn->prepare("SELECT user_id FROM wallets WHERE restaurant_id=? AND wallet_type='restaurant' LIMIT 1");
            $rw->bind_param("i", $rid);
            $rw->execute();
            $rw_row              = $rw->get_result()->fetch_assoc();
            $rest_wallet_user_id = $rw_row ? (int)$rw_row['user_id'] : 0;

            // Fallback: restaurant's created_by
            if (!$rest_wallet_user_id) {
                $cb = $conn->prepare("SELECT created_by FROM restaurants WHERE id=? LIMIT 1");
                $cb->bind_param("i", $rid);
                $cb->execute();
                $cb_row              = $cb->get_result()->fetch_assoc();
                $rest_wallet_user_id = $cb_row ? (int)$cb_row['created_by'] : 0;
            }

            if (!$rest_wallet_user_id) {
                $error = "Order failed: restaurant wallet not found. Please contact support.";
            } else {
                // Unique references (wallet_transactions has UNIQUE KEY on reference)
                $ts       = time() . rand(100, 999);
                $ref_cust = "ORD_{$ts}";
                $ref_rest = "REST_ORD_{$ts}";
                $ref_comm = "COMM_ORD_{$ts}";

                $conn->begin_transaction();
                $ok      = true;
                $err_msg = "";

                // 1. Insert order
                $os = $conn->prepare(
                    "INSERT INTO orders
                        (user_id, restaurant_id, table_number, table_label, note, total_amount,
                         payment_method, payment_status, order_status, payment_reference)
                     VALUES (?, ?, ?, ?, ?, ?, 'wallet', 'paid', 'pending', ?)"
                );
                $os->bind_param("iisssds", $uid, $rid, $table_num, $table_label, $note, $total, $ref_cust);
                if (!$os->execute()) {
                    $ok      = false;
                    $err_msg = "Could not create order: " . $conn->error;
                }
                $order_id = (int)$conn->insert_id;

                // 2. Order items
                if ($ok) {
                    foreach ($order_items as $oi) {
                        $ois = $conn->prepare(
                            "INSERT INTO order_items (order_id, menu_item_id, item_name, quantity, price)
                             VALUES (?, ?, ?, ?, ?)"
                        );
                        $ois->bind_param("iisid", $order_id, $oi['id'], $oi['name'], $oi['qty'], $oi['price']);
                        if (!$ois->execute()) {
                            $ok      = false;
                            $err_msg = "Could not save order items: " . $conn->error;
                            break;
                        }
                    }
                }

                // 2b. Decrement tracked inventory (atomic — the WHERE guard makes the
                //     UPDATE fail if a simultaneous order grabbed the last portions),
                //     then auto-disable anything that just hit zero. Untracked items
                //     (stock_qty IS NULL — rice, beans, etc.) are unaffected.
                if ($ok) {
                    foreach ($order_items as $oi) {
                        $sd = $conn->prepare(
                            "UPDATE menu_items SET stock_qty = stock_qty - ?
                             WHERE id=? AND restaurant_id=? AND stock_qty IS NOT NULL AND stock_qty >= ?"
                        );
                        $sd->bind_param("iiii", $oi['qty'], $oi['id'], $rid, $oi['qty']);
                        $sd->execute();
                        if ($sd->affected_rows === 0) {
                            // Untracked item (fine) or someone else bought the last one (fail)
                            $chk = $conn->prepare("SELECT stock_qty FROM menu_items WHERE id=? AND restaurant_id=?");
                            $chk->bind_param("ii", $oi['id'], $rid);
                            $chk->execute();
                            $chk_row = $chk->get_result()->fetch_assoc();
                            if ($chk_row && $chk_row['stock_qty'] !== null) {
                                $ok      = false;
                                $left    = (int)$chk_row['stock_qty'];
                                $err_msg = "'{$oi['name']}' just sold out" . ($left > 0 ? " — only {$left} left" : "") . ". Please adjust your cart";
                                break;
                            }
                        }
                    }
                    if ($ok) {
                        $ad = $conn->prepare("UPDATE menu_items SET is_available=0 WHERE restaurant_id=? AND stock_qty IS NOT NULL AND stock_qty <= 0 AND is_available=1");
                        $ad->bind_param("i", $rid);
                        $ad->execute();
                    }
                }

                // 3 + 4. Deduct from the customer's spendable balance — organisation
                //        meal-ticket funds first, then their personal wallet — and
                //        record a debit transaction for each wallet actually used.
                //        (For a normal customer the meal-ticket balance is 0, so this
                //        behaves exactly like the previous single customer-wallet debit.)
                if ($ok) {
                    $cust_desc = "Payment for Order #" . str_pad($order_id, 4, '0', STR_PAD_LEFT)
                               . " at " . $restaurant['name'];

                    $deductions = [];
                    $remaining  = $total;
                    $take_mt    = min($remaining, $mt_balance);
                    if ($take_mt > 0)   { $deductions[] = ['meal_ticket', round($take_mt, 2)]; $remaining = round($remaining - $take_mt, 2); }
                    if ($remaining > 0) { $deductions[] = ['customer',    $remaining]; }

                    foreach ($deductions as [$wtype, $wamt]) {
                        $du = $conn->prepare(
                            "UPDATE wallets SET balance = balance - ?, updated_at = NOW()
                             WHERE user_id = ? AND wallet_type = ?"
                        );
                        $du->bind_param("dis", $wamt, $uid, $wtype);
                        if (!$du->execute() || $du->affected_rows < 1) {
                            $ok = false; $err_msg = "Could not debit {$wtype} wallet: " . $conn->error; break;
                        }
                        $dref = $ref_cust . ($wtype === 'meal_ticket' ? '_MT' : '');
                        $dt = $conn->prepare(
                            "INSERT INTO wallet_transactions
                                (user_id, wallet_type, order_id, amount, type, reference, description, status)
                             VALUES (?, ?, ?, ?, 'debit', ?, ?, 'success')"
                        );
                        $dt->bind_param("isidss", $uid, $wtype, $order_id, $wamt, $dref, $cust_desc);
                        if (!$dt->execute()) {
                            $ok = false; $err_msg = "Could not record {$wtype} transaction: " . $conn->error; break;
                        }
                    }
                }

                // 5. Commission split
                $commission_amt = round($total * $commission_rate / 100, 2);
                $restaurant_amt = round($total - $commission_amt, 2);

                // 6. Credit restaurant wallet ─────────────────────────────────
                // Simple UPDATE by restaurant_id — always reliable.
                // The new UNIQUE KEY is (user_id, wallet_type) so a fallback
                // INSERT won't get a duplicate error as long as user_id differs.
                if ($ok) {
                    $rc = $conn->prepare(
                        "UPDATE wallets SET balance = balance + ?, updated_at = NOW()
                         WHERE restaurant_id = ? AND wallet_type = 'restaurant'"
                    );
                    $rc->bind_param("di", $restaurant_amt, $rid);
                    $rc->execute();
                    if ($conn->affected_rows < 1) {
                        // Row missing — insert it
                        $rc2 = $conn->prepare(
                            "INSERT INTO wallets (user_id, wallet_type, restaurant_id, balance)
                             VALUES (?, 'restaurant', ?, ?)"
                        );
                        $rc2->bind_param("iid", $rest_wallet_user_id, $rid, $restaurant_amt);
                        if (!$rc2->execute()) {
                            $ok      = false;
                            $err_msg = "Could not credit restaurant wallet: " . $conn->error;
                        }
                    }
                }

                // 7. Restaurant credit transaction
                // NOTE: wallet_transactions has FK user_id → users.id
                // If rest_wallet_user_id is a restaurant ID (not a real user ID),
                // this INSERT will fail with FK violation.
                // We verify the user exists first; if not, skip this transaction
                // record (the wallet IS still credited — this is just the log row).
                if ($ok) {
                    $rest_desc = "Order #" . str_pad($order_id, 4, '0', STR_PAD_LEFT)
                               . " received (after {$commission_rate}% platform fee)";

                    // Check if rest_wallet_user_id is a real user
                    $ucheck = $conn->prepare("SELECT id FROM users WHERE id=? LIMIT 1");
                    $ucheck->bind_param("i", $rest_wallet_user_id);
                    $ucheck->execute();
                    $ucheck_row = $ucheck->get_result()->fetch_assoc();

                    if ($ucheck_row) {
                        // Valid user — insert normally
                        $rt = $conn->prepare(
                            "INSERT INTO wallet_transactions
                                (user_id, wallet_type, restaurant_id, order_id, amount, type, reference, description, status)
                             VALUES (?, 'restaurant', ?, ?, ?, 'credit', ?, ?, 'success')"
                        );
                        $rt->bind_param("iiidss", $rest_wallet_user_id, $rid, $order_id, $restaurant_amt, $ref_rest, $rest_desc);
                        if (!$rt->execute()) {
                            $ok      = false;
                            $err_msg = "Could not record restaurant transaction: " . $conn->error;
                        }
                    } else {
                        // rest_wallet_user_id is not a real user (pre-migration state).
                        // Use super_admin as the user_id placeholder so FK is satisfied,
                        // but keep wallet_type='restaurant' and restaurant_id so it
                        // shows correctly in the restaurant's transaction history.
                        $rt = $conn->prepare(
                            "INSERT INTO wallet_transactions
                                (user_id, wallet_type, restaurant_id, order_id, amount, type, reference, description, status)
                             VALUES (?, 'restaurant', ?, ?, ?, 'credit', ?, ?, 'success')"
                        );
                        // Use restaurant's created_by as user_id (always a real user)
                        $cb2 = $conn->prepare("SELECT created_by FROM restaurants WHERE id=? LIMIT 1");
                        $cb2->bind_param("i", $rid); $cb2->execute();
                        $cb2_row    = $cb2->get_result()->fetch_assoc();
                        $safe_uid   = $cb2_row ? (int)$cb2_row['created_by'] : $super_admin_id;
                        $rt->bind_param("iiidss", $safe_uid, $rid, $order_id, $restaurant_amt, $ref_rest, $rest_desc);
                        if (!$rt->execute()) {
                            // Non-fatal — wallet IS credited, just log it
                            error_log("Dabil: Could not record restaurant txn for order $order_id: " . $conn->error);
                        }
                    }
                }

                // 8. Super admin commission (non-fatal — don't block order)
                if ($ok && $super_admin_id && $commission_amt > 0) {
                    $sc = $conn->prepare(
                        "UPDATE wallets SET balance = balance + ?, updated_at = NOW()
                         WHERE user_id = ? AND wallet_type = 'super_admin'"
                    );
                    $sc->bind_param("di", $commission_amt, $super_admin_id);
                    $sc->execute(); // non-fatal

                    $sa_desc = "{$commission_rate}% commission — Order #"
                             . str_pad($order_id, 4, '0', STR_PAD_LEFT)
                             . " at " . $restaurant['name'];
                    $sat = $conn->prepare(
                        "INSERT INTO wallet_transactions
                            (user_id, wallet_type, order_id, amount, type, reference, description, status)
                         VALUES (?, 'super_admin', ?, ?, 'credit', ?, ?, 'success')"
                    );
                    $sat->bind_param("iidss", $super_admin_id, $order_id, $commission_amt, $ref_comm, $sa_desc);
                    $sat->execute(); // non-fatal
                }

                // 9. Notification (non-fatal)
                if ($ok) {
                    $n_title = "New Order #" . str_pad($order_id, 4, '0', STR_PAD_LEFT);
                    $n_msg   = "₦" . number_format($total, 0) . " order received"
                             . ($table_label ? " — $table_label" : "");
                    $notif = $conn->prepare(
                        "INSERT INTO notifications (restaurant_id, type, title, message, related_id)
                         VALUES (?, 'new_order', ?, ?, ?)"
                    );
                    $notif->bind_param("issi", $rid, $n_title, $n_msg, $order_id);
                    $notif->execute(); // non-fatal
                }

                if ($ok) {
                    $conn->commit();
                    $success = $order_id;
                } else {
                    $conn->rollback();
                    $error = "Order failed: " . $err_msg . " — Please try again.";
                }
            }
        }
    }
}

// ── Parse insufficient balance error ──────────────────────────────────────────
$is_balance_error = (strpos($error, 'INSUFFICIENT_BALANCE:') === 0);
$balance_data     = [];
if ($is_balance_error) {
    $parts        = explode(':', $error);
    $balance_data = [
        'total'     => $parts[1] ?? '0',
        'balance'   => $parts[2] ?? '0',
        'shortfall' => $parts[3] ?? '0',
    ];
    $error = '';
}

// ── Render ────────────────────────────────────────────────────────────────────
$page_title = 'Cart';
// Checkout is treated as part of the Orders tab, not a separate immersive
// flow — the bottom nav stays visible here (unlike scan.php's Pay/Menu
// screens), with "Orders" highlighted.
$active_nav = 'orders';

// Flush any buffered output before including header
ob_end_flush();

include("includes/header.php");
?>

<style>
/* Custom topbar only — unlike scan.php's Pay/Menu screens, the bottom tab
   bar stays visible here (Orders tab highlighted), so we don't touch
   .app-bottomnav or the bottom main-content padding it reserves. */
.app-topbar { display: none; }
.main-content { padding-top: env(safe-area-inset-top); }

.cart-topbar { display: flex; align-items: center; justify-content: space-between; padding: 14px 2px 18px; }
.cart-topbar-left { display: flex; align-items: center; gap: 12px; }
.cart-topbar .cart-back {
  width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
  color: var(--text); background: var(--bg); flex-shrink: 0; touch-action: manipulation;
}
.cart-topbar .cart-title { font-size: 1.05rem; font-weight: 800; letter-spacing: -.02em; }
.cart-topbar-right { display: flex; align-items: center; gap: 12px; }

.cart-section-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; margin: 4px 0 14px; }

.cart-item-card {
  display: flex; align-items: center; gap: 14px;
  background: #fff; border-radius: 16px; padding: 14px; margin-bottom: 12px;
  box-shadow: 0 2px 10px rgba(15,23,42,.05);
}
.cart-item-card .ci-thumb { width: 64px; height: 64px; border-radius: 12px; overflow: hidden; flex-shrink: 0; background: #0F172A; }
.cart-item-card .ci-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.cart-item-card .ci-thumb-fallback { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; background: var(--primary-bg); }
.cart-item-card .ci-info { flex: 1; min-width: 0; }
.cart-item-card .ci-name { font-weight: 700; font-size: .9rem; line-height: 1.3; margin-bottom: 8px; }
.cart-item-card .ci-stepper { display: flex; align-items: center; gap: 10px; }
.cart-item-card .ci-step-btn {
  position: relative;
  width: 36px; height: 36px; border-radius: 50%; border: 1.5px solid var(--border); background: #fff;
  color: var(--text); display: flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation;
}
/* Invisible tap-area expansion → ~44px hit target without enlarging the visual button. */
.cart-item-card .ci-step-btn::after { content: ""; position: absolute; inset: -4px; border-radius: 50%; }
.cart-item-card .ci-step-btn:active { background: var(--bg); }
.cart-item-card .ci-qty { font-weight: 700; font-size: .88rem; min-width: 16px; text-align: center; }
.cart-item-card .ci-right { display: flex; flex-direction: column; align-items: flex-end; gap: 12px; flex-shrink: 0; }
.cart-item-card .ci-price { font-weight: 800; color: var(--primary); font-size: .9rem; white-space: nowrap; }

.notes-card { background: #fff; border-radius: 16px; padding: 16px; margin-bottom: 22px; }
.notes-card .nc-label { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: .88rem; margin-bottom: 12px; }
.notes-card .nc-icon {
  width: 30px; height: 30px; border-radius: 50%; background: var(--primary-bg); color: var(--primary);
  display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.notes-card textarea {
  width: 100%; border: 1.5px solid var(--border); border-radius: 12px; background: var(--bg);
  padding: 12px 14px; font-size: .85rem; font-family: var(--font); color: var(--text); resize: vertical; outline: none;
}
.notes-card textarea:focus { border-color: var(--primary); background: #fff; }
.notes-card textarea::placeholder { color: var(--text-light); }

.wallet-banner {
  background: linear-gradient(135deg, #225AE3 0%, #1844b8 100%);
  border-radius: 18px; padding: 18px 20px; margin-bottom: 14px;
  display: flex; align-items: center; justify-content: space-between; gap: 14px;
  box-shadow: 0 8px 24px rgba(34,90,227,.25); text-decoration: none;
}
.wallet-banner .wb-label { font-size: .66rem; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: rgba(255,255,255,.75); margin-bottom: 6px; }
.wallet-banner .wb-amount { font-size: 1.3rem; font-weight: 800; color: #fff; letter-spacing: -.02em; }
.wallet-banner .wb-icon {
  width: 40px; height: 40px; border-radius: 50%; background: rgba(255,255,255,.18);
  display: flex; align-items: center; justify-content: center; color: #fff; flex-shrink: 0;
}

.totals-list { padding: 4px 2px 18px; }
.totals-list .tl-row { display: flex; align-items: center; justify-content: space-between; padding: 7px 0; font-size: .86rem; color: var(--text-muted); }
.totals-list .tl-row .free { color: var(--success); font-weight: 700; }
.totals-list .tl-final { display: flex; align-items: center; justify-content: space-between; padding: 12px 0 0; margin-top: 6px; border-top: 1px solid var(--border); }
.totals-list .tl-final span:first-child { font-weight: 800; font-size: .95rem; }
.totals-list .tl-final span:last-child { font-weight: 800; font-size: 1.3rem; color: var(--primary); }

.charge-note { display: flex; gap: 10px; background: var(--primary-bg); border-radius: 12px; padding: 13px 15px; margin-bottom: 20px; font-size: .78rem; color: var(--text-muted); line-height: 1.5; }
.charge-note svg { flex-shrink: 0; margin-top: 1px; color: var(--primary); }

.btn-place-order {
  width: 100%; display: flex; align-items: center; justify-content: center; gap: 8px;
  background: var(--primary); color: #fff; border: none; border-radius: 14px;
  padding: 16px; font-size: .95rem; font-weight: 700; cursor: pointer; font-family: var(--font);
  box-shadow: var(--shadow-lg); touch-action: manipulation;
}
.btn-place-order:active { background: var(--primary-dark); }
.btn-place-order:disabled { opacity: .5; cursor: not-allowed; }
.secure-caption { text-align: center; font-size: .72rem; color: var(--text-light); margin-top: 12px; }
</style>

<div style="max-width:600px;margin:0 auto">

  <!-- Topbar -->
  <div class="cart-topbar">
    <div class="cart-topbar-left">
      <a href="scan.php?rid=<?php echo $rid; ?><?php echo $table_qs_checkout; ?>" class="cart-back">
        <svg width="17" height="17" 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="cart-title">Cart</span>
    </div>
    <div class="cart-topbar-right">
      <a href="notifications.php" class="icon-btn" title="Notifications">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 10-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 01-3.46 0"/></svg>
        <?php if ($__unread > 0): ?><span class="notif-dot"></span><?php endif; ?>
      </a>
      <a href="profile.php" class="topbar-avatar" style="width:32px;height:32px;font-size:.65rem" title="<?php echo htmlspecialchars($__name); ?>"><?php echo $__avatar_url ? '<img src="' . htmlspecialchars($__avatar_url) . '" alt="">' : $__initials; ?></a>
    </div>
  </div>

  <?php if (!$restaurant): ?>
  <div class="alert alert-error">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
    Invalid restaurant. <a href="scan.php">Go back and scan again</a>
  </div>
  <?php include("includes/footer.php"); exit; endif; ?>

  <?php if ($error): ?>
  <div class="alert alert-error" style="margin-bottom:16px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" style="flex-shrink:0">
      <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/>
    </svg>
    <?php echo htmlspecialchars($error); ?>
  </div>
  <?php endif; ?>

  <?php if ($is_balance_error): ?>
  <div style="background:var(--error-bg);border:2px solid #FECACA;border-radius:16px;padding:22px 24px;margin-bottom:20px">
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
      <div style="width:44px;height:44px;background:var(--error);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.5" 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>
        <div style="font-size:1rem;font-weight:800;color:var(--error);margin-bottom:2px">Insufficient Wallet Balance</div>
        <div style="font-size:.82rem;color:var(--error);opacity:.85">Your wallet doesn't have enough funds</div>
      </div>
    </div>
    <div style="background:#fff;border-radius:10px;padding:14px 16px;margin-bottom:16px">
      <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--border)">
        <span style="font-size:.83rem;color:var(--text-muted)">Order Total</span>
        <span style="font-size:.9rem;font-weight:800">₦<?php echo $balance_data['total']; ?></span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--border)">
        <span style="font-size:.83rem;color:var(--text-muted)">Your Wallet Balance</span>
        <span style="font-size:.9rem;font-weight:700;color:var(--error)">₦<?php echo $balance_data['balance']; ?></span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:8px 0 0">
        <span style="font-size:.83rem;font-weight:700">Amount Needed</span>
        <span style="font-size:1rem;font-weight:800;color:var(--error)">₦<?php echo $balance_data['shortfall']; ?></span>
      </div>
    </div>
    <a href="fund_wallet.php"
       style="display:flex;align-items:center;justify-content:center;gap:8px;background:var(--error);color:#fff;padding:13px 20px;border-radius:12px;font-weight:700;font-size:.9rem;text-decoration:none">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
        <circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/>
      </svg>
      Top Up Wallet to Proceed
    </a>
    <p style="text-align:center;font-size:.75rem;color:var(--error);opacity:.75;margin-top:10px">Your cart is saved — come back after topping up</p>
  </div>
  <?php endif; ?>

  <?php if ($success): ?>
  <!-- ── SUCCESS ─────────────────────────────────────────────────────────── -->
  <div class="card" style="padding:40px 32px;text-align:center">
    <div style="width:68px;height:68px;background:var(--success-bg);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 18px;border:3px solid var(--success)">
      <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2.5" 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>
    </div>
    <h2 style="font-size:1.4rem;font-weight:800;margin-bottom:6px">Order Placed! 🎉</h2>
    <p style="color:var(--text-muted);font-size:.875rem;margin-bottom:6px">
      Order <strong>#<?php echo str_pad($success, 4, '0', STR_PAD_LEFT); ?></strong>
      sent to <strong><?php echo htmlspecialchars($restaurant['name']); ?></strong>
    </p>

    <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap;margin-top:24px">
      <a href="order_detail.php?id=<?php echo $success; ?>" class="btn btn-primary btn-md">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round">
          <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
        </svg>
        Track Order
      </a>
      <a href="scan.php?rid=<?php echo $rid; ?><?php echo $table_qs_checkout; ?>" class="btn btn-secondary btn-md">Order More</a>
    </div>
  </div>

  <?php else: ?>
  <!-- ── CART ───────────────────────────────────────────────────────────── -->
  <form method="POST" action="checkout.php?rid=<?php echo $rid; ?>" id="checkoutForm">
    <input type="hidden" name="items" id="itemsInput">
    <input type="hidden" name="rid"   value="<?php echo $rid; ?>">
    <input type="hidden" name="table_number" value="<?php echo htmlspecialchars($table_num_prefill); ?>">
    <input type="hidden" name="table_type" value="<?php echo $table_type === 'loc' ? 'loc' : ''; ?>">
    <input type="hidden" name="payment_method" value="wallet">

    <h2 class="cart-section-title">Order Summary</h2>
    <div id="cartItems">
      <div style="padding:48px 10px;text-align:center;color:var(--text-muted)">
        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg>
        <p style="font-size:.9rem;font-weight:700;margin-bottom:4px;color:var(--text)">There are no items in your cart</p>
        <p style="font-size:.82rem">
          <a href="scan.php?rid=<?php echo $rid; ?><?php echo $table_qs_checkout; ?>" style="color:var(--primary);font-weight:600">Browse the menu →</a>
        </p>
      </div>
    </div>

    <h2 class="cart-section-title" style="margin-top:24px">Special Instructions</h2>
    <div class="notes-card">
      <div class="nc-label">
        <span class="nc-icon">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 113 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
        </span>
        Notes for the Chef/Waiter
      </div>
      <textarea name="note" rows="2" placeholder="e.g. No onions, extra spicy, allergies…"></textarea>
    </div>

    <a href="fund_wallet.php" class="wallet-banner">
      <div>
        <div class="wb-label">Available Wallet Balance</div>
        <div class="wb-amount">₦<?php echo number_format($wallet_balance, 2); ?></div>
      </div>
      <span class="wb-icon">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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>
    </a>

    <div id="insufficientWarning" style="display:none;background:var(--error-bg);border:1.5px solid #FECACA;border-radius:10px;padding:13px 16px;margin-bottom:16px">
      <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--error)" stroke-width="2" stroke-linecap="round">
          <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
          <line x1="12" y1="9" x2="12" y2="13"/>
        </svg>
        <span style="font-size:.82rem;font-weight:700;color:var(--error)">Wallet balance is not enough</span>
      </div>
      <div style="font-size:.79rem;color:var(--error);margin-bottom:10px">
        You need <strong id="neededAmt"></strong> but your balance is
        <strong>₦<?php echo number_format($wallet_balance, 2); ?></strong>.
        Top up <strong id="shortfallAmt"></strong> to continue.
      </div>
      <a href="fund_wallet.php"
         style="display:inline-flex;align-items:center;gap:6px;background:var(--error);color:#fff;padding:8px 14px;border-radius:8px;font-weight:700;font-size:.78rem;text-decoration:none">
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
          <circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/>
        </svg>
        Top Up Wallet
      </a>
    </div>

    <div class="totals-list">
      <div class="tl-row"><span>Subtotal</span><span id="orderTotal">₦0</span></div>
      <div class="tl-row"><span>Delivery</span><span class="free">FREE</span></div>
      <div class="tl-final"><span>Total Amount</span><span id="orderTotalFinal">₦0</span></div>
    </div>

    <div class="charge-note">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
      <span>You will be charged instantly from your wallet upon confirmation. Please ensure your balance is sufficient.</span>
    </div>

    <button type="submit" class="btn-place-order" id="placeBtn">
      Place Order
      <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
    </button>
    <p class="secure-caption">Secure Transaction encrypted by Dabil Pay</p>
  </form>
  <?php endif; ?>

</div>

<?php if (!$success && $restaurant): ?>
<!-- ── Order confirmation modal (shown before any wallet charge) ─────────── -->
<style>
  .oc-overlay { position:fixed; inset:0; z-index:3000; display:none; align-items:center; justify-content:center;
    background:rgba(15,23,42,.55); -webkit-backdrop-filter:blur(3px); backdrop-filter:blur(3px); padding:16px; overflow-y:auto; }
  .oc-overlay.show { display:flex; animation:ocFade .2s ease both; }
  .oc-modal { width:100%; max-width:440px; margin:auto; background:#fff; border-radius:22px; padding:24px 22px 20px;
    box-shadow:0 24px 60px rgba(15,23,42,.32); animation:ocPop .26s cubic-bezier(.22,1,.36,1) both; }
  /* While the confirm modal is open, hide the bottom tab bar so it can never overlap the centered modal */
  body.dabil-modal-open .app-bottomnav { display:none !important; }
  .oc-icon { width:54px; height:54px; border-radius:16px; background:var(--primary-bg); color:var(--primary);
    display:flex; align-items:center; justify-content:center; margin-bottom:14px; }
  .oc-modal h3 { font-size:1.2rem; font-weight:800; letter-spacing:-.02em; margin-bottom:6px; }
  .oc-modal p  { font-size:.88rem; color:var(--text-muted); line-height:1.5; }
  .oc-amount-row { display:flex; align-items:center; justify-content:space-between; background:var(--bg);
    border:1px solid var(--border); border-radius:14px; padding:13px 15px; margin:16px 0 18px; }
  .oc-amount-row .lbl { font-size:.82rem; color:var(--text-muted); font-weight:600; }
  .oc-amount-row .val { font-size:1.18rem; font-weight:800; color:var(--primary); letter-spacing:-.02em; }
  .oc-actions { display:flex; gap:12px; }
  .oc-btn { flex:1; height:52px; border-radius:14px; font-family:var(--font); font-weight:700; font-size:.95rem;
    cursor:pointer; display:flex; align-items:center; justify-content:center; gap:8px; border:none; touch-action:manipulation; }
  .oc-btn.cancel  { background:#fff; color:var(--text); border:1.5px solid var(--border); }
  .oc-btn.cancel:active { background:var(--bg); }
  .oc-btn.confirm { background:var(--primary); color:#fff; box-shadow:0 8px 22px rgba(34,90,227,.3); }
  .oc-btn.confirm:active { background:var(--primary-dark); }
  @keyframes ocFade { from{opacity:0} to{opacity:1} }
  @keyframes ocPop { from{opacity:0; transform:scale(.94)} to{opacity:1; transform:none} }
  @media (prefers-reduced-motion: reduce){ .oc-overlay.show, .oc-modal { animation:none !important; } }
</style>
<div class="oc-overlay" id="orderConfirmOverlay" aria-hidden="true" onclick="if(event.target===this)closeOrderConfirm()">
  <div class="oc-modal" role="dialog" aria-modal="true" aria-labelledby="ocTitle">
    <div class="oc-icon">
      <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="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>
    <h3 id="ocTitle">Confirm your order</h3>
    <p>You're paying <strong><?php echo htmlspecialchars($restaurant['name']); ?></strong> straight from your Dabil wallet. Do you want to proceed?</p>
    <div class="oc-amount-row">
      <span class="lbl">Total to pay</span>
      <span class="val" id="ocAmount">₦0</span>
    </div>
    <div class="oc-actions">
      <button type="button" class="oc-btn cancel" onclick="closeOrderConfirm()">Cancel</button>
      <button type="button" class="oc-btn confirm" onclick="confirmOrder()">Confirm &amp; Pay</button>
    </div>
  </div>
</div>
<?php endif; ?>

<script>
const WALLET_BALANCE = <?php echo json_encode($wallet_balance); ?>;
const RID            = <?php echo json_encode($rid); ?>;

let cart = {};
try {
  const s = sessionStorage.getItem('dabil_cart');
  if (s) { const d = JSON.parse(s); if (d && d.rid == RID) cart = d.cart || {}; }
} catch(e) {}

function fmt(n) {
  return '₦' + Number(n).toLocaleString('en-NG', {minimumFractionDigits:0, maximumFractionDigits:2});
}
function getTotal() {
  return Object.values(cart).reduce((s,i) => s + (i.price * i.qty), 0);
}
function checkBalance() {
  const total = getTotal();
  const warn  = document.getElementById('insufficientWarning');
  const btn   = document.getElementById('placeBtn');
  if (!warn || !btn) return;
  if (total > 0 && total > WALLET_BALANCE) {
    document.getElementById('neededAmt').textContent    = fmt(total);
    document.getElementById('shortfallAmt').textContent = fmt(total - WALLET_BALANCE);
    warn.style.display = 'block';
    btn.disabled = true;
  } else {
    warn.style.display = 'none';
    const has = Object.values(cart).some(i => i.qty > 0);
    btn.disabled = !has;
  }
}
// The empty state is generated here every time rather than toggling a
// static element's visibility — renderCart() replaces #cartItems'
// innerHTML wholesale when there are items, which would otherwise destroy
// any static "empty" markup permanently after the first real render. That
// was the cause of an item card staying stuck on screen forever once the
// cart had been emptied back down to zero via the stepper.
function emptyCartHtml() {
  const browseHref = 'scan.php?rid=' + RID + (<?php echo json_encode($table_qs_checkout); ?> || '');
  return `<div style="padding:48px 10px;text-align:center;color:var(--text-muted)">
    <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg>
    <p style="font-size:.9rem;font-weight:700;margin-bottom:4px;color:var(--text)">There are no items in your cart</p>
    <p style="font-size:.82rem">
      <a href="${browseHref}" style="color:var(--primary);font-weight:600">Browse the menu →</a>
    </p>
  </div>`;
}
function renderCart() {
  const container = document.getElementById('cartItems');
  if (!container) return;
  const keys = Object.keys(cart).filter(k => cart[k] && cart[k].qty > 0);
  if (keys.length === 0) {
    container.innerHTML = emptyCartHtml();
    ['orderTotal','orderTotalFinal'].forEach(id => { const el=document.getElementById(id); if(el) el.textContent='₦0'; });
    const ii = document.getElementById('itemsInput'); if (ii) ii.value = '{}';
    checkBalance(); return;
  }
  const fallbackThumb = `<div class="ci-thumb-fallback"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="1.5" stroke-linecap="round" opacity=".5"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg></div>`;
  let total = 0, html = '';
  keys.forEach(k => {
    const i = cart[k], lt = i.price * i.qty; total += lt;
    const thumb = i.img ? `<img src="${i.img}" alt="">` : fallbackThumb;
    html += `<div class="cart-item-card">
      <div class="ci-thumb">${thumb}</div>
      <div class="ci-info">
        <div class="ci-name">${i.name}</div>
        <div class="ci-stepper">
          <button type="button" class="ci-step-btn" onclick="changeQty(${k},-1)" aria-label="Remove one">
            <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="ci-qty">${i.qty}</span>
          <button type="button" class="ci-step-btn" onclick="changeQty(${k},1)" aria-label="Add one">
            <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>
      </div>
      <div class="ci-right">
        <span class="ci-price">${fmt(i.price)}</span>
      </div>
    </div>`;
  });
  container.innerHTML = html;
  const ot = document.getElementById('orderTotal');       if(ot) ot.textContent = fmt(total);
  const of = document.getElementById('orderTotalFinal'); if(of) of.textContent = fmt(total);
  const ii = document.getElementById('itemsInput');       if(ii) ii.value = JSON.stringify(cart);
  checkBalance();
}
function changeQty(id, delta) {
  if (!cart[id]) return;
  cart[id].qty = Math.max(0, cart[id].qty + delta);
  if (cart[id].qty === 0) delete cart[id];
  sessionStorage.setItem('dabil_cart', JSON.stringify({cart, rid: RID}));
  renderCart();
}
document.addEventListener('DOMContentLoaded', renderCart);
renderCart();

const form = document.getElementById('checkoutForm');
let _orderConfirmed = false;
if (form) {
  form.addEventListener('submit', function(e) {
    const total = getTotal();
    if (total === 0)            { e.preventDefault(); alert('Your cart is empty.'); return; }
    if (total > WALLET_BALANCE) { e.preventDefault(); return; }
    // First click only previews the confirmation modal — no charge happens
    // until the user explicitly confirms.
    if (!_orderConfirmed) { e.preventDefault(); openOrderConfirm(total); return; }
    // Confirmed → finalize and let the real submit go through.
    const ii  = document.getElementById('itemsInput');
    if (ii) ii.value = JSON.stringify(cart);
    const btn = document.getElementById('placeBtn');
    if (btn) {
      btn.disabled  = true;
      btn.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="animation:spin .8s linear infinite"><circle cx="12" cy="12" r="10" stroke-dasharray="30 70"/></svg> Processing…';
    }
    sessionStorage.removeItem('dabil_cart');
  });
}

// ── Order confirmation modal ─────────────────────────────────────────────
function openOrderConfirm(total) {
  const amt = document.getElementById('ocAmount');
  if (amt) amt.textContent = fmt(total);
  const ov = document.getElementById('orderConfirmOverlay');
  if (ov) { ov.classList.add('show'); ov.setAttribute('aria-hidden', 'false'); document.body.classList.add('dabil-modal-open'); }
}
function closeOrderConfirm() {
  const ov = document.getElementById('orderConfirmOverlay');
  if (ov) { ov.classList.remove('show'); ov.setAttribute('aria-hidden', 'true'); document.body.classList.remove('dabil-modal-open'); }
}
function confirmOrder() {
  _orderConfirmed = true;
  closeOrderConfirm();
  if (form && form.requestSubmit) { form.requestSubmit(); return; }
  // Fallback for older browsers (requestSubmit unavailable): finalize manually.
  const ii = document.getElementById('itemsInput'); if (ii) ii.value = JSON.stringify(cart);
  const btn = document.getElementById('placeBtn');
  if (btn) { btn.disabled = true; btn.innerHTML = 'Processing…'; }
  sessionStorage.removeItem('dabil_cart');
  if (form) form.submit();
}
</script>
<style>@keyframes spin { to { transform: rotate(360deg); } }</style>

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