<?php
require 'config.php';

// Ambil nomor meja dari URL
$table = isset($_GET['meja']) ? (int)$_GET['meja'] : 0;
if ($table <= 0) {
    die("QR Code tidak valid. Silakan scan ulang QR di meja Anda.");
}

// Ambil produk aktif
$products = $pdo->query("SELECT id, name, price, category, img FROM products WHERE is_active = 1 ORDER BY category, name")->fetchAll(PDO::FETCH_ASSOC);

// Ambil payment settings
$pay_settings = [];
$pay_banks = [];
try {
    $rows = $pdo->query("SELECT key_name, value FROM payment_settings")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) $pay_settings[$r['key_name']] = $r['value'];
    $pay_banks = $pdo->query("SELECT * FROM payment_banks WHERE is_active = 1 ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

$tunai_enabled = ($pay_settings['tunai_enabled'] ?? '1') == '1';
$qris_enabled  = ($pay_settings['qris_enabled']  ?? '0') == '1';

// Rate dari DB (default: takeaway 5%, service 0%, ppn 0%)
$fee_takeaway_rate = (float)($pay_settings['takeaway_rate'] ?? 5);
$fee_service_rate  = (float)($pay_settings['service_rate']  ?? 0);
$fee_ppn_rate      = (float)($pay_settings['ppn_rate']      ?? 0);
$qris_image    = $pay_settings['qris_image'] ?? '';
$qris_name     = $pay_settings['qris_merchant_name'] ?? 'GoldenWok Resto';

$foods  = array_filter($products, fn($p) => $p['category'] === 'food');
$drinks = array_filter($products, fn($p) => $p['category'] === 'drink');
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Order - Meja <?= $table ?> | GoldenWok</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }

        :root {
            --primary: #1a1a2e;
            --primary-light: #2d2d4a;
            --accent: #c8a951;
            --accent-light: #e8d48b;
            --accent-bg: rgba(200,169,81,0.08);
            --bg: #f8f7f4;
            --bg-warm: #f3f1ec;
            --surface: #ffffff;
            --surface-hover: #fafaf8;
            --border: #e8e5df;
            --border-light: #f0eeea;
            --text: #1a1a2e;
            --text-secondary: #6b6b7b;
            --text-tertiary: #9a9aaa;
            --green: #16a34a;
            --green-bg: rgba(22,163,74,0.08);
            --red: #dc2626;
            --red-bg: rgba(220,38,38,0.06);
            --radius-sm: 10px;
            --radius: 14px;
            --radius-lg: 20px;
            --radius-xl: 24px;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.04), 0 1px 2px rgba(0,0,0,0.02);
            --shadow: 0 2px 8px rgba(0,0,0,0.06), 0 1px 3px rgba(0,0,0,0.04);
            --shadow-lg: 0 8px 30px rgba(0,0,0,0.08), 0 2px 8px rgba(0,0,0,0.04);
            --shadow-xl: 0 20px 60px rgba(0,0,0,0.12), 0 4px 16px rgba(0,0,0,0.06);
        }

        html, body {
            background: var(--bg);
            color: var(--text);
            font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
            min-height: 100vh;
            overscroll-behavior: none;
            -webkit-font-smoothing: antialiased;
        }

        /* ── HEADER ── */
        .top-header {
            background: var(--surface);
            border-bottom: 1px solid var(--border);
            padding: 14px 20px;
            position: sticky;
            top: 0;
            z-index: 100;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .header-brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .header-logo {
            width: 36px;
            height: 36px;
            background: var(--primary);
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--accent);
            font-size: 1rem;
        }
        .header-brand h1 {
            font-size: 1.15rem;
            font-weight: 800;
            color: var(--text);
            letter-spacing: -0.02em;
        }
        .header-brand-sub {
            font-size: 0.68rem;
            color: var(--text-tertiary);
            font-weight: 500;
            letter-spacing: 0.04em;
            text-transform: uppercase;
            margin-top: -2px;
        }
        .table-badge {
            background: var(--accent-bg);
            color: var(--accent);
            font-weight: 700;
            font-size: 0.72rem;
            padding: 5px 14px;
            border-radius: 50px;
            letter-spacing: 0.04em;
            border: 1px solid rgba(200,169,81,0.15);
        }
        .cart-btn {
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 10px 18px;
            font-weight: 700;
            font-size: 0.8rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
            position: relative;
        }
        .cart-btn:hover { background: var(--primary-light); transform: translateY(-1px); box-shadow: var(--shadow); }
        .cart-btn:active { transform: translateY(0); }
        .cart-count {
            background: var(--accent);
            color: var(--primary);
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 0.65rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 800;
        }

        /* ── CATEGORY TABS ── */
        .cat-tabs {
            display: flex;
            gap: 6px;
            padding: 12px 20px;
            overflow-x: auto;
            scrollbar-width: none;
            background: var(--surface);
            border-bottom: 1px solid var(--border-light);
            position: sticky;
            top: 63px;
            z-index: 90;
        }
        .cat-tabs::-webkit-scrollbar { display: none; }
        .cat-tab {
            white-space: nowrap;
            padding: 8px 18px;
            border-radius: 50px;
            border: 1.5px solid var(--border);
            background: transparent;
            color: var(--text-secondary);
            font-weight: 600;
            font-size: 0.78rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .cat-tab:hover { border-color: var(--accent); color: var(--accent); }
        .cat-tab.active {
            background: var(--primary);
            color: #fff;
            border-color: var(--primary);
        }

        /* ── PRODUCT GRID ── */
        .products-wrapper { padding: 16px 16px 100px; }
        .section-label {
            font-weight: 700;
            font-size: 0.68rem;
            color: var(--text-tertiary);
            letter-spacing: 0.12em;
            text-transform: uppercase;
            margin: 20px 0 12px;
            padding-left: 4px;
        }
        .product-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
        }
        @media (min-width: 480px) { .product-grid { grid-template-columns: repeat(3, 1fr); } }
        @media (min-width: 768px) { .product-grid { grid-template-columns: repeat(4, 1fr); } }

        .product-card {
            background: var(--surface);
            border: 1px solid var(--border-light);
            border-radius: var(--radius);
            overflow: hidden;
            cursor: pointer;
            transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
        }
        .product-card:hover {
            border-color: var(--border);
            transform: translateY(-2px);
            box-shadow: var(--shadow);
        }
        .product-card.in-cart {
            border-color: var(--accent);
            box-shadow: 0 0 0 1px var(--accent), var(--shadow-sm);
        }
        .product-img {
            width: 100%;
            aspect-ratio: 4/3;
            object-fit: cover;
            background: var(--bg-warm);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.2rem;
            color: var(--text-tertiary);
        }
        .product-img img { width: 100%; height: 100%; object-fit: cover; }
        .product-info { padding: 10px 10px 12px; }
        .product-name {
            font-weight: 600;
            font-size: 0.78rem;
            color: var(--text);
            line-height: 1.4;
            margin-bottom: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }
        .product-price {
            font-weight: 700;
            color: var(--primary);
            font-size: 0.82rem;
            letter-spacing: -0.01em;
        }
        .qty-control {
            display: flex;
            align-items: center;
            gap: 0;
            margin-top: 8px;
            background: var(--bg);
            border-radius: var(--radius-sm);
            overflow: hidden;
        }
        .qty-btn {
            width: 30px;
            height: 30px;
            border: none;
            background: transparent;
            color: var(--text-secondary);
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.15s;
            flex-shrink: 0;
        }
        .qty-btn.plus { background: var(--primary); color: #fff; border-radius: var(--radius-sm); }
        .qty-btn:hover { opacity: 0.8; }

        /* FLOATING CART BAR - always visible at bottom */
        .float-cart-bar {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 150;
            background: var(--surface);
            border-top: 1px solid var(--border);
            padding: 12px 16px;
            padding-bottom: max(12px, env(safe-area-inset-bottom));
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 -4px 20px rgba(0,0,0,.08);
            transform: translateY(100%);
            transition: transform .3s cubic-bezier(0.4,0,0.2,1);
        }
        .float-cart-bar.visible { transform: translateY(0); }
        .float-cart-icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            background: var(--primary);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            flex-shrink: 0;
            position: relative;
        }
        .float-cart-count {
            position: absolute;
            top: -6px;
            right: -6px;
            background: var(--accent);
            color: #fff;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 0.65rem;
            font-weight: 800;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .float-cart-info { flex: 1; }
        .float-cart-label { font-size: 0.72rem; color: var(--text-tertiary); font-weight: 500; }
        .float-cart-total { font-size: 1rem; font-weight: 800; color: var(--text); letter-spacing: -0.02em; }
        .float-cart-btn {
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 50px;
            padding: 12px 24px;
            font-weight: 700;
            font-size: 0.85rem;
            cursor: pointer;
            white-space: nowrap;
            transition: all .2s;
            box-shadow: 0 4px 14px rgba(26,26,46,.25);
        }
        .float-cart-btn:hover {
            background: var(--primary-light);
            transform: translateY(-1px);
            box-shadow: 0 6px 20px rgba(26,26,46,.35);
        }
        .float-cart-btn:active { transform: translateY(0); }
        .qty-display {
            flex: 1;
            text-align: center;
            font-weight: 700;
            font-size: 0.82rem;
            color: var(--text);
        }
        .in-cart-badge {
            position: absolute;
            top: 8px;
            right: 8px;
            background: var(--primary);
            color: #fff;
            border-radius: 50%;
            width: 22px;
            height: 22px;
            font-size: 0.62rem;
            font-weight: 700;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .product-card.in-cart .in-cart-badge { display: flex; }

        /* ── MODAL OVERLAY ── */
        .modal-overlay {
            position: fixed;
            inset: 0;
            background: rgba(26, 26, 46, 0.5);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            z-index: 200;
            display: flex;
            align-items: flex-end;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }
        .modal-overlay.open { opacity: 1; visibility: visible; }
        .modal-sheet {
            background: var(--surface);
            border-radius: var(--radius-xl) var(--radius-xl) 0 0;
            width: 100%;
            max-height: 92vh;
            overflow-y: auto;
            padding: 20px 20px 32px;
            transform: translateY(100%);
            transition: transform 0.4s cubic-bezier(0.32, 0.72, 0, 1);
            box-shadow: var(--shadow-xl);
        }
        .modal-overlay.open .modal-sheet { transform: translateY(0); }
        .modal-handle {
            width: 36px;
            height: 4px;
            background: var(--border);
            border-radius: 2px;
            margin: 0 auto 20px;
        }
        .modal-title {
            font-weight: 800;
            font-size: 1.2rem;
            color: var(--text);
            margin-bottom: 4px;
            letter-spacing: -0.02em;
        }
        .modal-sub { color: var(--text-tertiary); font-size: 0.82rem; margin-bottom: 20px; }

        /* ── CART ITEMS ── */
        .cart-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 0;
            border-bottom: 1px solid var(--border-light);
        }
        .cart-item:last-child { border-bottom: none; }
        .cart-item-name { flex: 1; font-weight: 600; font-size: 0.85rem; color: var(--text); }
        .cart-item-price { font-weight: 700; color: var(--primary); font-size: 0.82rem; white-space: nowrap; }
        .cart-item-qty {
            display: flex;
            align-items: center;
            gap: 4px;
            background: var(--bg);
            border-radius: var(--radius-sm);
        }
        .cart-item-qty button {
            width: 28px; height: 28px;
            border: none;
            background: transparent;
            color: var(--text-secondary);
            font-size: 0.95rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.15s;
        }
        .cart-item-qty button.plus { background: var(--primary); color: #fff; border-radius: 8px; }
        .cart-item-qty button:hover { opacity: 0.8; }
        .cart-item-qty span {
            font-weight: 700;
            min-width: 20px;
            text-align: center;
            font-size: 0.82rem;
        }

        /* ── FORM FIELDS ── */
        .field-label {
            font-size: 0.75rem;
            font-weight: 600;
            color: var(--text-secondary);
            margin-bottom: 6px;
            display: block;
            letter-spacing: 0.02em;
        }
        .field-input {
            width: 100%;
            background: var(--bg);
            border: 1.5px solid var(--border);
            border-radius: var(--radius-sm);
            color: var(--text);
            padding: 12px 14px;
            font-size: 0.9rem;
            font-family: inherit;
            outline: none;
            transition: all 0.2s;
        }
        .field-input:focus { border-color: var(--primary); background: var(--surface); box-shadow: 0 0 0 3px rgba(26,26,46,0.06); }
        .field-input::placeholder { color: var(--text-tertiary); }

        /* ── SUMMARY ── */
        .summary-box {
            background: var(--bg);
            border-radius: var(--radius);
            padding: 14px 16px;
            margin-top: 16px;
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 0;
            font-size: 0.85rem;
        }
        .summary-row .label { color: var(--text-secondary); }
        .summary-row .value { font-weight: 600; color: var(--text); }
        .summary-row.total {
            font-weight: 800;
            font-size: 1.05rem;
            color: var(--text);
            border-top: 1px solid var(--border);
            padding-top: 10px;
            margin-top: 4px;
        }
        .summary-row.total .value { color: var(--primary); }

        /* ── PAYMENT OPTIONS ── */
        .payment-option {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 16px;
            border: 1.5px solid var(--border);
            border-radius: 16px;
            cursor: pointer;
            transition: all 0.25s cubic-bezier(0.4,0,0.2,1);
            margin-bottom: 10px;
            background: var(--surface);
            position: relative;
        }
        .payment-option:hover {
            border-color: var(--primary);
            background: var(--surface-hover);
            transform: translateY(-1px);
            box-shadow: var(--shadow);
        }
        .payment-option.selected {
            border-color: var(--primary);
            background: linear-gradient(135deg, rgba(26,26,46,0.04), rgba(26,26,46,0.01));
            box-shadow: 0 0 0 2px rgba(26,26,46,0.12);
        }
        .payment-option .icon {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.15rem;
            flex-shrink: 0;
            transition: all 0.25s;
        }
        .payment-option[data-method="tunai"] .icon { color: #10b981; background: rgba(16,185,129,0.1); }
        .payment-option[data-method="qris"] .icon  { color: #6366f1; background: rgba(99,102,241,0.1); }
        .payment-option[data-method^="bank"] .icon  { color: #f59e0b; background: rgba(245,158,11,0.1); }
        .payment-option[data-method="tunai"].selected .icon { background: #10b981; color: #fff; box-shadow: 0 4px 14px rgba(16,185,129,0.3); }
        .payment-option[data-method="qris"].selected .icon  { background: #6366f1; color: #fff; box-shadow: 0 4px 14px rgba(99,102,241,0.3); }
        .payment-option[data-method^="bank"].selected .icon  { background: #f59e0b; color: #000; box-shadow: 0 4px 14px rgba(245,158,11,0.3); }
        .payment-option .label { font-weight: 600; font-size: 0.88rem; color: var(--text); letter-spacing: -0.01em; }
        .payment-option .sublabel { font-size: 0.75rem; color: var(--text-tertiary); margin-top: 2px; }
        .payment-radio {
            margin-left: auto;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 2px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            transition: all 0.25s;
            font-size: 10px;
            color: transparent;
        }
        .payment-option.selected .payment-radio {
            border-color: var(--primary);
            background: var(--primary);
            color: #fff;
        }

        /* ── QRIS IMG ── */
        .qris-img-container {
            text-align: center;
            padding: 20px;
            background: #fff;
            border-radius: var(--radius);
            margin: 12px 0;
            border: 1px solid var(--border-light);
        }
        .qris-img-container img {
            max-width: 200px;
            width: 100%;
            border-radius: 8px;
        }

        /* ── BUTTONS ── */
        .btn-primary {
            width: 100%;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: var(--radius);
            padding: 15px;
            font-weight: 700;
            font-size: 0.92rem;
            cursor: pointer;
            transition: all 0.2s;
            letter-spacing: -0.01em;
        }
        .btn-primary:hover { background: var(--primary-light); transform: translateY(-1px); box-shadow: var(--shadow); }
        .btn-primary:active { transform: translateY(0); }
        .btn-primary:disabled { opacity: 0.4; cursor: not-allowed; transform: none; box-shadow: none; }
        .btn-secondary {
            width: 100%;
            background: var(--bg);
            color: var(--text);
            border: 1.5px solid var(--border);
            border-radius: var(--radius);
            padding: 13px;
            font-weight: 600;
            font-size: 0.85rem;
            cursor: pointer;
            transition: all 0.2s;
            margin-top: 8px;
        }
        .btn-secondary:hover { background: var(--surface); border-color: var(--primary); }

        /* ── SUCCESS SCREEN ── */
        .success-screen {
            display: none;
            text-align: center;
            padding: 40px 20px;
        }
        .success-icon {
            width: 72px; height: 72px;
            background: var(--green-bg);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.8rem;
            color: var(--green);
            margin: 0 auto 20px;
            animation: popIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }
        @keyframes popIn { from { transform: scale(0); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .success-title {
            font-weight: 800;
            font-size: 1.4rem;
            color: var(--text);
            margin-bottom: 8px;
            letter-spacing: -0.02em;
        }
        .success-sub { color: var(--text-secondary); margin-bottom: 24px; line-height: 1.7; font-size: 0.9rem; }
        .invoice-box {
            background: var(--bg);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 16px;
            font-weight: 700;
            color: var(--primary);
            font-size: 1.05rem;
            margin-bottom: 20px;
            letter-spacing: 0.02em;
        }

        /* ── ORDER TYPE PILLS ── */
        .order-type-group {
            display: flex;
            gap: 8px;
            margin-bottom: 16px;
        }
        .order-type-pill {
            flex: 1;
            text-align: center;
            padding: 12px 10px;
            border-radius: var(--radius);
            border: 1.5px solid var(--border);
            cursor: pointer;
            font-weight: 600;
            font-size: 0.8rem;
            transition: all 0.2s;
            color: var(--text-secondary);
            background: var(--bg);
        }
        .order-type-pill i { display: block; font-size: 1.2rem; margin-bottom: 4px; color: var(--text-tertiary); }
        .order-type-pill.active {
            border-color: var(--primary);
            background: rgba(26,26,46,0.04);
            color: var(--text);
        }
        .order-type-pill.active i { color: var(--primary); }

        /* ── EMPTY CART ── */
        .empty-cart {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-tertiary);
        }
        .empty-cart .icon { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.4; }

        /* ── STEP INDICATOR ── */
        .steps {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            margin-bottom: 20px;
        }
        .step-dot {
            width: 8px; height: 8px;
            border-radius: 50%;
            background: var(--border);
            transition: all 0.3s;
        }
        .step-dot.active { background: var(--primary); width: 24px; border-radius: 4px; }
        .step-dot.done { background: var(--green); }

        /* ── TOAST ── */
        .toast-msg {
            position: fixed;
            bottom: 90px;
            left: 50%;
            transform: translateX(-50%) translateY(20px);
            background: var(--primary);
            color: #fff;
            padding: 12px 24px;
            border-radius: 50px;
            font-size: 0.82rem;
            font-weight: 600;
            white-space: nowrap;
            opacity: 0;
            transition: all 0.3s;
            z-index: 9999;
            box-shadow: var(--shadow-lg);
        }
        .toast-msg.show {
            opacity: 1;
            transform: translateX(-50%) translateY(0);
        }

        /* ── SCROLLBAR ── */
        .modal-sheet::-webkit-scrollbar { width: 4px; }
        .modal-sheet::-webkit-scrollbar-thumb { background: var(--border); border-radius: 2px; }

        /* ── ANIMATIONS ── */
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .product-card { animation: fadeInUp 0.3s ease backwards; }
    </style>
</head>
<body>

<!-- TOP HEADER -->
<div class="top-header">
    <div class="header-brand">
        <div class="header-logo">
            <i class="fas fa-fire-flame-curved"></i>
        </div>
        <div>
            <h1>GoldenWok</h1>
            <div class="header-brand-sub">Self Order</div>
        </div>
    </div>
    <div style="display:flex;align-items:center;gap:10px;">
        <div class="table-badge"><i class="fas fa-chair" style="margin-right:4px;font-size:0.6rem;"></i> Meja <?= $table ?></div>
        <button class="cart-btn" onclick="openCart()">
            <i class="fas fa-bag-shopping"></i>
            <span id="cart-total-header">0</span>
            <div class="cart-count" id="cart-count-badge">0</div>
        </button>
    </div>
</div>

<!-- CATEGORY TABS -->
<div class="cat-tabs">
    <button class="cat-tab active" onclick="filterCat('all',this)"><i class="fas fa-grid-2" style="margin-right:4px;font-size:0.7rem;"></i> Semua</button>
    <button class="cat-tab" onclick="filterCat('food',this)"><i class="fas fa-utensils" style="margin-right:4px;font-size:0.7rem;"></i> Makanan</button>
    <button class="cat-tab" onclick="filterCat('drink',this)"><i class="fas fa-mug-hot" style="margin-right:4px;font-size:0.7rem;"></i> Minuman</button>
</div>

<!-- PRODUCTS -->
<div class="products-wrapper" id="products-wrapper">
    <div id="section-food">
        <div class="section-label"><i class="fas fa-utensils" style="margin-right:6px;"></i>Makanan</div>
        <div class="product-grid" id="grid-food">
            <?php foreach ($foods as $p): ?>
            <div class="product-card" id="card-<?= $p['id'] ?>" onclick="addToCart(<?= $p['id'] ?>, '<?= addslashes($p['name']) ?>', <?= $p['price'] ?>)">
                <div class="in-cart-badge" id="badge-<?= $p['id'] ?>">0</div>
                <div class="product-img">
                    <?php if ($p['img'] && $p['img'] !== 'uploads/default.jpg'): ?>
                        <img src="<?= htmlspecialchars($p['img']) ?>" alt="<?= htmlspecialchars($p['name']) ?>" loading="lazy"
                             onerror="this.parentNode.innerHTML='<i class=\'fas fa-utensils\'></i>'">
                    <?php else: ?>
                        <i class="fas fa-utensils"></i>
                    <?php endif; ?>
                </div>
                <div class="product-info">
                    <div class="product-name"><?= htmlspecialchars($p['name']) ?></div>
                    <div class="product-price">Rp <?= number_format($p['price'], 0, ',', '.') ?></div>
                    <div class="qty-control" id="qty-ctrl-<?= $p['id'] ?>" style="display:none" onclick="event.stopPropagation()">
                        <button class="qty-btn" onclick="changeQty(<?= $p['id'] ?>, -1)">-</button>
                        <div class="qty-display" id="qty-display-<?= $p['id'] ?>">1</div>
                        <button class="qty-btn plus" onclick="changeQty(<?= $p['id'] ?>, 1)">+</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div id="section-drink">
        <div class="section-label"><i class="fas fa-mug-hot" style="margin-right:6px;"></i>Minuman</div>
        <div class="product-grid" id="grid-drink">
            <?php foreach ($drinks as $p): ?>
            <div class="product-card" id="card-<?= $p['id'] ?>" onclick="addToCart(<?= $p['id'] ?>, '<?= addslashes($p['name']) ?>', <?= $p['price'] ?>)">
                <div class="in-cart-badge" id="badge-<?= $p['id'] ?>">0</div>
                <div class="product-img">
                    <?php if ($p['img'] && $p['img'] !== 'uploads/default.jpg'): ?>
                        <img src="<?= htmlspecialchars($p['img']) ?>" alt="<?= htmlspecialchars($p['name']) ?>" loading="lazy"
                             onerror="this.parentNode.innerHTML='<i class=\'fas fa-mug-hot\'></i>'">
                    <?php else: ?>
                        <i class="fas fa-mug-hot"></i>
                    <?php endif; ?>
                </div>
                <div class="product-info">
                    <div class="product-name"><?= htmlspecialchars($p['name']) ?></div>
                    <div class="product-price">Rp <?= number_format($p['price'], 0, ',', '.') ?></div>
                    <div class="qty-control" id="qty-ctrl-<?= $p['id'] ?>" style="display:none" onclick="event.stopPropagation()">
                        <button class="qty-btn" onclick="changeQty(<?= $p['id'] ?>, -1)">-</button>
                        <div class="qty-display" id="qty-display-<?= $p['id'] ?>">1</div>
                        <button class="qty-btn plus" onclick="changeQty(<?= $p['id'] ?>, 1)">+</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- ===================== MODAL: CART ===================== -->
<div class="modal-overlay" id="cartModal" onclick="if(event.target===this)closeModal('cartModal')">
    <div class="modal-sheet">
        <div class="modal-handle"></div>

        <!-- Step 1: Cart -->
        <div id="step-cart">
            <div class="steps">
                <div class="step-dot active" id="dot1"></div>
                <div class="step-dot" id="dot2"></div>
                <div class="step-dot" id="dot3"></div>
            </div>
            <div class="modal-title">Pesanan Saya</div>
            <div class="modal-sub">Meja <strong style="color:var(--primary)"><?= $table ?></strong></div>

            <div id="cart-items-list"></div>

            <div id="cart-summary" class="summary-box" style="display:none">
                <div class="summary-row">
                    <span class="label">Subtotal</span>
                    <span class="value" id="sum-subtotal">Rp 0</span>
                </div>
                <div class="summary-row">
                    <span class="label">Service (Incl.)</span>
                    <span class="value" id="sum-service">Rp 0</span>
                </div>
                <div class="summary-row">
                    <span class="label">PPN / Pajak</span>
                    <span class="value" id="sum-ppn">Rp 0</span>
                </div>
                <div class="summary-row total">
                    <span>Total</span>
                    <span class="value" id="sum-total">Rp 0</span>
                </div>
            </div>

            <div style="margin-top:20px;display:flex;gap:10px">
                <button class="btn-secondary" style="margin:0" onclick="closeModal('cartModal')">Tambah lagi</button>
                <button class="btn-primary" style="flex:1.5" id="btn-next-step1" onclick="goStep(2)">Lanjut <i class="fas fa-arrow-right" style="margin-left:4px;font-size:0.75rem;"></i></button>
            </div>
        </div>

        <!-- Step 2: Customer Info -->
        <div id="step-info" style="display:none">
            <div class="steps">
                <div class="step-dot done" id="dot1b"></div>
                <div class="step-dot active" id="dot2b"></div>
                <div class="step-dot" id="dot3b"></div>
            </div>
            <div class="modal-title">Info Pelanggan</div>
            <div class="modal-sub">Wajib isi nama, nomor meja otomatis</div>

            <div style="margin-bottom:14px">
                <label class="field-label">Nama Pemesan <span style="color:var(--red)">*</span></label>
                <input type="text" id="customer-name" class="field-input" placeholder="Masukkan nama kamu..." maxlength="80">
            </div>
            <div style="margin-bottom:14px">
                <label class="field-label">No. WhatsApp <span style="color:var(--text-tertiary)">(opsional)</span></label>
                <input type="tel" id="customer-phone" class="field-input" placeholder="08xxxxxxxxxx" maxlength="20">
            </div>
            <div style="margin-bottom:14px">
                <label class="field-label">Tipe Order</label>
                <div class="order-type-group">
                    <div class="order-type-pill active" onclick="selectOrderType('dinein',this)"><i class="fas fa-chair"></i>Dine In</div>
                    <div class="order-type-pill" onclick="selectOrderType('takeaway',this)"><i class="fas fa-bag-shopping"></i>Take Away</div>
                </div>
            </div>
            <div style="margin-bottom:14px">
                <label class="field-label">Nomor Meja</label>
                <input type="text" class="field-input" value="Meja <?= $table ?>" disabled style="opacity:0.6">
            </div>
            <div style="display:flex;gap:10px">
                <button class="btn-secondary" style="margin:0" onclick="goStep(1)"><i class="fas fa-arrow-left" style="margin-right:4px;font-size:0.7rem;"></i> Kembali</button>
                <button class="btn-primary" style="flex:1.5" onclick="goStep(3)">Pilih Pembayaran <i class="fas fa-arrow-right" style="margin-left:4px;font-size:0.75rem;"></i></button>
            </div>
        </div>

        <!-- Step 3: Payment -->
        <div id="step-payment" style="display:none">
            <div class="steps">
                <div class="step-dot done"></div>
                <div class="step-dot done"></div>
                <div class="step-dot active"></div>
            </div>
            <div class="modal-title">Metode Pembayaran</div>
            <div class="modal-sub" id="pay-summary-text"></div>

            <div id="payment-options">
                <?php if ($tunai_enabled): ?>
                <div class="payment-option" onclick="selectPayment('tunai',this)" data-method="tunai">
                    <div class="icon"><i class="fas fa-money-bill-wave"></i></div>
                    <div>
                        <div class="label">Tunai</div>
                        <div class="sublabel">Bayar ke kasir setelah pesanan</div>
                    </div>
                    <div class="payment-radio"><i class="fas fa-check"></i></div>
                </div>
                <?php endif; ?>

                <?php if ($qris_enabled): ?>
                <div class="payment-option" onclick="selectPayment('qris',this)" data-method="qris">
                    <div class="icon"><i class="fas fa-qrcode"></i></div>
                    <div>
                        <div class="label">QRIS</div>
                        <div class="sublabel"><?= htmlspecialchars($qris_name) ?></div>
                    </div>
                    <div class="payment-radio"><i class="fas fa-check"></i></div>
                </div>
                <?php if ($qris_image): ?>
                <div id="qris-img-box" style="display:none">
                    <div class="qris-img-container">
                        <p style="color:var(--text-secondary);font-size:0.75rem;font-weight:600;margin-bottom:8px;">Scan untuk bayar</p>
                        <img src="<?= htmlspecialchars($qris_image) ?>" alt="QRIS">
                        <p style="color:var(--text-tertiary);font-size:0.7rem;margin-top:8px;"><?= htmlspecialchars($qris_name) ?></p>
                    </div>
                </div>
                <?php endif; ?>
                <?php endif; ?>

                <?php foreach ($pay_banks as $bank): ?>
                <div class="payment-option" onclick="selectPayment('bank_<?= $bank['id'] ?>',this)" data-method="bank_<?= $bank['id'] ?>">
                    <div class="icon"><i class="fas fa-building-columns"></i></div>
                    <div>
                        <div class="label"><?= htmlspecialchars($bank['bank_name']) ?></div>
                        <div class="sublabel"><?= htmlspecialchars($bank['account_number']) ?> · <?= htmlspecialchars($bank['account_name']) ?></div>
                    </div>
                    <div class="payment-radio"><i class="fas fa-check"></i></div>
                </div>
                <?php endforeach; ?>
            </div>

            <div style="margin-top:20px;display:flex;gap:10px">
                <button class="btn-secondary" style="margin:0" onclick="goStep(2)"><i class="fas fa-arrow-left" style="margin-right:4px;font-size:0.7rem;"></i> Kembali</button>
                <button class="btn-primary" style="flex:1.5" id="btn-confirm" onclick="submitOrder()" disabled>
                    <i class="fas fa-check" style="margin-right:4px;font-size:0.8rem;"></i> Konfirmasi Order
                </button>
            </div>
        </div>

        <!-- Step 4: Success -->
        <div id="step-success" style="display:none">
            <div class="success-screen" style="display:block">
                <div class="success-icon"><i class="fas fa-check"></i></div>
                <div class="success-title">Pesanan Masuk!</div>
                <p class="success-sub">Pesanan kamu sudah diterima dan sedang diproses. Mohon tunggu, ya!</p>
                <div class="invoice-box" id="success-invoice"></div>
                <button class="btn-primary" onclick="resetAll()">Order Lagi</button>
            </div>
        </div>
    </div>
</div>

<!-- TOAST -->
<div class="toast-msg" id="toast-msg"></div>

<script>
    const TABLE_NO = <?= $table ?>;

    const RATE_TAKEAWAY = Number(<?= $fee_takeaway_rate ?>);

    const RATE_SERVICE  = Number(<?= $fee_service_rate ?>);

    const RATE_PPN      = Number(<?= $fee_ppn_rate ?>);

    let cart = {};
    let selectedOrderType = 'dinein';
    let selectedPayment = null;

    // ── Cart Logic ─────────────────────────────────────────────────────
    function addToCart(id, name, price) {
        if (cart[id]) {
            cart[id].qty++;
        } else {
            cart[id] = { id, name, price, qty: 1 };
        }
        updateCardUI(id);
        updateCartHeader();
        showToast(`${name} ditambahkan`);
    }

    function changeQty(id, delta) {
        if (!cart[id]) return;
        cart[id].qty += delta;
        if (cart[id].qty <= 0) {
            delete cart[id];
            document.getElementById(`card-${id}`).classList.remove('in-cart');
            document.getElementById(`qty-ctrl-${id}`).style.display = 'none';
            document.getElementById(`badge-${id}`).style.display = 'none';
        } else {
            document.getElementById(`qty-display-${id}`).textContent = cart[id].qty;
            document.getElementById(`badge-${id}`).textContent = cart[id].qty;
        }
        updateCartHeader();
    }

    function updateCardUI(id) {
        const card = document.getElementById(`card-${id}`);
        const ctrl = document.getElementById(`qty-ctrl-${id}`);
        const badge = document.getElementById(`badge-${id}`);
        const display = document.getElementById(`qty-display-${id}`);
        card.classList.add('in-cart');
        ctrl.style.display = 'flex';
        badge.style.display = 'flex';
        if (display) display.textContent = cart[id].qty;
        if (badge) badge.textContent = cart[id].qty;
    }

    function updateCartHeader() {
        const items = Object.values(cart);
        const totalQty = items.reduce((s,i) => s + i.qty, 0);
        const subtotal = items.reduce((s,i) => s + (i.price * i.qty), 0);
        document.getElementById('cart-count-badge').textContent = totalQty;
        document.getElementById('cart-total-header').textContent = 'Rp ' + fmt(subtotal);
        // Update floating bar
        const floatBar = document.getElementById('float-cart-bar');
        document.getElementById('float-cart-count').textContent = totalQty;
        document.getElementById('float-cart-total').textContent = 'Rp ' + fmt(subtotal);
        if (totalQty > 0) floatBar.classList.add('visible');
        else floatBar.classList.remove('visible');
    }

    // ── Open Cart Modal ─────────────────────────────────────────────────
    function openCart() {
        renderCartStep();
        openModal('cartModal');
        goStep(1);
    }

    function renderCartStep() {
        const items = Object.values(cart);
        const list = document.getElementById('cart-items-list');
        const summary = document.getElementById('cart-summary');

        if (items.length === 0) {
            list.innerHTML = `<div class="empty-cart"><div class="icon"><i class="fas fa-bag-shopping"></i></div><p>Keranjang masih kosong</p></div>`;
            summary.style.display = 'none';
            document.getElementById('btn-next-step1').disabled = true;
            return;
        }

        document.getElementById('btn-next-step1').disabled = false;
        list.innerHTML = items.map(i => `
            <div class="cart-item">
                <div class="cart-item-name">${i.name}</div>
                <div class="cart-item-qty">
                    <button onclick="changeQtyCart(${i.id},-1)">-</button>
                    <span>${i.qty}</span>
                    <button class="plus" onclick="changeQtyCart(${i.id},1)">+</button>
                </div>
                <div class="cart-item-price">Rp ${fmt(i.price * i.qty)}</div>
            </div>
        `).join('');

        const subtotal = items.reduce((s,i) => s + (i.price * i.qty), 0);
        const service  = Math.round(subtotal * RATE_SERVICE / 100);
        const ppn      = Math.round((subtotal + service) * RATE_PPN / 100);
        const total    = subtotal + service + ppn;

        document.getElementById('sum-subtotal').textContent = 'Rp ' + fmt(subtotal);
        document.getElementById('sum-service').textContent  = 'Rp ' + fmt(service);
        document.getElementById('sum-ppn').textContent      = 'Rp ' + fmt(ppn);
        document.getElementById('sum-total').textContent    = 'Rp ' + fmt(total);
        summary.style.display = 'block';
    }

    function changeQtyCart(id, delta) {
        changeQty(id, delta);
        renderCartStep();
    }

    // ── Steps ───────────────────────────────────────────────────────────
    function goStep(n) {
        if (n === 2) {
            const items = Object.values(cart);
            if (items.length === 0) { showToast('Pilih menu dulu!'); return; }
        }
        if (n === 3) {
            const name = document.getElementById('customer-name').value.trim();
            if (!name) { showToast('Nama wajib diisi!'); document.getElementById('customer-name').focus(); return; }
        }
        ['cart','info','payment','success'].forEach((s,i) => {
            document.getElementById(`step-${s}`).style.display = (i+1 === n) ? 'block' : 'none';
        });
        if (n === 3) renderPaymentSummary();
    }

    function renderPaymentSummary() {
        const items = Object.values(cart);
        const subtotal = items.reduce((s,i) => s + (i.price * i.qty), 0);
        const service  = Math.round(subtotal * RATE_SERVICE / 100);
        const fee      = selectedOrderType === 'takeaway' ? Math.round(subtotal * RATE_TAKEAWAY / 100) : 0;
        const ppn      = Math.round((subtotal + service + fee) * RATE_PPN / 100);
        const total    = subtotal + service + fee + ppn;
        document.getElementById('pay-summary-text').textContent =
            `Total yang harus dibayar: Rp ${fmt(total)}`;
    }

    // ── Order Type ──────────────────────────────────────────────────────
    function selectOrderType(type, el) {
        selectedOrderType = type;
        document.querySelectorAll('.order-type-pill').forEach(e => e.classList.remove('active'));
        el.classList.add('active');
    }

    // ── Payment Selection ───────────────────────────────────────────────
    function selectPayment(method, el) {
        selectedPayment = method;
        document.querySelectorAll('.payment-option').forEach(e => e.classList.remove('selected'));
        el.classList.add('selected');
        document.getElementById('btn-confirm').disabled = false;
        // Show QRIS QR if selected
        const qrisBox = document.getElementById('qris-img-box');
        if (qrisBox) qrisBox.style.display = (method === 'qris') ? 'block' : 'none';
    }

    // ── Submit Order ────────────────────────────────────────────────────
    async function submitOrder() {
        const btn = document.getElementById('btn-confirm');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right:6px;"></i> Memproses...';

        const items = Object.values(cart);
        const customerName = document.getElementById('customer-name').value.trim();
        const customerPhone = document.getElementById('customer-phone').value.trim();
        const subtotal = items.reduce((s,i) => s + (i.price * i.qty), 0);
        const service  = Math.round(subtotal * RATE_SERVICE / 100);
        const fee      = selectedOrderType === 'takeaway' ? Math.round(subtotal * RATE_TAKEAWAY / 100) : 0;
        const ppn      = Math.round((subtotal + service + fee) * RATE_PPN / 100);
        const total    = subtotal + service + fee + ppn;

        const cartForServer = items.map(i => ({
            id: i.id, name: i.name, price: i.price, qty: i.qty
        }));

        const fd = new FormData();
        fd.append('cart', JSON.stringify(cartForServer));
        fd.append('customer', customerName);
        fd.append('phone', customerPhone);
        fd.append('order_type', selectedOrderType);
        fd.append('table_no', TABLE_NO);
        fd.append('payment_method', selectedPayment || 'tunai');
        fd.append('voucher_discount', '0');
        fd.append('voucher_code', '');

        try {
            const res = await fetch('save_customer_order.php', { method: 'POST', body: fd });
            const data = await res.json();

            if (data.success) {
                document.getElementById('success-invoice').textContent = '# ' + data.invoice;
                goStep(4);
                cart = {};
                updateCartHeader();
                document.getElementById('float-cart-bar').classList.remove('visible');
                // Reset card UIs
                document.querySelectorAll('.product-card').forEach(c => c.classList.remove('in-cart'));
                document.querySelectorAll('[id^="qty-ctrl-"]').forEach(c => c.style.display = 'none');
                document.querySelectorAll('[id^="badge-"]').forEach(c => c.style.display = 'none');
            } else {
                showToast(data.message || 'Gagal, coba lagi');
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-check" style="margin-right:4px;font-size:0.8rem;"></i> Konfirmasi Order';
            }
        } catch (e) {
            showToast('Koneksi bermasalah');
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-check" style="margin-right:4px;font-size:0.8rem;"></i> Konfirmasi Order';
        }
    }

    // ── Reset ───────────────────────────────────────────────────────────
    function resetAll() {
        closeModal('cartModal');
        selectedPayment = null;
        selectedOrderType = 'dinein';
        document.getElementById('customer-name').value = '';
        document.getElementById('customer-phone').value = '';
    }

    // ── Category Filter ─────────────────────────────────────────────────
    function filterCat(cat, el) {
        document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
        el.classList.add('active');
        document.getElementById('section-food').style.display  = (cat === 'drink') ? 'none' : 'block';
        document.getElementById('section-drink').style.display = (cat === 'food')  ? 'none' : 'block';
    }

    // ── Helpers ─────────────────────────────────────────────────────────
    function openModal(id) { document.getElementById(id).classList.add('open'); document.body.style.overflow='hidden'; }
    function closeModal(id) { document.getElementById(id).classList.remove('open'); document.body.style.overflow=''; }
    function fmt(n) { return n.toLocaleString('id-ID'); }
    function showToast(msg) {
        const t = document.getElementById('toast-msg');
        t.textContent = msg;
        t.classList.add('show');
        setTimeout(() => t.classList.remove('show'), 2200);
    }
</script>

<!-- FLOATING CART BAR -->
<div class="float-cart-bar" id="float-cart-bar">
    <div class="float-cart-icon" onclick="openCart()">
        <i class="fas fa-bag-shopping"></i>
        <div class="float-cart-count" id="float-cart-count">0</div>
    </div>
    <div class="float-cart-info">
        <div class="float-cart-label">Total Pesanan</div>
        <div class="float-cart-total" id="float-cart-total">Rp 0</div>
    </div>
    <button class="float-cart-btn" onclick="openCart()">
        Pesan <i class="fas fa-arrow-right" style="margin-left:4px;font-size:0.7rem;"></i>
    </button>
</div>
</body>
</html>