<?php
$db = getDB();
$restaurant_id = $_SESSION['restaurant_id'];

// Fetch all printing settings
$pStmt = $db->prepare('SELECT setting_key, setting_value FROM restaurant_settings WHERE restaurant_id = ?');
$pStmt->execute([$restaurant_id]);
$pRows = $pStmt->fetchAll();
$printSettings = [];
foreach ($pRows as $row) {
    $printSettings[$row['setting_key']] = $row['setting_value'];
}

// Load feature gate to check module permissions
$gate = FeatureGate::check($restaurant_id);
$hasHr = !$gate['expired'] && !empty($gate['features']['staff_management']);
$hasKitchen = !$gate['expired'] && !empty($gate['features']['kitchen_display']);
$hasInventory = !$gate['expired'] && !empty($gate['features']['inventory']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS - <?php echo htmlspecialchars($restaurant_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qz-tray@2.2.4/qz-tray.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { font-family: 'Inter', sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #06080f; color: #e2e8f0; overflow: hidden; }
        .hide-scroll::-webkit-scrollbar { display: none; }
        .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }
        .glass { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); backdrop-filter: blur(12px); }
        .glass-hover:hover { background: rgba(255,255,255,0.06); border-color: rgba(139,92,246,0.3); }
        .glow-purple { box-shadow: 0 0 20px rgba(139,92,246,0.15), inset 0 1px 0 rgba(255,255,255,0.05); }
        .glow-green { box-shadow: 0 0 15px rgba(16,185,129,0.2); }
        .glow-amber { box-shadow: 0 0 15px rgba(245,158,11,0.25); }
        .table-available { background: rgba(16,185,129,0.06); border: 1px solid rgba(16,185,129,0.2); }
        .table-available:hover { background: rgba(16,185,129,0.12); border-color: rgba(16,185,129,0.4); transform: scale(1.02); }
        .table-occupied { background: rgba(245,158,11,0.08); border: 1px solid rgba(245,158,11,0.3); cursor: pointer; }
        .table-occupied:hover { background: rgba(245,158,11,0.15); }
        .product-card { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); transition: all 0.2s ease; }
        .product-card:hover { background: rgba(139,92,246,0.08); border-color: rgba(139,92,246,0.3); transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,0,0,0.3); }
        .product-img { aspect-ratio: 1; object-fit: cover; width: 100%; border-radius: 10px; }
        .cart-item { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); }
        .cart-item-locked { background: rgba(245,158,11,0.05); border: 1px solid rgba(245,158,11,0.15); }
        .btn-kot { background: linear-gradient(135deg, #1e293b, #334155); border: 1px solid rgba(255,255,255,0.1); }
        .btn-kot:hover { background: linear-gradient(135deg, #334155, #475569); }
        .btn-pay-later { background: linear-gradient(135deg, #b45309, #d97706); }
        .btn-pay-later:hover { background: linear-gradient(135deg, #d97706, #f59e0b); }
        .btn-pay-now { background: linear-gradient(135deg, #7c3aed, #6d28d9); }
        .btn-pay-now:hover { background: linear-gradient(135deg, #8b5cf6, #7c3aed); }
        .btn-void { background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); color: #fca5a5; }
        .btn-void:hover { background: rgba(239,68,68,0.25); }
        .pulse-amber { animation: pulseAmber 2s infinite; }
        @keyframes pulseAmber { 0%, 100% { box-shadow: 0 0 0 0 rgba(245,158,11,0.4); } 50% { box-shadow: 0 0 0 8px rgba(245,158,11,0); } }
        .cat-pill { transition: all 0.15s ease; }
        .cat-pill.active { background: linear-gradient(135deg, #7c3aed, #6d28d9); color: white; box-shadow: 0 4px 15px rgba(124,58,237,0.3); }
        /* Print Styles */
        @media print {
            body > *:not(#print-area) { display: none !important; }
            #print-area { display: block !important; position: static; background: white; color: black; }
            .no-print { display: none !important; }
        }
        #print-area { display: none; }

        /* Light Theme overrides */
        body.light-theme {
            background: #f8fafc !important;
            color: #0f172a !important;
        }
        body.light-theme header, 
        body.light-theme footer {
            background: #ffffff !important;
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme header h1,
        body.light-theme header span,
        body.light-theme header p,
        body.light-theme footer span {
            color: #0f172a !important;
        }
        body.light-theme .flex-1.flex-col {
            background: #f1f5f9 !important;
        }
        body.light-theme .w-80, 
        body.light-theme .xl\:w-96 {
            background: #ffffff !important;
            border-left-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme .text-white {
            color: #0f172a !important;
        }
        body.light-theme .text-slate-300 {
            color: #1e293b !important;
        }
        body.light-theme .text-slate-400 {
            color: #334155 !important;
        }
        body.light-theme .text-slate-500 {
            color: #475569 !important;
        }
        body.light-theme .text-slate-600 {
            color: #64748b !important;
        }
        body.light-theme .text-purple-300 {
            color: #6d28d9 !important;
        }
        body.light-theme .glass {
            background: rgba(0, 0, 0, 0.02) !important;
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme .glass-hover:hover {
            background: rgba(0, 0, 0, 0.04) !important;
            border-color: rgba(139, 92, 246, 0.4) !important;
        }
        body.light-theme .product-card {
            background: #ffffff !important;
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme .product-card:hover {
            background: rgba(139, 92, 246, 0.04) !important;
            border-color: rgba(139, 92, 246, 0.3) !important;
        }
        body.light-theme .cart-item {
            background: rgba(0, 0, 0, 0.02) !important;
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme .cart-item-locked {
            background: rgba(245, 158, 11, 0.05) !important;
            border-color: rgba(245, 158, 11, 0.2) !important;
        }
        body.light-theme .cat-pill:not(.active) {
            background: rgba(0, 0, 0, 0.04) !important;
            border-color: rgba(0, 0, 0, 0.06) !important;
            color: #475569 !important;
        }
        body.light-theme select, 
        body.light-theme input {
            background: #ffffff !important;
            border-color: rgba(0, 0, 0, 0.12) !important;
            color: #0f172a !important;
        }
        body.light-theme select option {
            background: #ffffff !important;
            color: #0f172a !important;
        }
        body.light-theme select {
            color: #334155 !important;
        }
        body.light-theme input::placeholder {
            color: #94a3b8 !important;
        }
        body.light-theme .fixed .max-w-md,
        body.light-theme .fixed .max-w-4xl {
            background: #ffffff !important;
            border-color: rgba(0, 0, 0, 0.1) !important;
        }
        body.light-theme .fixed .border-white\/8,
        body.light-theme .fixed .border-white\/6,
        body.light-theme .fixed .border-white\/10 {
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
        body.light-theme .fixed .bg-white\/3 {
            background: rgba(0, 0, 0, 0.02) !important;
        }
        body.light-theme .bg-white\/5 {
            background: rgba(0, 0, 0, 0.04) !important;
        }
        body.light-theme .border-white\/5 {
            border-color: rgba(0, 0, 0, 0.06) !important;
        }
        body.light-theme .border-white\/8 {
            border-color: rgba(0, 0, 0, 0.08) !important;
        }
    </style>
</head>
<body class="h-screen flex flex-col" x-data="posApp" :class="theme === 'light' ? 'light-theme' : ''">

    <!-- ═══ HEADER ═══ -->
    <header class="h-12 flex items-center justify-between px-4 flex-shrink-0" style="background: rgba(15,17,30,0.95); border-bottom: 1px solid rgba(139,92,246,0.15);">
        <div class="flex items-center gap-3">
            <?php
            $dashboardUrl = '';
            $exitTitle = 'Pause ordering and return to Dashboard';
            if (isset($_SESSION['role'])) {
                if ($_SESSION['role'] === 'admin') {
                    $dashboardUrl = '/restpo/admin/dashboard';
                } elseif ($_SESSION['role'] === 'superadmin') {
                    $dashboardUrl = '/restpo/superadmin/dashboard';
                } else {
                    $dashboardUrl = '/restpo/logout';
                    $exitTitle = 'Pause ordering and log out';
                }
            }
            if (!empty($dashboardUrl)):
            ?>
                <a href="<?php echo $dashboardUrl; ?>" class="px-2.5 py-1.5 rounded-lg text-[11px] font-bold transition glass glass-hover text-slate-300 flex items-center gap-1.5 mr-1 animate-pulse" title="<?php echo htmlspecialchars($exitTitle); ?>">
                    <i class="fas fa-pause text-amber-400"></i> Pause & Exit
                </a>
            <?php endif; ?>
            <div class="flex items-center gap-2">
                <?php if (!empty($restaurant_logo)): ?>
                    <img src="/restpo/<?php echo htmlspecialchars($restaurant_logo); ?>" class="w-7 h-7 rounded-lg object-cover" alt="logo">
                <?php else: ?>
                    <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-purple-600 to-violet-700 flex items-center justify-center">
                        <i class="fas fa-utensils text-white text-xs"></i>
                    </div>
                <?php endif; ?>
                <div>
                    <h1 class="text-sm font-bold text-white leading-none"><?php echo htmlspecialchars($restaurant_name); ?></h1>
                    <p class="text-[10px] text-slate-500 leading-none mt-0.5">
                        <i class="fas fa-user-tie mr-0.5"></i> 
                        <?php echo htmlspecialchars($cashier_name); ?>
                        <?php if ((($_SESSION['role'] ?? '') === 'admin' || ($_SESSION['role'] ?? '') === 'superadmin') && isset($_SESSION['selected_cashier_id'])): ?>
                            <a href="/restpo/pos?cashier_id=change" class="text-purple-400 hover:text-purple-300 ml-2 font-semibold underline inline-flex items-center gap-0.5" title="Change Cashier Context">
                                <i class="fas fa-arrows-rotate text-[9px]"></i>Switch
                            </a>
                        <?php endif; ?>
                    </p>
                </div>
            </div>
        </div>
        <div class="flex items-center gap-4">
            <span class="text-xs text-slate-400 font-mono"><i class="fas fa-clock mr-1 text-purple-400/60"></i><span x-text="currentTime"></span></span>
            <button @click="toggleTheme()" class="w-8 h-8 rounded-lg flex items-center justify-center transition glass glass-hover text-slate-300" title="Toggle Light/Dark Theme">
                <i :class="theme === 'light' ? 'fas fa-moon text-amber-500' : 'fas fa-sun text-yellow-400'"></i>
            </button>
            <button @click="showTerminalSettings = true" class="w-8 h-8 rounded-lg flex items-center justify-center transition glass glass-hover text-slate-300" title="Terminal Hardware Settings">
                <i class="fas fa-print text-indigo-400"></i>
            </button>
            <?php if ($hasHr): ?>
                <a href="/restpo/admin/hr" class="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold transition glass glass-hover text-slate-300 flex items-center gap-1" title="HR & Staff Management">
                    <i class="fas fa-id-badge text-sky-400"></i> HR
                </a>
            <?php endif; ?>
            <?php if ($hasKitchen): ?>
                <a href="/restpo/kitchen" class="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold transition glass glass-hover text-slate-300 flex items-center gap-1" title="Kitchen Display">
                    <i class="fas fa-fire-burner text-amber-400"></i> Kitchen
                </a>
            <?php endif; ?>
            <?php if ($hasInventory): ?>
                <a href="/restpo/admin/inventory" class="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold transition glass glass-hover text-slate-300 flex items-center gap-1" title="Inventory">
                    <i class="fas fa-boxes text-emerald-400"></i> Inventory
                </a>
            <?php endif; ?>
            <div class="flex items-center gap-1.5">
                <button x-show="pendingOrders.length > 0" @click="showActiveOrders = true; playChime()" 
                    class="relative px-3 py-1.5 rounded-lg text-xs font-semibold transition text-amber-300 border border-amber-500/30 hover:bg-amber-500/15 pulse-amber" 
                    title="View Pending Orders">
                    <i class="fas fa-bell mr-1 animate-bounce"></i> <span x-text="pendingOrders.length"></span> Pending
                </button>
                <button @click="showActiveOrders = true" class="relative px-3 py-1.5 rounded-lg text-xs font-semibold transition glass glass-hover text-slate-300">
                    <i class="fas fa-receipt mr-1 text-purple-400"></i> Orders
                    <span x-show="activeOrders.length > 0" x-text="activeOrders.length" class="absolute -top-1.5 -right-1.5 bg-red-500 text-white text-[10px] font-bold rounded-full h-4 w-4 flex items-center justify-center"></span>
                </button>
                <form action="/restpo/pos/session/close" method="POST" class="inline">
                    <button type="submit" onclick="return confirm('Close this session?')" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition text-red-400 hover:bg-red-500/10 border border-red-500/20">
                        <i class="fas fa-power-off mr-1"></i> End
                    </button>
                </form>
            </div>
        </div>
    </header>

    <!-- ═══ MAIN AREA ═══ -->
    <div class="flex-1 flex overflow-hidden">

        <!-- ══ LEFT PANEL: Tables / Products ══ -->
        <div class="flex-1 flex flex-col overflow-hidden" style="background: #080b14;">

            <!-- ── TABLE SELECTION VIEW ── -->
            <div x-show="mode === 'tables'" class="flex-1 flex flex-col overflow-hidden">
                <!-- Floor Tabs -->
                <div class="flex items-center gap-2 px-4 pt-4 pb-2 flex-shrink-0">
                    <span class="text-xs font-bold uppercase tracking-widest text-slate-500 mr-2">Select Table</span>
                    <template x-for="floor in floors" :key="floor.id">
                        <button @click="activeFloor = floor.id"
                            :class="activeFloor === floor.id ? 'bg-purple-600/20 text-purple-300 border-purple-500/40' : 'text-slate-500 border-white/5 hover:border-white/15'"
                            class="px-3 py-1 rounded-lg text-xs font-semibold border transition" x-text="floor.name">
                        </button>
                    </template>
                </div>

                <!-- Tables Grid -->
                <div class="flex-1 overflow-y-auto hide-scroll px-4 pb-4">
                    <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8 gap-3">
                        <template x-for="table in floorTables" :key="table.id">
                            <button @click="clickTable(table)"
                                :class="table.status === 'occupied' ? 'table-occupied pulse-amber' : 'table-available'"
                                class="rounded-xl p-3 text-center transition-all flex flex-col items-center justify-center h-24 relative group">
                                <i class="text-xl mb-1" :class="table.status === 'occupied' ? 'fas fa-concierge-bell text-amber-400' : 'fas fa-chair text-emerald-400/70'"></i>
                                <span class="text-sm font-bold" :class="table.status === 'occupied' ? 'text-amber-300' : 'text-white'" x-text="table.name"></span>
                                <span class="text-[10px] mt-0.5" :class="table.status === 'occupied' ? 'text-amber-500/70' : 'text-slate-500'">
                                    <i class="fas fa-users mr-0.5"></i><span x-text="table.capacity"></span>
                                </span>
                                <!-- Occupied badge -->
                                <div x-show="table.status === 'occupied'" class="absolute top-1 right-1">
                                    <span class="text-[9px] font-extrabold uppercase bg-amber-500/20 text-amber-400 px-1.5 py-0.5 rounded border border-amber-500/30">Pending</span>
                                </div>
                            </button>
                        </template>
                    </div>
                </div>
            </div>

            <!-- ── ORDERING VIEW (after table selected) ── -->
            <div x-show="mode === 'ordering'" class="flex-1 flex flex-col overflow-hidden">
                <!-- Top Bar: Table info + Search + Categories -->
                <div class="px-4 pt-3 pb-2 flex-shrink-0 space-y-2">
                    <!-- Table Info Bar -->
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-2">
                            <button @click="backToTables()" class="text-slate-500 hover:text-white transition text-xs"><i class="fas fa-arrow-left mr-1"></i></button>
                            <span class="text-xs font-bold text-white"><i class="fas fa-concierge-bell text-purple-400 mr-1"></i>Table: <span x-text="selectedTableName" class="text-purple-300"></span></span>
                            <span x-show="isResuming" class="text-[10px] font-bold uppercase bg-amber-500/15 text-amber-400 px-2 py-0.5 rounded border border-amber-500/20">Resuming Order #<span x-text="activeOrderNumber"></span></span>
                        </div>
                        <div class="relative w-56">
                            <i class="fas fa-search absolute left-2.5 top-2 text-slate-600 text-xs"></i>
                            <input type="text" x-model="searchQuery" placeholder="Search products..."
                                class="w-full pl-8 pr-3 py-1.5 text-xs rounded-lg bg-white/5 border border-white/8 text-white placeholder-slate-600 focus:border-purple-500/40 focus:bg-white/8 outline-none transition">
                        </div>
                    </div>

                    <!-- Category Pills -->
                    <div class="flex gap-1.5 overflow-x-auto hide-scroll">
                        <button @click="activeCategory = null" :class="!activeCategory ? 'active' : 'bg-white/5 text-slate-400 border-white/8 hover:bg-white/8'"
                            class="cat-pill px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap border border-transparent">All</button>
                        <template x-for="cat in categories" :key="cat.id">
                            <button @click="activeCategory = cat.id" :class="activeCategory === cat.id ? 'active' : 'bg-white/5 text-slate-400 border-white/8 hover:bg-white/8'"
                                class="cat-pill px-3 py-1.5 rounded-lg text-xs font-semibold whitespace-nowrap border border-transparent" x-text="cat.name"></button>
                        </template>
                    </div>
                </div>

                <!-- Products Grid -->
                <div class="flex-1 overflow-y-auto hide-scroll px-4 pb-4">
                    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
                        <template x-for="product in filteredProducts" :key="product.id">
                            <button @click="addToCart(product)" class="product-card rounded-xl overflow-hidden text-left group relative">
                                <!-- Product Image -->
                                <div class="aspect-square bg-gradient-to-br from-slate-800/50 to-slate-900/50 relative overflow-hidden rounded-t-xl">
                                    <template x-if="product.image">
                                        <img :src="'/restpo/public/' + product.image" :alt="product.name" class="product-img" loading="lazy">
                                    </template>
                                    <template x-if="!product.image">
                                        <div class="w-full h-full flex items-center justify-center">
                                            <i class="fas fa-utensils text-slate-700 text-2xl"></i>
                                        </div>
                                    </template>
                                    <!-- Hover Overlay -->
                                    <div class="absolute inset-0 bg-purple-600/0 group-hover:bg-purple-600/20 transition-all flex items-center justify-center">
                                        <div class="w-10 h-10 rounded-full bg-white/0 group-hover:bg-white/20 flex items-center justify-center transition-all transform scale-50 group-hover:scale-100">
                                            <i class="fas fa-plus text-white opacity-0 group-hover:opacity-100 transition-all"></i>
                                        </div>
                                    </div>
                                    <!-- Cart badge -->
                                    <template x-if="getCartQty(product.id) > 0">
                                        <div class="absolute top-1.5 right-1.5 bg-purple-600 text-white text-[10px] font-bold rounded-full h-5 w-5 flex items-center justify-center shadow-lg" x-text="getCartQty(product.id)"></div>
                                    </template>
                                </div>
                                <div class="p-2.5">
                                    <h4 class="font-semibold text-white text-xs leading-tight truncate" x-text="product.name"></h4>
                                    <div class="text-purple-400 font-bold text-xs mt-1"><span x-text="currency"></span><span x-text="parseFloat(product.price).toFixed(2)"></span></div>
                                </div>
                            </button>
                        </template>
                    </div>
                    <div x-show="filteredProducts.length === 0" class="flex flex-col items-center justify-center py-20 text-slate-600">
                        <i class="fas fa-search text-3xl mb-3"></i>
                        <p class="text-sm">No products found</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- ══ RIGHT PANEL: Cart ══ -->
        <div class="w-80 xl:w-96 flex flex-col flex-shrink-0" style="background: #0c0f1a; border-left: 1px solid rgba(255,255,255,0.05);">
            <!-- Cart Header -->
            <div class="px-4 py-3 flex justify-between items-center flex-shrink-0" style="border-bottom: 1px solid rgba(255,255,255,0.05);">
                <h2 class="text-sm font-bold text-white flex items-center gap-2">
                    <i class="fas fa-shopping-cart text-purple-400 text-xs"></i> Current Order
                </h2>
                <button x-show="!isResuming && cart.length > 0" @click="clearCart()" class="text-[10px] text-slate-500 hover:text-red-400 transition font-semibold">
                    <i class="fas fa-trash-alt mr-0.5"></i> Clear
                </button>
            </div>

            <!-- Waiter Selection (only for new orders) -->
            <div x-show="mode === 'ordering' && !isResuming" class="px-4 py-2 flex-shrink-0" style="border-bottom: 1px solid rgba(255,255,255,0.04);">
                <label class="text-[10px] font-bold uppercase tracking-wider text-slate-500 mb-1 block">Assign Waiter <span class="text-red-400 font-extrabold">*</span></label>
                <button @click="waiterSelectTarget = 'cart'; waiterSearchQuery = ''; showWaiterSelectModal = true;"
                    type="button"
                    :class="theme === 'light' 
                        ? (cart.length > 0 && !selectedWaiterId ? 'border-red-500/50 bg-red-50/50 text-slate-800 hover:bg-red-50' : 'border-slate-200 bg-white text-slate-800 hover:bg-slate-50')
                        : (cart.length > 0 && !selectedWaiterId ? 'border-red-500/50 bg-red-500/5 text-slate-300 hover:bg-red-500/10' : 'border-white/8 bg-white/5 text-slate-300 hover:bg-white/8')"
                    class="w-full text-xs py-2.5 px-3 rounded-lg border outline-none focus:border-purple-500/40 transition flex items-center justify-between text-left">
                    <span class="flex items-center gap-2">
                        <i class="fas fa-user-tie text-purple-400 text-sm"></i>
                        <span class="font-semibold" x-text="selectedWaiterId ? (waiters.find(w => w.id == selectedWaiterId)?.name || 'Select Waiter') : 'Assign Waiter (Tap to select)'"></span>
                    </span>
                    <span class="text-[10px] bg-purple-600/20 text-purple-300 font-bold px-2 py-0.5 rounded border border-purple-500/30">Select</span>
                </button>
            </div>


            <!-- Discount Coupon -->
            <div x-show="mode === 'ordering'" class="px-4 py-2 flex-shrink-0" style="border-bottom: 1px solid rgba(255,255,255,0.04);">
                <label class="text-[10px] font-bold uppercase tracking-wider text-slate-500 mb-1 block">Apply Coupon</label>
                <select x-model="selectedCouponCode" @change="applyCouponByCode(); if(isResuming) { updateOrderCoupon(activeOrderId, selectedCouponCode); }" class="w-full text-xs py-1.5 px-2.5 rounded-lg bg-white/5 border border-white/8 text-slate-300 outline-none focus:border-purple-500/40 transition">
                    <option value="">— No Coupon —</option>
                    <template x-for="c in availableCoupons" :key="c.id">
                        <option :value="c.code" x-text="c.code + ' (' + (c.type === 'percentage' ? c.value + '%' : currency + parseFloat(c.value).toFixed(2)) + ')'"></option>
                    </template>
                </select>
                <!-- Coupon alert/message -->
                <p x-show="couponMessage" class="text-[9px] mt-1 font-semibold" :class="couponSuccess ? 'text-emerald-400' : 'text-red-400'" x-text="couponMessage"></p>
            </div>

            <!-- Cart Items -->
            <div class="flex-1 overflow-y-auto hide-scroll px-3 py-2 space-y-1.5">
                <!-- Empty State -->
                <div x-show="lockedItems.length === 0 && cart.length === 0" class="h-full flex flex-col items-center justify-center text-slate-600">
                    <i class="fas fa-shopping-basket text-3xl mb-2 opacity-30"></i>
                    <p class="text-xs">No items added</p>
                </div>

                <!-- Locked Items (from pending order — cannot decrease/remove) -->
                <template x-for="(item, idx) in lockedItems" :key="'locked-' + idx">
                    <div class="cart-item-locked rounded-lg px-3 py-2 flex items-center gap-2">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-1">
                                <i class="fas fa-lock text-[8px] text-amber-500/60"></i>
                                <h4 class="font-semibold text-slate-300 text-xs truncate" x-text="item.name"></h4>
                            </div>
                            <div class="text-[10px] text-slate-500 mt-0.5"><span x-text="currency"></span><span x-text="parseFloat(item.price).toFixed(2)"></span> each</div>
                        </div>
                        <div class="flex items-center gap-1.5">
                            <div class="text-xs font-bold text-amber-300"><span x-text="currency"></span><span x-text="(item.price * item.qty).toFixed(2)"></span></div>
                            <div class="flex items-center rounded-md border border-amber-500/20 bg-amber-500/5">
                                <span class="px-2 py-0.5 text-xs font-bold text-amber-300 w-8 text-center" x-text="item.qty"></span>
                                <button @click="increaseLockedItem(idx)" class="px-1.5 py-0.5 text-amber-400 hover:bg-amber-500/15 rounded-r-md transition"><i class="fas fa-plus text-[9px]"></i></button>
                            </div>
                        </div>
                    </div>
                </template>

                <!-- Divider if both locked + new items exist -->
                <div x-show="lockedItems.length > 0 && cart.length > 0" class="flex items-center gap-2 py-1">
                    <div class="flex-1 border-t border-dashed border-purple-500/20"></div>
                    <span class="text-[9px] font-bold uppercase tracking-widest text-purple-400/60">New Items</span>
                    <div class="flex-1 border-t border-dashed border-purple-500/20"></div>
                </div>

                <!-- New Cart Items (full control) -->
                <template x-for="(item, index) in cart" :key="'cart-' + index">
                    <div class="cart-item rounded-lg px-3 py-2 flex items-center gap-2">
                        <div class="flex-1 min-w-0">
                            <h4 class="font-semibold text-white text-xs truncate" x-text="item.name"></h4>
                            <div class="text-[10px] text-slate-500 mt-0.5"><span x-text="currency"></span><span x-text="parseFloat(item.price).toFixed(2)"></span> each</div>
                        </div>
                        <div class="flex items-center gap-1.5">
                            <div class="text-xs font-bold text-white"><span x-text="currency"></span><span x-text="(item.price * item.qty).toFixed(2)"></span></div>
                            <div class="flex items-center rounded-md border border-white/10 bg-white/5">
                                <button @click="updateQty(index, -1)" class="px-1.5 py-0.5 text-slate-400 hover:text-red-400 hover:bg-red-500/10 rounded-l-md transition"><i class="fas fa-minus text-[9px]"></i></button>
                                <span class="px-2 py-0.5 text-xs font-bold text-white w-7 text-center" x-text="item.qty"></span>
                                <button @click="updateQty(index, 1)" class="px-1.5 py-0.5 text-slate-400 hover:text-emerald-400 hover:bg-emerald-500/10 rounded-r-md transition"><i class="fas fa-plus text-[9px]"></i></button>
                            </div>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Totals & Actions -->
            <div class="flex-shrink-0 px-4 py-3" style="border-top: 1px solid rgba(255,255,255,0.06); background: rgba(255,255,255,0.01);">
                <!-- Totals -->
                <div class="space-y-1 mb-3">
                    <div class="flex justify-between text-xs text-slate-400">
                        <span>Subtotal</span>
                        <span><span x-text="currency"></span><span x-text="grandSubtotal.toFixed(2)"></span></span>
                    </div>
                    <div x-show="discountRate > 0" class="flex justify-between text-xs text-emerald-400">
                        <span>Discount (<span x-text="discountRate"></span>%)</span>
                        <span>-<span x-text="currency"></span><span x-text="(grandSubtotal * (discountRate / 100)).toFixed(2)"></span></span>
                    </div>
                    <div x-show="couponDiscountAmount > 0" class="flex justify-between text-xs text-emerald-400">
                        <span>Coupon Discount (<span x-text="selectedCouponCode"></span>)</span>
                        <span>-<span x-text="currency"></span><span x-text="couponDiscountAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between text-xs text-slate-400">
                        <span>Tax (<span x-text="taxRate"></span>%)</span>
                        <span><span x-text="currency"></span><span x-text="taxAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between text-base font-extrabold text-white pt-1.5 mt-1.5" style="border-top: 1px solid rgba(255,255,255,0.08);">
                        <span>Total</span>
                        <span class="text-purple-400"><span x-text="currency"></span><span x-text="grandTotal.toFixed(2)"></span></span>
                    </div>
                </div>

                <!-- Action Buttons — New Order -->
                <div x-show="!isResuming" class="space-y-1.5">
                    <div class="grid grid-cols-2 gap-1.5">
                        <button @click="doPayLater()" :disabled="!canSubmit" :class="canSubmit ? 'btn-pay-later' : 'bg-slate-800 text-slate-600 cursor-not-allowed'" class="py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1 transition">
                            <i class="fas fa-clock"></i> Pay Later
                        </button>
                        <button @click="doPayNow()" :disabled="!canSubmit" :class="canSubmit ? 'btn-pay-now' : 'bg-slate-800 text-slate-600 cursor-not-allowed'" class="py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1 transition shadow-lg">
                            <i class="fas fa-credit-card"></i> Pay Now
                        </button>
                    </div>
                </div>

                <!-- Action Buttons — Resuming Pending Order -->
                <div x-show="isResuming" class="space-y-1.5">
                    <div class="grid grid-cols-2 gap-1.5">
                        <button x-show="hasNewItems" @click="doPrintKotResume()" class="btn-kot py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1 transition">
                            <i class="fas fa-print"></i> Print KOT
                        </button>
                        <button x-show="!hasNewItems" @click="printCurrentResumedUnpaidBill()" class="btn-pay-later py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1 transition shadow-lg">
                            <i class="fas fa-file-invoice"></i> Not Paid Bill
                        </button>
                        <button @click="doPayPending()" class="btn-pay-now py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1 transition shadow-lg">
                            <i class="fas fa-credit-card"></i> Pay Bill
                        </button>
                    </div>
                    <button @click="doVoidOrder()" class="w-full btn-void py-2 rounded-xl text-xs font-semibold flex items-center justify-center gap-1 transition">
                        <i class="fas fa-ban"></i> Void Order
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ FOOTER ═══ -->
    <footer class="h-7 flex items-center justify-center flex-shrink-0" style="background: rgba(15,17,30,0.95); border-top: 1px solid rgba(139,92,246,0.1);">
        <span class="text-[10px] text-slate-600 font-medium tracking-wider">Powered By <span class="text-purple-500/80 font-bold">RESTPO</span></span>
    </footer>

    <!-- ═══ PAYMENT MODAL ═══ -->
    <div x-show="showPayment" class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display:none; background: rgba(0,0,0,0.8); backdrop-filter: blur(8px);" x-transition>
        <div @click.away="showPayment = false" class="w-full max-w-md rounded-2xl overflow-hidden" style="background: #0f111a; border: 1px solid rgba(139,92,246,0.2); box-shadow: 0 25px 50px rgba(0,0,0,0.5);">
            <div class="px-5 py-4 flex justify-between items-center" style="border-bottom: 1px solid rgba(255,255,255,0.06);">
                <h2 class="text-base font-bold text-white"><i class="fas fa-cash-register text-purple-400 mr-2"></i>Process Payment</h2>
                <button @click="showPayment = false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            <div class="p-5 space-y-5">
                <!-- Total Display -->
                <div class="text-center py-3 rounded-xl" style="background: rgba(139,92,246,0.08); border: 1px solid rgba(139,92,246,0.15);">
                    <div class="text-[10px] uppercase tracking-widest text-purple-400/80 font-bold mb-1">Total Due</div>
                    <div class="text-3xl font-black text-white"><span x-text="currency"></span><span x-text="payTotal.toFixed(2)"></span></div>
                </div>

                <!-- Payment Method -->
                <div class="grid grid-cols-5 gap-1.5">
                    <button @click="payMethod = 'cash'" :class="payMethod === 'cash' ? 'border-purple-500/50 bg-purple-500/10' : 'border-white/8 bg-white/3'" class="border rounded-xl p-2.5 text-center transition">
                        <i class="fas fa-money-bill-wave text-base mb-1 block" :class="payMethod === 'cash' ? 'text-purple-400' : 'text-slate-500'"></i>
                        <span class="text-[9px] font-bold" :class="payMethod === 'cash' ? 'text-white' : 'text-slate-400'">Cash</span>
                    </button>
                    <button @click="payMethod = 'card'" :class="payMethod === 'card' ? 'border-purple-500/50 bg-purple-500/10' : 'border-white/8 bg-white/3'" class="border rounded-xl p-2.5 text-center transition">
                        <i class="fas fa-credit-card text-base mb-1 block" :class="payMethod === 'card' ? 'text-purple-400' : 'text-slate-500'"></i>
                        <span class="text-[9px] font-bold" :class="payMethod === 'card' ? 'text-white' : 'text-slate-400'">Card</span>
                    </button>
                    <button @click="payMethod = 'bkash'" :class="payMethod === 'bkash' ? 'border-pink-500/50 bg-pink-500/10' : 'border-white/8 bg-white/3'" class="border rounded-xl p-2.5 text-center transition">
                        <i class="fas fa-mobile-screen text-base mb-1 block" :class="payMethod === 'bkash' ? 'text-pink-400' : 'text-slate-500'"></i>
                        <span class="text-[9px] font-bold" :class="payMethod === 'bkash' ? 'text-white' : 'text-slate-400'">bKash</span>
                    </button>
                    <button @click="payMethod = 'nagad'" :class="payMethod === 'nagad' ? 'border-orange-500/50 bg-orange-500/10' : 'border-white/8 bg-white/3'" class="border rounded-xl p-2.5 text-center transition">
                        <i class="fas fa-mobile-screen text-base mb-1 block" :class="payMethod === 'nagad' ? 'text-orange-400' : 'text-slate-500'"></i>
                        <span class="text-[9px] font-bold" :class="payMethod === 'nagad' ? 'text-white' : 'text-slate-400'">Nagad</span>
                    </button>
                    <button @click="payMethod = 'others'" :class="payMethod === 'others' ? 'border-purple-500/50 bg-purple-500/10' : 'border-white/8 bg-white/3'" class="border rounded-xl p-2.5 text-center transition">
                        <i class="fas fa-ellipsis-h text-base mb-1 block" :class="payMethod === 'others' ? 'text-purple-400' : 'text-slate-500'"></i>
                        <span class="text-[9px] font-bold" :class="payMethod === 'others' ? 'text-white' : 'text-slate-400'">Others</span>
                    </button>
                </div>

                <!-- Cash Amount -->
                <div x-show="payMethod === 'cash'" class="space-y-3">
                    <div>
                        <label class="text-[10px] font-bold uppercase tracking-wider text-slate-500 mb-1 block">Amount Received</label>
                        <input type="number" step="0.01" x-model.number="payGiven" class="w-full px-4 py-3 rounded-xl bg-white/5 border border-white/10 text-white text-xl font-bold text-center outline-none focus:border-purple-500/40 transition">
                        <div class="grid grid-cols-6 gap-1 mt-2">
                            <template x-for="amt in [50, 100, 150, 200, 500, 1000]" :key="amt">
                                <button @click="payGiven = amt" type="button" class="py-1 px-1 text-[10px] font-bold rounded-lg border border-purple-500/20 bg-purple-500/5 text-purple-300 hover:bg-purple-500/20 transition text-center" x-text="amt"></button>
                            </template>
                        </div>
                    </div>
                    <div class="flex justify-between items-center px-3 py-2 rounded-lg" style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.05);">
                        <span class="text-xs text-slate-400 font-medium">Change</span>
                        <span class="text-lg font-bold" :class="payGiven >= payTotal ? 'text-emerald-400' : 'text-red-400'">
                            <span x-text="currency"></span><span x-text="Math.max(0, payGiven - payTotal).toFixed(2)"></span>
                        </span>
                    </div>
                </div>

                <!-- Pay Button -->
                <button @click="executePayment()" :disabled="isProcessing || (payMethod === 'cash' && payGiven < payTotal)"
                    class="w-full py-3.5 rounded-xl text-sm font-bold transition disabled:bg-slate-800 disabled:text-slate-600 disabled:cursor-not-allowed"
                    :class="!(isProcessing || (payMethod === 'cash' && payGiven < payTotal)) ? 'bg-gradient-to-r from-emerald-600 to-emerald-500 text-white shadow-lg hover:from-emerald-500 hover:to-emerald-400' : ''">
                    <i class="fas fa-check-circle mr-1" x-show="!isProcessing"></i>
                    <i class="fas fa-circle-notch fa-spin mr-1" x-show="isProcessing"></i>
                    <span x-text="isProcessing ? 'Processing...' : 'Complete Payment'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- ═══ ACTIVE ORDERS MODAL ═══ -->
    <div x-show="showActiveOrders" class="fixed inset-0 z-50 flex items-center justify-center p-4" style="display:none; background: rgba(0,0,0,0.8); backdrop-filter: blur(8px);" x-transition>
        <div @click.away="showActiveOrders = false" class="w-full max-w-4xl max-h-[80vh] rounded-2xl flex flex-col overflow-hidden" style="background: #0f111a; border: 1px solid rgba(255,255,255,0.08);">
            <div class="px-5 py-4 flex justify-between items-center flex-shrink-0" style="border-bottom: 1px solid rgba(255,255,255,0.06);">
                <h2 class="text-base font-bold text-white"><i class="fas fa-receipt text-purple-400 mr-2"></i>Active Orders</h2>
                <button @click="showActiveOrders = false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            <div class="flex-1 overflow-y-auto p-5 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                <template x-for="order in activeOrders" :key="order.id">
                    <div class="rounded-xl p-4 flex flex-col" style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06);">
                        <div class="flex justify-between items-start mb-2 pb-2" style="border-bottom: 1px solid rgba(255,255,255,0.05);">
                            <div>
                                <h3 class="font-bold text-white text-sm">
                                    <span x-show="order.table_name" x-text="order.table_name"></span>
                                    <span x-show="!order.table_name" class="capitalize" x-text="order.order_type"></span>
                                </h3>
                                <p class="text-[10px] text-slate-500 mt-0.5">Order #<span x-text="order.order_number"></span> • <span x-text="order.waiter_name || 'No waiter'"></span></p>
                            </div>
                            <span class="text-[9px] font-extrabold uppercase px-2 py-0.5 rounded"
                                :class="order.status === 'pending' ? 'bg-blue-500/15 text-blue-400 border border-blue-500/20' : 'bg-amber-500/15 text-amber-400 border border-amber-500/20'"
                                x-text="order.status"></span>
                        </div>
                        <div class="flex-1 overflow-y-auto max-h-28 mb-2 space-y-0.5 text-xs">
                            <template x-for="item in order.items">
                                <div class="flex justify-between text-slate-400">
                                    <span><span x-text="item.quantity"></span>x <span x-text="item.name"></span></span>
                                    <span><span x-text="currency"></span><span x-text="parseFloat(item.subtotal).toFixed(2)"></span></span>
                                </div>
                            </template>
                        </div>
                        <div class="flex justify-between items-center pt-2 mb-2" style="border-top: 1px solid rgba(255,255,255,0.05);">
                            <span class="text-xs text-slate-500 font-medium">Total</span>
                            <span class="font-bold text-purple-400"><span x-text="currency"></span><span x-text="parseFloat(order.total).toFixed(2)"></span></span>
                        </div>
                        <div class="grid grid-cols-2 gap-1.5 mt-auto">
                            <!-- Pending waiter orders -->
                            <button x-show="order.status === 'pending' && order.waiter_id" @click="acceptWaiterOrder(order.id)" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-blue-600/20 text-blue-300 border border-blue-500/20 hover:bg-blue-600/30" title="Accept waiter order">
                                <i class="fas fa-check mr-0.5"></i> Accept Order
                            </button>
                            <!-- Pending QR orders -->
                            <button x-show="order.status === 'pending' && !order.waiter_id" @click="currentQrOrder = order; popupWaiterId = ''; showQrPopup = true; showActiveOrders = false;" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-amber-600/20 text-amber-300 border border-amber-500/20 hover:bg-amber-600/30" title="Accept QR order">
                                <i class="fas fa-check mr-0.5"></i> Accept QR Order
                            </button>
                            <button x-show="order.status === 'pending'" @click="printUnpaidBill(order)" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-amber-600/15 border border-amber-500/15 text-amber-300 hover:bg-amber-600/25" title="Print Pre-Bill Invoice (Unpaid)">
                                <i class="fas fa-file-invoice mr-0.5"></i> Not Paid Bill
                            </button>
                            
                            <!-- Accepted unpaid orders -->
                            <button x-show="order.status !== 'pending'" @click="resumeOrder(order); showActiveOrders = false" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-white/5 border border-white/8 text-slate-300 hover:bg-white/10" title="Add more items to this table">
                                <i class="fas fa-plus mr-0.5"></i> Add Items
                            </button>
                            <button x-show="order.status !== 'pending'" @click="payExistingOrder(order); showActiveOrders = false" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-emerald-600/20 text-emerald-300 border border-emerald-500/20 hover:bg-emerald-600/30" title="Settle payment for this table">
                                <i class="fas fa-credit-card mr-0.5"></i> Pay Bill
                            </button>
                            <button x-show="order.status !== 'pending'" @click="printUnpaidBill(order)" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-amber-600/15 border border-amber-500/15 text-amber-300 hover:bg-amber-600/25" title="Print Pre-Bill Invoice (Unpaid)">
                                <i class="fas fa-file-invoice mr-0.5"></i> Not Paid Bill
                            </button>
                            <button x-show="order.status !== 'pending'" @click="reprintKot(order)" class="py-1.5 rounded-lg text-[11px] font-semibold transition bg-blue-600/10 border border-blue-500/15 text-blue-300 hover:bg-blue-600/25" title="Print Kitchen Order Ticket">
                                <i class="fas fa-print mr-0.5"></i> Print KOT
                            </button>
                        </div>
                    </div>
                </template>
                <div x-show="activeOrders.length === 0" class="col-span-full flex flex-col items-center justify-center py-16 text-slate-600">
                    <i class="fas fa-inbox text-3xl mb-3"></i>
                    <p class="text-sm">No active orders</p>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ QR PENDING ORDER POPUP ═══ -->
    <div x-show="showQrPopup" class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in" style="display:none; background: rgba(0,0,0,0.85); backdrop-filter: blur(10px);" x-transition>
        <div :class="currentQrOrder && currentQrOrder.waiter_id ? 'w-full max-w-md rounded-2xl overflow-hidden glass border-blue-500/20 shadow-blue-500/10 shadow-2xl' : 'w-full max-w-md rounded-2xl overflow-hidden glass glow-amber'" style="background: #0f111a; border: 1px solid rgba(245,158,11,0.25); box-shadow: 0 25px 50px rgba(0,0,0,0.6);">
            <!-- Header -->
            <div class="px-5 py-4 flex justify-between items-center" :style="currentQrOrder && currentQrOrder.waiter_id ? 'border-bottom: 1px solid rgba(59,130,246,0.15);' : 'border-bottom: 1px solid rgba(245,158,11,0.15);'">
                <h2 :class="currentQrOrder && currentQrOrder.waiter_id ? 'text-base font-bold text-blue-400 flex items-center gap-2' : 'text-base font-bold text-amber-400 flex items-center gap-2'">
                    <i :class="currentQrOrder && currentQrOrder.waiter_id ? 'fas fa-utensils text-lg animate-pulse' : 'fas fa-qrcode text-lg animate-pulse'"></i>
                    <span x-text="currentQrOrder && currentQrOrder.waiter_id ? 'New Waiter Dine-in Order!' : 'New QR Dine-in Order!'"></span>
                </h2>
                <button @click="dismissQrPopup()" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            
            <!-- Content -->
            <div class="p-5 space-y-4" x-show="currentQrOrder">
                <!-- Info Grid -->
                <div class="grid grid-cols-2 gap-2 text-xs">
                    <div class="rounded-lg p-2 bg-white/5 border border-white/5">
                        <span class="text-slate-500 block mb-0.5">Table</span>
                        <span class="font-bold text-white text-sm" x-text="currentQrOrder ? currentQrOrder.table_name : ''"></span>
                    </div>
                    <div class="rounded-lg p-2 bg-white/5 border border-white/5">
                        <span class="text-slate-500 block mb-0.5">Order Number</span>
                        <span class="font-bold text-white text-sm">#<span x-text="currentQrOrder ? currentQrOrder.order_number : ''"></span></span>
                    </div>
                </div>

                <!-- Items list -->
                <div class="rounded-lg p-3 bg-white/3 border border-white/5 max-h-40 overflow-y-auto space-y-1.5 hide-scroll">
                    <div class="text-[10px] font-bold uppercase tracking-wider text-slate-500 pb-1 border-b border-white/5 mb-1.5">Items Ordered</div>
                    <template x-if="currentQrOrder">
                        <template x-for="item in currentQrOrder.items">
                            <div class="flex justify-between items-center text-xs">
                                <span class="text-slate-300 font-medium"><span x-text="item.quantity"></span>x <span x-text="item.name"></span></span>
                                <span class="font-semibold text-slate-400"><span x-text="currency"></span><span x-text="parseFloat(item.subtotal).toFixed(2)"></span></span>
                            </div>
                        </template>
                    </template>
                </div>

                <!-- Total due -->
                <div class="flex justify-between items-center p-3 rounded-lg" style="background: rgba(139,92,246,0.08); border: 1px solid rgba(139,92,246,0.15);">
                    <span class="text-xs text-slate-400 font-semibold">Total Amount</span>
                    <span class="text-lg font-bold text-purple-400"><span x-text="currency"></span><span x-text="currentQrOrder ? parseFloat(currentQrOrder.total).toFixed(2) : '0.00'"></span></span>
                </div>

                <!-- Waiter Assignment (only for QR orders) -->
                <div class="space-y-1" x-show="currentQrOrder && !currentQrOrder.waiter_id">
                    <label class="text-[10px] font-bold uppercase tracking-wider text-slate-400 block">Assign Waiter (Required to Accept)</label>
                    
                    <button @click="waiterSelectTarget = 'qr'; waiterSearchQuery = ''; showWaiterSelectModal = true;"
                        type="button"
                        :class="theme === 'light' 
                            ? (popupWaiterId ? 'border-purple-500/40 bg-white text-slate-800 hover:bg-slate-50' : 'border-slate-200 bg-white text-slate-800 hover:bg-slate-50')
                            : (popupWaiterId ? 'border-purple-500/40 bg-slate-900 text-white hover:bg-slate-850' : 'border-white/10 bg-slate-900 text-white hover:bg-white/5')"
                        class="w-full text-xs py-2.5 px-3 rounded-xl border outline-none transition flex items-center justify-between text-left">
                        <span class="flex items-center gap-2">
                            <i class="fas fa-user-tie text-purple-400 text-sm"></i>
                            <span class="font-semibold" x-text="popupWaiterId ? (waiters.find(w => w.id == popupWaiterId)?.name || 'Select Waiter') : 'Assign Waiter (Tap to select)'"></span>
                        </span>
                        <span class="text-[10px] bg-purple-600/20 text-purple-300 font-bold px-2 py-0.5 rounded border border-purple-500/30">Select</span>
                    </button>
                </div>
                
                <!-- Waiter Name display (only for Waiter orders) -->
                <div x-show="currentQrOrder && currentQrOrder.waiter_id" class="rounded-lg p-3 bg-blue-500/10 border border-blue-500/20 text-xs flex justify-between items-center">
                    <span class="text-blue-300 font-semibold">Waiter Assigned</span>
                    <span class="font-bold text-white font-mono" x-text="currentQrOrder ? currentQrOrder.waiter_name : ''"></span>
                </div>

                <!-- Actions -->
                <div class="grid grid-cols-2 gap-2 pt-2">
                    <button @click="rejectQrOrder(currentQrOrder.id)" class="py-2.5 rounded-xl text-xs font-bold transition text-red-400 hover:bg-red-500/10 border border-red-500/20">
                        <i class="fas fa-ban mr-1"></i> Reject & Void
                    </button>
                    <button @click="acceptQrOrder(currentQrOrder.id)" :disabled="(!popupWaiterId && currentQrOrder && !currentQrOrder.waiter_id) || isProcessing"
                        :class="((popupWaiterId || (currentQrOrder && currentQrOrder.waiter_id)) && !isProcessing) ? 'bg-gradient-to-r from-emerald-600 to-emerald-500 text-white hover:from-emerald-500 hover:to-emerald-400 shadow-lg' : 'bg-slate-800 text-slate-600 cursor-not-allowed'"
                        class="py-2.5 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1">
                        <i class="fas fa-check-circle"></i> Accept Order
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ WAITER SELECT MODAL ═══ -->
    <div x-show="showWaiterSelectModal" class="fixed inset-0 z-[60] flex items-center justify-center p-4" style="display:none; background: rgba(0,0,0,0.85); backdrop-filter: blur(10px);" x-transition>
        <div @click.away="showWaiterSelectModal = false" class="w-full max-w-2xl max-h-[85vh] rounded-2xl flex flex-col overflow-hidden" :class="theme === 'light' ? 'bg-white border-slate-200' : 'bg-[#0f111a] border-white/8'" style="border: 1px solid; box-shadow: 0 25px 50px rgba(0,0,0,0.6);">
            <!-- Header -->
            <div class="px-5 py-4 flex justify-between items-center" style="border-bottom: 1px solid rgba(255,255,255,0.06);">
                <h2 class="text-base font-bold flex items-center gap-2" :class="theme === 'light' ? 'text-slate-800' : 'text-white'">
                    <i class="fas fa-user-tie text-purple-400 text-lg"></i>
                    <span>Select Waiter</span>
                </h2>
                <button @click="showWaiterSelectModal = false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            
            <!-- Search & Actions -->
            <div class="p-4 flex-shrink-0" style="border-bottom: 1px solid rgba(255,255,255,0.04);">
                <div class="relative w-full">
                    <i class="fas fa-search absolute left-3.5 top-3.5 text-slate-500 text-sm"></i>
                    <input type="text" x-model="waiterSearchQuery" placeholder="Search waiter by name..." 
                        :class="theme === 'light' ? 'bg-slate-50 border-slate-200 text-slate-800 placeholder-slate-400' : 'bg-white/5 border border-white/8 text-white placeholder-slate-600'"
                        class="w-full pl-10 pr-9 py-2.5 rounded-xl outline-none focus:border-purple-500/40 transition text-sm">
                    <button x-show="waiterSearchQuery" @click="waiterSearchQuery = ''" type="button" class="absolute right-3.5 top-3 text-slate-500 hover:text-slate-800 dark:hover:text-white">
                        <i class="fas fa-times text-sm"></i>
                    </button>
                </div>
            </div>

            <!-- Waiter Grid -->
            <div class="flex-1 overflow-y-auto p-5 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 hide-scroll">
                <template x-for="w in waiters.filter(x => !waiterSearchQuery || x.name.toLowerCase().includes(waiterSearchQuery.toLowerCase())).sort((a, b) => a.name.localeCompare(b.name))" :key="w.id">
                    <button @click="selectWaiterFromModal(w.id)"
                        :class="isWaiterActive(w.id)
                            ? 'border-purple-500/50 bg-purple-500/10' 
                            : (theme === 'light' ? 'border-slate-200 hover:border-purple-500/40 hover:bg-purple-50/20 text-slate-800 bg-white' : 'border-white/5 hover:border-purple-500/40 hover:bg-white/5 text-slate-300 bg-white/3')"
                        class="rounded-xl p-3 border text-center transition flex flex-col items-center justify-center gap-2 group relative">
                        
                        <!-- Avatar circle with initials -->
                        <div :class="isWaiterActive(w.id) ? 'bg-purple-600 text-white' : 'bg-purple-600/10 text-purple-400'" 
                            class="w-12 h-12 rounded-full flex items-center justify-center font-bold text-base transition-transform group-hover:scale-105">
                            <span x-text="w.name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase()"></span>
                        </div>
                        
                        <!-- Waiter name -->
                        <div class="text-xs font-bold leading-tight" x-text="w.name"></div>
                        
                        <!-- Active Indicator badge -->
                        <div x-show="isWaiterActive(w.id)" class="absolute top-1.5 right-1.5">
                            <span class="h-2 w-2 rounded-full bg-emerald-500 block"></span>
                        </div>
                    </button>
                </template>
                
                <!-- Empty Search State -->
                <div x-show="waiters.filter(x => !waiterSearchQuery || x.name.toLowerCase().includes(waiterSearchQuery.toLowerCase())).length === 0" 
                    class="col-span-full flex flex-col items-center justify-center py-10 text-slate-600">
                    <i class="fas fa-search text-2xl mb-2"></i>
                    <p class="text-xs">No waiters found matching "<span x-text="waiterSearchQuery"></span>"</p>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══ PRINT PREVIEW POPUP ═══ -->
    <div x-show="showPrintPreview" class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in" style="display:none; background: rgba(0,0,0,0.85); backdrop-filter: blur(10px);" x-transition>
        <div @click.away="showPrintPreview = false" class="w-full max-w-md rounded-2xl overflow-hidden glass border-purple-500/20 shadow-purple-500/10 shadow-2xl" style="background: #0f111a; border: 1px solid rgba(139,92,246,0.25); box-shadow: 0 25px 50px rgba(0,0,0,0.6);">
            <!-- Header -->
            <div class="px-5 py-4 flex justify-between items-center border-b border-purple-500/15">
                <h2 class="text-base font-bold text-purple-400 flex items-center gap-2">
                    <i class="fas fa-print text-lg"></i>
                    <span x-text="previewType === 'kot' ? 'Kitchen Order Ticket (KOT)' : (previewType === 'bill' ? 'Unpaid Draft Bill' : 'Customer Receipt')"></span>
                </h2>
                <button @click="showPrintPreview = false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            
            <!-- Content -->
            <div class="p-5 flex flex-col items-center space-y-4">
                <!-- Size Indicator -->
                <div class="text-[11px] text-slate-400 font-semibold px-3 py-1 rounded-full bg-slate-900 border border-white/5">
                    Paper Size: <span class="text-purple-300" x-text="printSize"></span> (<span x-text="printSize === '58mm' ? '200px width' : '280px width'"></span>)
                </div>

                <!-- Paper Container -->
                <div class="bg-white rounded-lg p-1 border border-slate-700/50 max-h-[50vh] overflow-y-auto shadow-2xl hide-scroll" :style="printSize === '58mm' ? 'width: 200px;' : 'width: 280px;'">
                    <div x-html="previewHtml" style="width: 100%;"></div>
                </div>
            </div>

            <!-- Actions -->
            <div class="px-5 py-4 bg-slate-950/50 border-t border-white/5 grid grid-cols-2 gap-3">
                <button @click="showPrintPreview = false" class="py-2.5 rounded-xl text-xs font-bold transition text-slate-400 hover:bg-white/5 border border-white/10">
                    <i class="fas fa-ban mr-1"></i> Close
                </button>
                <button @click="_doPrint(previewHtml); showPrintPreview = false;" class="py-2.5 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1.5 bg-gradient-to-r from-purple-600 to-purple-500 text-white hover:from-purple-500 hover:to-purple-400 shadow-lg shadow-purple-500/15">
                    <i class="fas fa-print"></i> Print Now
                </button>
            </div>
        </div>
    </div>

    <!-- ═══ TERMINAL HARDWARE SETTINGS MODAL ═══ -->
    <div x-show="showTerminalSettings" class="fixed inset-0 z-50 flex items-center justify-center p-4 animate-fade-in" style="display:none; background: rgba(0,0,0,0.85); backdrop-filter: blur(10px);" x-transition>
        <div @click.away="showTerminalSettings = false" class="w-full max-w-md rounded-2xl overflow-hidden glass shadow-2xl" style="background: #0f111a; border: 1px solid rgba(139,92,246,0.25);">
            <!-- Header -->
            <div class="px-5 py-4 flex justify-between items-center border-b border-white/5">
                <h2 class="text-base font-bold text-white flex items-center gap-2">
                    <i class="fas fa-desktop text-indigo-400"></i> Terminal Settings
                </h2>
                <button @click="showTerminalSettings = false" class="text-slate-500 hover:text-white transition"><i class="fas fa-times"></i></button>
            </div>
            
            <!-- Content -->
            <div class="p-5 space-y-4">
                <div class="p-3 rounded-lg border border-indigo-500/20 bg-indigo-500/5 mb-2">
                    <p class="text-[11px] text-indigo-200/70 leading-relaxed">
                        <i class="fas fa-info-circle text-indigo-400 mr-1"></i>
                        These hardware settings are saved locally in this browser. If you clear your browser data, you will need to set them again.
                    </p>
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-400 mb-1">Cashier Printer Name (QZ Tray)</label>
                    <input type="text" x-model="qzCashierPrinter" placeholder="e.g. EPSON TM-T82"
                           class="w-full px-4 py-2.5 rounded-lg text-white font-medium text-sm outline-none transition focus:ring-2 focus:ring-indigo-500/50" 
                           style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                </div>
                
                <div>
                    <label class="block text-xs font-bold text-slate-400 mb-1">Kitchen Printer Name (QZ Tray)</label>
                    <input type="text" x-model="qzKitchenPrinter" placeholder="e.g. EPSON TM-T82"
                           class="w-full px-4 py-2.5 rounded-lg text-white font-medium text-sm outline-none transition focus:ring-2 focus:ring-indigo-500/50" 
                           style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                </div>

                <label class="flex items-center gap-3 p-3 rounded-xl cursor-pointer border border-white/5 transition hover:bg-white/5" style="background:rgba(255,255,255,0.02)">
                    <div class="relative flex items-center">
                        <input type="checkbox" x-model="qzEnableCashDrawer" class="peer sr-only">
                        <div class="w-10 h-5 bg-slate-700 rounded-full peer peer-checked:bg-emerald-500 transition-colors"></div>
                        <div class="absolute left-1 top-1 w-3 h-3 bg-white rounded-full transition-transform peer-checked:translate-x-5"></div>
                    </div>
                    <div>
                        <span class="text-xs font-bold text-white block">Auto Open Cash Drawer</span>
                        <span class="text-[10px] text-slate-500">Kick drawer on Paid Bill</span>
                    </div>
                </label>
            </div>

            <!-- Actions -->
            <div class="px-5 py-4 bg-slate-950/50 border-t border-white/5 flex justify-end gap-3">
                <button @click="testQzPrint()" class="px-4 py-2 rounded-lg text-xs font-bold transition flex items-center justify-center gap-1.5 bg-emerald-600/20 text-emerald-400 border border-emerald-500/30 hover:bg-emerald-600/40">
                    <i class="fas fa-print"></i> Test Hardware
                </button>
                <div class="flex-1"></div>
                <button @click="showTerminalSettings = false" class="px-4 py-2 rounded-lg text-xs font-bold transition text-slate-400 hover:text-white">
                    Cancel
                </button>
                <button @click="saveTerminalSettings()" class="px-5 py-2 rounded-lg text-xs font-bold transition flex items-center justify-center gap-1.5 bg-indigo-600 text-white hover:bg-indigo-500 shadow-lg shadow-indigo-500/25">
                    <i class="fas fa-save"></i> Save Settings
                </button>
            </div>
        </div>
    </div>

    <!-- ═══ PRINT AREA (hidden, used for printing) ═══ -->
    <div id="print-area"></div>

    <!-- ═══ ALPINE.JS APP ═══ -->
    <script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('posApp', () => ({
            // ── Core State ──
            currentTime: '',
            currency: '<?php echo $currency; ?>',
            taxRate: <?php echo $tax_rate; ?>,
            discountRate: <?php echo $discount_rate; ?>,
            restaurantName: <?php echo json_encode($restaurant_name); ?>,
            cashierName: <?php echo json_encode($cashier_name); ?>,
            restaurantLogo: <?php echo json_encode($restaurant_logo ?? ''); ?>,
            theme: localStorage.getItem('pos-theme') || 'dark',
            restaurantId: <?php echo json_encode($_SESSION['restaurant_id'] ?? ''); ?>,
            userId: <?php echo json_encode($_SESSION['user_id'] ?? ''); ?>,
            // Printing configurations
            printSize: <?php echo json_encode($printSettings['thermal_printing_size'] ?? '80mm'); ?>,
            popupKot: <?php echo json_encode($printSettings['print_popup_kot'] ?? 'silent'); ?>,
            popupBill: <?php echo json_encode($printSettings['print_popup_bill'] ?? 'silent'); ?>,
            popupReceipt: <?php echo json_encode($printSettings['print_popup_receipt'] ?? 'silent'); ?>,
            qzCashierPrinter: localStorage.getItem('qzCashierPrinter') || '',
            qzKitchenPrinter: localStorage.getItem('qzKitchenPrinter') || '',
            qzEnableCashDrawer: localStorage.getItem('qzEnableCashDrawer') === 'true',
            qzConnected: false,
            showPrintPreview: false,
            showTerminalSettings: false,
            previewHtml: '',
            previewType: '',
            // Coupon state
            coupons: [],
            selectedCouponCode: '',
            selectedCoupon: null,
            couponMessage: '',
            couponSuccess: false,
            lastPendingCount: 0,
            toggleTheme() {
                this.theme = this.theme === 'dark' ? 'light' : 'dark';
                localStorage.setItem('pos-theme', this.theme);
            },

            // ── Data ──
            categories: [],
            products: [],
            floors: [],
            tables: [],
            waiters: [],
            activeOrders: [],
            restaurantPhone: '',
            restaurantAddress: '',

            // ── Table & Ordering State ──
            mode: 'tables', // 'tables' | 'ordering'
            activeFloor: null,
            activeCategory: null,
            searchQuery: '',
            selectedTableId: null,
            selectedTableName: '',
            selectedWaiterId: '',
            activeOrderId: null,
            activeOrderNumber: null,
            isResuming: false,

            // ── Cart ──
            cart: [],          // new items (full control)
            lockedItems: [],   // existing items from pending order (read-mostly)

            // ── UI ──
            showPayment: false,
            showActiveOrders: false,
            payMethod: 'cash',
            payGiven: 0,
            payTotal: 0,
            isProcessing: false,
            showQrPopup: false,
            currentQrOrder: null,
            popupWaiterId: '',
            dismissedQrIds: [],
            autoProcessingIds: [],
            showWaiterSelectModal: false,
            waiterSelectTarget: 'cart', // 'cart' | 'qr'
            waiterSearchQuery: '',

            // ── Client-Side State Persistence ──
            getStateKey() {
                return `pos_state_${this.restaurantId}_${this.userId}`;
            },

            saveState() {
                if (!this.restaurantId || !this.userId) return;
                const state = {
                    cart: this.cart,
                    lockedItems: this.lockedItems,
                    selectedTableId: this.selectedTableId,
                    selectedTableName: this.selectedTableName,
                    selectedWaiterId: this.selectedWaiterId,
                    activeOrderId: this.activeOrderId,
                    activeOrderNumber: this.activeOrderNumber,
                    isResuming: this.isResuming,
                    mode: this.mode,
                    selectedCouponCode: this.selectedCouponCode
                };
                localStorage.setItem(this.getStateKey(), JSON.stringify(state));
            },

            restoreState() {
                if (!this.restaurantId || !this.userId) return;
                try {
                    const saved = localStorage.getItem(this.getStateKey());
                    if (saved) {
                        const state = JSON.parse(saved);
                        if (state) {
                            this.cart = state.cart || [];
                            this.lockedItems = state.lockedItems || [];
                            this.selectedTableId = state.selectedTableId || null;
                            this.selectedTableName = state.selectedTableName || '';
                            this.selectedWaiterId = state.selectedWaiterId || '';
                            this.activeOrderId = state.activeOrderId || null;
                            this.activeOrderNumber = state.activeOrderNumber || null;
                            this.isResuming = !!state.isResuming;
                            this.mode = state.mode || 'tables';
                            this.selectedCouponCode = state.selectedCouponCode || '';
                        }
                    }
                } catch (e) {
                    console.error("Error restoring state: ", e);
                }
            },

            clearSavedState() {
                if (!this.restaurantId || !this.userId) return;
                localStorage.removeItem(this.getStateKey());
            },

            // ── Terminal Settings ──
            testQzPrint() {
                const testHtml = `<div style="text-align:center; padding: 20px;">
                    <h2>RESTPO Hardware Test</h2>
                    <p>If this printed, QZ Tray is working correctly!</p>
                    <p>${new Date().toLocaleString()}</p>
                    <p>Cash Drawer status: ${this.qzEnableCashDrawer ? 'Kicked Open' : 'Disabled'}</p>
                </div>`;
                
                // Temporarily ensure we have the latest modal state stored so _doPrint uses it
                localStorage.setItem('qzCashierPrinter', this.qzCashierPrinter);
                localStorage.setItem('qzKitchenPrinter', this.qzKitchenPrinter);
                localStorage.setItem('qzEnableCashDrawer', this.qzEnableCashDrawer);

                // Initialize if not already
                if (typeof qz !== 'undefined' && !this.qzConnected && (this.qzCashierPrinter || this.qzKitchenPrinter)) {
                    qz.websocket.connect().then(() => {
                        this.qzConnected = true;
                        this._doPrint(testHtml, 'receipt');
                    }).catch(e => alert("Could not connect to QZ Tray! Check if it's running."));
                } else {
                    this._doPrint(testHtml, 'receipt');
                }
            },

            saveTerminalSettings() {
                localStorage.setItem('qzCashierPrinter', this.qzCashierPrinter);
                localStorage.setItem('qzKitchenPrinter', this.qzKitchenPrinter);
                localStorage.setItem('qzEnableCashDrawer', this.qzEnableCashDrawer);
                this.showTerminalSettings = false;
                
                // Reconnect if needed
                if (typeof qz !== 'undefined' && !this.qzConnected && (this.qzCashierPrinter || this.qzKitchenPrinter)) {
                    qz.websocket.connect().then(() => {
                        this.qzConnected = true;
                        console.log("QZ Tray Connected!");
                    }).catch((e) => {
                        console.error("QZ Tray connection failed:", e);
                    });
                }
            },

            // ── Init ──
            init() {
                // Initialize QZ Tray
                if (typeof qz !== 'undefined' && (this.qzCashierPrinter || this.qzKitchenPrinter)) {
                    qz.websocket.connect().then(() => {
                        this.qzConnected = true;
                        console.log("QZ Tray Connected!");
                    }).catch((e) => {
                        console.error("QZ Tray connection failed:", e);
                    });
                }

                this.updateClock();
                setInterval(() => this.updateClock(), 1000);
                this.fetchData();
                setInterval(() => this.fetchData(), 3000);

                // Restore paused state
                this.restoreState();

                // Setup deep watches
                this.$watch('cart', () => this.saveState());
                this.$watch('lockedItems', () => this.saveState());
                this.$watch('selectedTableId', () => this.saveState());
                this.$watch('selectedTableName', () => this.saveState());
                this.$watch('selectedWaiterId', () => this.saveState());
                this.$watch('activeOrderId', () => this.saveState());
                this.$watch('activeOrderNumber', () => this.saveState());
                this.$watch('isResuming', () => this.saveState());
                this.$watch('mode', () => this.saveState());
                this.$watch('selectedCouponCode', () => this.saveState());
            },

            updateClock() {
                const now = new Date();
                this.currentTime = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true });
            },

            fetchData() {
                fetch('/restpo/pos/api/data')
                    .then(r => r.json())
                    .then(d => {
                        if (d.error) { window.location = '/restpo/login'; return; }
                        this.categories = d.categories;
                        this.products = d.products;
                        this.floors = d.floors;
                        this.tables = d.tables;
                        this.waiters = d.waiters || [];
                        this.activeOrders = d.active_orders;
                        this.taxRate = parseFloat(d.tax_rate) || 0;
                        this.discountRate = parseFloat(d.discount_rate) || 0;
                        this.coupons = d.coupons || [];
                        this.restaurantPhone = d.restaurant_phone || '';
                        this.restaurantAddress = d.restaurant_address || '';
                        if (!this.activeFloor && this.floors.length) this.activeFloor = this.floors[0].id;

                        // Re-apply coupon on data refresh/load
                        if (this.selectedCouponCode) {
                            this.applyCouponByCode();
                        }

                        // Play chime if new pending orders arrive
                        const currentPendingCount = this.pendingOrders.length;
                        if (currentPendingCount > this.lastPendingCount) {
                            this.playChime();
                        }
                        this.lastPendingCount = currentPendingCount;

                        this.checkPendingOrdersQueue();
                    });
            },

            checkPendingOrdersQueue() {
                if (this.showQrPopup) return;
                const pendingOrders = this.activeOrders.filter(o => o.status === 'pending' && !this.dismissedQrIds.includes(o.id));
                if (pendingOrders.length > 0) {
                    this.currentQrOrder = pendingOrders[0];
                    this.popupWaiterId = '';
                    this.showQrPopup = true;
                    this.playChime();
                }
            },

            // ── Computed ──
            get floorTables() {
                return this.tables.filter(t => t.floor_id == this.activeFloor);
            },
            get filteredProducts() {
                let p = this.products;
                if (this.activeCategory) p = p.filter(x => x.category_id == this.activeCategory);
                if (this.searchQuery) {
                    const q = this.searchQuery.toLowerCase();
                    p = p.filter(x => x.name.toLowerCase().includes(q));
                }
                return p;
            },
            get grandSubtotal() {
                const locked = this.lockedItems.reduce((s, i) => s + (i.price * i.qty), 0);
                const cart = this.cart.reduce((s, i) => s + (i.price * i.qty), 0);
                return locked + cart;
            },
            get availableCoupons() {
                return this.coupons.filter(c => {
                    if (c.floor_id !== null && this.selectedTableId) {
                        const tbl = this.tables.find(t => t.id == this.selectedTableId);
                        if (tbl && tbl.floor_id != c.floor_id) return false;
                    }
                    return true;
                });
            },
            get pendingOrders() {
                return this.activeOrders.filter(o => o.status === 'pending');
            },
            get couponDiscountAmount() {
                if (!this.selectedCoupon) return 0;
                let restrictedSubtotal = 0;
                let hasRestriction = false;

                const allItems = [
                    ...this.lockedItems.map(i => ({ id: i.id, price: i.price, qty: i.qty })),
                    ...this.cart.map(i => ({ id: i.id, price: i.price, qty: i.qty }))
                ];

                allItems.forEach(item => {
                    const prod = this.products.find(p => p.id == item.id);
                    item.category_id = prod ? prod.category_id : null;
                });

                if (this.selectedCoupon.product_id) {
                    hasRestriction = true;
                    allItems.forEach(item => {
                        if (item.id == this.selectedCoupon.product_id) {
                            restrictedSubtotal += (item.price * item.qty);
                        }
                    });
                } else if (this.selectedCoupon.category_id) {
                    hasRestriction = true;
                    allItems.forEach(item => {
                        if (item.category_id == this.selectedCoupon.category_id) {
                            restrictedSubtotal += (item.price * item.qty); // wait: category_id here? No, item.price * item.qty!
                        }
                    });
                }

                if (!hasRestriction) {
                    restrictedSubtotal = this.grandSubtotal;
                }

                if (this.selectedCoupon.type === 'percentage') {
                    return restrictedSubtotal * (parseFloat(this.selectedCoupon.value) / 100);
                } else {
                    return Math.min(restrictedSubtotal, parseFloat(this.selectedCoupon.value));
                }
            },
            get discountAmount() {
                return (this.grandSubtotal * (this.discountRate / 100)) + this.couponDiscountAmount;
            },
            get taxAmount() {
                return Math.max(0, this.grandSubtotal - this.discountAmount) * (this.taxRate / 100);
            },
            get grandTotal() {
                return Math.max(0, this.grandSubtotal - this.discountAmount) + this.taxAmount;
            },
            get canSubmit() { return this.cart.length > 0 && this.mode === 'ordering' && this.selectedWaiterId; },
            get hasNewItems() {
                if (this.cart.length > 0) return true;
                // Check if any locked item was increased
                for (let item of this.lockedItems) {
                    if (item.qty > item.originalQty) return true;
                }
                return false;
            },

            getCartQty(pid) {
                const c = this.cart.find(x => x.id == pid);
                const l = this.lockedItems.find(x => x.id == pid);
                return (c ? c.qty : 0) + (l ? l.qty - (l.originalQty || 0) : 0);
            },

            // ── Table Interaction ──
            clickTable(table) {
                if (table.status === 'occupied') {
                    // Find the pending order for this table
                    const order = this.activeOrders.find(o => o.table_id == table.id);
                    if (order) {
                        this.resumeOrder(order);
                    }
                } else {
                    this.selectedTableId = table.id;
                    this.selectedTableName = table.name;
                    this.activeOrderId = null;
                    this.activeOrderNumber = null;
                    this.isResuming = false;
                    this.cart = [];
                    this.lockedItems = [];
                    this.mode = 'ordering';
                }
                this.saveState();
            },

            resumeOrder(order) {
                this.activeOrderId = order.id;
                this.activeOrderNumber = order.order_number;
                this.selectedTableId = order.table_id;
                this.selectedTableName = order.table_name || '';
                this.selectedWaiterId = order.waiter_id || '';
                this.selectedCouponCode = order.coupon_code || '';
                if (this.selectedCouponCode) {
                    this.selectedCoupon = this.coupons.find(c => c.code === this.selectedCouponCode) || null;
                    this.couponMessage = 'Coupon applied from existing order.';
                    this.couponSuccess = true;
                } else {
                    this.selectedCoupon = null;
                    this.couponMessage = '';
                    this.couponSuccess = false;
                }
                this.isResuming = true;
                this.cart = [];
                this.lockedItems = order.items.map(i => ({
                    id: parseInt(i.product_id),
                    name: i.name,
                    price: parseFloat(i.price),
                    qty: parseInt(i.quantity),
                    originalQty: parseInt(i.quantity),
                    printedQty: parseInt(i.printed_qty || i.quantity)
                }));
                this.mode = 'ordering';
                this.saveState();
            },

            backToTables() {
                if ((this.cart.length > 0 || this.hasNewItems) && !confirm('Discard current changes?')) return;
                this.mode = 'tables';
                this.cart = [];
                this.lockedItems = [];
                this.activeOrderId = null;
                this.activeOrderNumber = null;
                this.isResuming = false;
                this.selectedTableId = null;
                this.selectedWaiterId = '';
                this.selectedCouponCode = '';
                this.selectedCoupon = null;
                this.couponMessage = '';
                this.couponSuccess = false;
                this.searchQuery = '';
                this.activeCategory = null;
                this.clearSavedState();
            },

            // ── Cart Management ──
            addToCart(product) {
                // Check if it's a locked item — if so, increase the locked item
                if (this.isResuming) {
                    const locked = this.lockedItems.find(x => x.id == product.id);
                    if (locked) {
                        locked.qty++;
                        this.applyCouponByCode();
                        this.saveState();
                        return;
                    }
                }
                // Otherwise add to cart
                const existing = this.cart.find(x => x.id == product.id);
                if (existing) {
                    existing.qty++;
                } else {
                    this.cart.push({
                        id: parseInt(product.id),
                        name: product.name,
                        price: parseFloat(product.price),
                        qty: 1
                    });
                }
                this.applyCouponByCode();
                this.saveState();
            },

            updateQty(index, change) {
                this.cart[index].qty += change;
                if (this.cart[index].qty <= 0) {
                    this.cart.splice(index, 1);
                }
                this.applyCouponByCode();
                this.saveState();
            },

            increaseLockedItem(idx) {
                this.lockedItems[idx].qty++;
                this.applyCouponByCode();
                this.saveState();
            },

            clearCart() {
                this.cart = [];
                this.applyCouponByCode();
                this.saveState();
            },

            // ── Actions: New Order ──
            doPayLater() {
                if (!this.canSubmit) return;
                this.isProcessing = true;
                this._placeNewOrder().then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        this.printKotTicket(data.kot_items, data.order_number || data.order_id);
                        this.resetAfterOrder();
                    } else {
                        alert(data.message || 'Error');
                    }
                });
            },

            doPayNow() {
                if (!this.canSubmit) return;
                this.isProcessing = true;
                this._placeNewOrder().then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        // First print KOT
                        this.printKotTicket(data.kot_items, data.order_number || data.order_id);
                        // Then open payment modal
                        this.activeOrderId = data.order_id;
                        this.activeOrderNumber = data.order_number;
                        this.payTotal = this.grandTotal;
                        this.payGiven = this.grandTotal;
                        this.payMethod = 'cash';
                        this.showPayment = true;
                    } else {
                        alert(data.message || 'Error');
                    }
                });
            },

            _placeNewOrder() {
                return fetch('/restpo/pos/api/order', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        order_type: 'dining',
                        table_id: this.selectedTableId,
                        waiter_id: this.selectedWaiterId || null,
                        items: this.cart.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty })),
                        coupon_code: this.selectedCouponCode || null,
                        coupon_discount: this.couponDiscountAmount,
                        notes: ''
                    })
                }).then(r => r.json());
            },

            // ── Actions: Resume Pending Order ──
            doPrintKotResume() {
                if (!this.hasNewItems) return;
                this.isProcessing = true;

                // Build combined items (locked with new qty + brand new items)
                const allItems = [
                    ...this.lockedItems.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty })),
                    ...this.cart.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty }))
                ];

                fetch('/restpo/pos/api/add-items', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: this.activeOrderId, items: allItems })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        // Now print KOT for delta items
                        fetch('/restpo/pos/api/print-kot', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ order_id: this.activeOrderId })
                        })
                        .then(r => r.json())
                        .then(kotData => {
                            this.isProcessing = false;
                            if (kotData.kot_items && kotData.kot_items.length > 0) {
                                this.printKotTicket(kotData.kot_items, this.activeOrderNumber || this.activeOrderId, kotData.floor_name);
                            }
                            this.resetAfterOrder();
                        });
                    } else {
                        this.isProcessing = false;
                        alert(data.message || 'Error adding items');
                    }
                });
            },

            doPayPending() {
                // First save any new items
                if (this.hasNewItems) {
                    const allItems = [
                        ...this.lockedItems.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty })),
                        ...this.cart.map(i => ({ id: i.id, name: i.name, price: i.price, qty: i.qty }))
                    ];
                    fetch('/restpo/pos/api/add-items', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ order_id: this.activeOrderId, items: allItems })
                    })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            this.payTotal = data.new_total;
                            this.payGiven = data.new_total;
                            this.payMethod = 'cash';
                            this.showPayment = true;
                        }
                    });
                } else {
                    // No new items, just pay the existing total
                    const order = this.activeOrders.find(o => o.id == this.activeOrderId);
                    this.payTotal = parseFloat(order ? order.total : this.grandTotal);
                    this.payGiven = this.payTotal;
                    this.payMethod = 'cash';
                    this.showPayment = true;
                }
            },

            payExistingOrder(order) {
                this.activeOrderId = order.id;
                this.activeOrderNumber = order.order_number;
                this.selectedTableId = order.table_id;
                this.selectedTableName = order.table_name || '';
                this.payTotal = parseFloat(order.total);
                this.payGiven = this.payTotal;
                this.payMethod = 'cash';
                this.showPayment = true;
            },

            doVoidOrder() {
                if (!confirm('Are you sure you want to void this order? This cannot be undone.')) return;
                this.isProcessing = true;
                fetch('/restpo/pos/api/void', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: this.activeOrderId })
                })
                .then(r => r.json())
                .then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        this.resetAfterOrder();
                    } else {
                        alert(data.message);
                    }
                });
            },

            // ── Payment Execution ──
            executePayment() {
                this.isProcessing = true;
                fetch('/restpo/pos/api/pay', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        order_id: this.activeOrderId,
                        payment_method: this.payMethod,
                        given_amount: this.payMethod === 'cash' ? this.payGiven : this.payTotal
                    })
                })
                .then(r => r.json())
                .then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        this.showPayment = false;
                        if (data.invoice) {
                            this.printInvoice(data.invoice);
                        }
                        this.resetAfterOrder();
                    } else {
                        alert(data.message);
                    }
                });
            },

            acceptWaiterOrder(orderId) {
                fetch('/restpo/pos/api/accept', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: orderId })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        this.fetchData();
                        if (data.kot_items && data.kot_items.length > 0) {
                            const oldTableName = this.selectedTableName;
                            const oldWaiterId = this.selectedWaiterId;
                            this.selectedTableName = data.table_name || '—';
                            this.selectedWaiterId = data.waiter_id || '';
                            
                            this.printKotTicket(data.kot_items, data.order_number || orderId, data.floor_name);
                            
                            this.selectedTableName = oldTableName;
                            this.selectedWaiterId = oldWaiterId;
                        }
                    } else {
                        alert(data.message);
                    }
                });
            },

            acceptQrOrder(orderId) {
                const isWaiterOrder = this.currentQrOrder && this.currentQrOrder.waiter_id;
                if (!isWaiterOrder && !this.popupWaiterId) {
                    alert('Please select a waiter first.');
                    return;
                }
                this.isProcessing = true;
                const reqBody = { order_id: orderId };
                if (!isWaiterOrder) {
                    reqBody.waiter_id = this.popupWaiterId;
                }
                fetch('/restpo/pos/api/accept', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(reqBody)
                })
                .then(r => r.json())
                .then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        const assignedWaiterId = isWaiterOrder ? data.waiter_id : this.popupWaiterId;
                        this.showQrPopup = false;
                        this.currentQrOrder = null;
                        this.popupWaiterId = '';
                        this.fetchData();
                        
                        if (data.kot_items && data.kot_items.length > 0) {
                            const oldTableName = this.selectedTableName;
                            const oldWaiterId = this.selectedWaiterId;
                            this.selectedTableName = data.table_name || '—';
                            this.selectedWaiterId = assignedWaiterId || '';
                            
                            this.printKotTicket(data.kot_items, data.order_number || orderId, data.floor_name);
                            
                            this.selectedTableName = oldTableName;
                            this.selectedWaiterId = oldWaiterId;
                        }
                    } else {
                        alert(data.message || 'Error');
                    }
                })
                .catch(() => {
                    this.isProcessing = false;
                    alert('Network error');
                });
            },

            rejectQrOrder(orderId) {
                if (!confirm('Are you sure you want to reject and void this QR order?')) return;
                this.isProcessing = true;
                fetch('/restpo/pos/api/void', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: orderId })
                })
                .then(r => r.json())
                .then(data => {
                    this.isProcessing = false;
                    if (data.success) {
                        this.showQrPopup = false;
                        this.currentQrOrder = null;
                        this.popupWaiterId = '';
                        this.fetchData();
                    } else {
                        alert(data.message);
                    }
                })
                .catch(() => {
                    this.isProcessing = false;
                    alert('Network error');
                });
            },

            dismissQrPopup() {
                if (this.currentQrOrder) {
                    this.dismissedQrIds.push(this.currentQrOrder.id);
                }
                this.showQrPopup = false;
                this.currentQrOrder = null;
                this.popupWaiterId = '';
                this.$nextTick(() => {
                    this.checkPendingOrdersQueue();
                });
            },

            // ── Reset ──
            resetAfterOrder() {
                this.cart = [];
                this.lockedItems = [];
                this.activeOrderId = null;
                this.activeOrderNumber = null;
                this.isResuming = false;
                this.selectedTableId = null;
                this.selectedTableName = '';
                this.selectedWaiterId = '';
                this.selectedCouponCode = '';
                this.selectedCoupon = null;
                this.couponMessage = '';
                this.couponSuccess = false;
                this.mode = 'tables';
                this.searchQuery = '';
                this.activeCategory = null;
                this.clearSavedState();
                this.fetchData();
            },

            isWaiterActive(id) {
                if (this.waiterSelectTarget === 'cart') {
                    return this.selectedWaiterId == id;
                } else {
                    return this.popupWaiterId == id;
                }
            },

            selectWaiterFromModal(id) {
                if (this.waiterSelectTarget === 'cart') {
                    this.selectedWaiterId = id;
                } else {
                    this.popupWaiterId = id;
                }
                this.showWaiterSelectModal = false;
                this.waiterSearchQuery = '';
            },

            playChime() {
                try {
                    const ctx = new (window.AudioContext || window.webkitAudioContext)();
                    // Tone 1: C5 (523.25 Hz)
                    const osc1 = ctx.createOscillator();
                    const gain1 = ctx.createGain();
                    osc1.type = 'sine';
                    osc1.frequency.value = 523.25;
                    osc1.connect(gain1);
                    gain1.connect(ctx.destination);
                    gain1.gain.setValueAtTime(0.1, ctx.currentTime);
                    gain1.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.15);
                    osc1.start(ctx.currentTime);
                    osc1.stop(ctx.currentTime + 0.15);

                    // Tone 2: E5 (659.25 Hz) at 0.12s delay
                    const osc2 = ctx.createOscillator();
                    const gain2 = ctx.createGain();
                    osc2.type = 'sine';
                    osc2.frequency.value = 659.25;
                    osc2.connect(gain2);
                    gain2.connect(ctx.destination);
                    gain2.gain.setValueAtTime(0.1, ctx.currentTime + 0.12);
                    gain2.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.32);
                    osc2.start(ctx.currentTime + 0.12);
                    osc2.stop(ctx.currentTime + 0.32);
                } catch (e) {
                    console.error("Audio Context error: ", e);
                }
            },

            updateOrderCoupon(orderId, couponCode) {
                fetch('/restpo/pos/api/assign-coupon', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ order_id: orderId, coupon_code: couponCode })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        this.fetchData();
                    } else {
                        alert(data.message || 'Error assigning coupon');
                    }
                });
            },

            applyCouponByCode() {
                if (!this.selectedCouponCode) {
                    this.selectedCoupon = null;
                    this.couponMessage = '';
                    this.couponSuccess = false;
                    return;
                }
                const coupon = this.coupons.find(c => c.code === this.selectedCouponCode);
                if (!coupon) {
                    this.selectedCoupon = null;
                    this.couponMessage = 'Coupon not found';
                    this.couponSuccess = false;
                    return;
                }

                let isEligible = false;
                const allItems = [
                    ...this.lockedItems.map(i => ({ id: i.id, category_id: this.products.find(p => p.id == i.id)?.category_id })),
                    ...this.cart.map(i => ({ id: i.id, category_id: this.products.find(p => p.id == i.id)?.category_id }))
                ];

                if (coupon.product_id) {
                    isEligible = allItems.some(item => item.id == coupon.product_id);
                } else if (coupon.category_id) {
                    isEligible = allItems.some(item => item.category_id == coupon.category_id);
                } else {
                    isEligible = true;
                }

                if (!isEligible) {
                    this.selectedCoupon = null;
                    this.couponMessage = 'Coupon not applicable to items in cart';
                    this.couponSuccess = false;
                    return;
                }

                this.selectedCoupon = coupon;
                this.couponMessage = 'Coupon applied successfully!';
                this.couponSuccess = true;
            },

            reprintKot(order) {
                const kotItems = (order.items || []).map(i => ({
                    name: i.name,
                    qty: i.quantity,
                    label: ''
                }));
                const oldTableName = this.selectedTableName;
                const oldWaiterId = this.selectedWaiterId;
                
                this.selectedTableName = order.table_name || '—';
                this.selectedWaiterId = order.waiter_id || '';
                
                this.printKotTicket(kotItems, order.order_number || order.id, order.floor_name);
                
                this.selectedTableName = oldTableName;
                this.selectedWaiterId = oldWaiterId;
            },

            printCurrentResumedUnpaidBill() {
                const order = this.activeOrders.find(o => o.id == this.activeOrderId);
                if (order) {
                    this.printUnpaidBill(order);
                } else {
                    let floor_name = '';
                    if (this.selectedTableId) {
                        const tbl = this.tables.find(t => t.id == this.selectedTableId);
                        const fl = tbl ? this.floors.find(f => f.id == tbl.floor_id) : null;
                        floor_name = fl ? fl.name : '';
                    }
                    const fallbackOrder = {
                        id: this.activeOrderId,
                        order_number: this.activeOrderNumber,
                        table_name: this.selectedTableName,
                        floor_name: floor_name,
                        items: this.lockedItems.map(i => ({
                            name: i.name,
                            price: i.price,
                            quantity: i.qty
                        })),
                        subtotal: this.grandSubtotal,
                        tax: this.taxAmount,
                        discount: this.discountAmount,
                        total: this.grandTotal
                    };
                    this.printUnpaidBill(fallbackOrder);
                }
            },

            printUnpaidBill(order) {
                const sym = this.currency;
                let itemsHtml = '';
                (order.items || []).forEach(i => {
                    const sub = (parseFloat(i.price) * parseInt(i.quantity)).toFixed(2);
                    itemsHtml += `<div style="display:flex; justify-content:space-between; padding:2px 0; font-size:11px; font-weight:bold;"><span><b>${i.quantity}x ${i.name}</b></span><span><b>${sym}${sub}</b></span></div>`;
                });
                const discountLabel = order.coupon_code ? `Discount (${order.coupon_code})` : 'Discount';
                const discountLine = parseFloat(order.discount) > 0 ? `<div style="display:flex; justify-content:space-between; font-size:11px; font-weight:bold;"><span><b>${discountLabel}</b></span><span><b>-${sym}${parseFloat(order.discount).toFixed(2)}</b></span></div>` : '';
                let logoHtml = this.restaurantLogo ? `<center><img src="/restpo/${this.restaurantLogo}" style="max-height:55px; margin-bottom:8px; border-radius:4px; display:inline-block;" alt="logo"></center>` : '';
                const html = `
                    <div style="font-family: 'Courier New', monospace; font-size: 12px; width: 100%; box-sizing: border-box; padding: 15px; color: #000; background: #fff;">
                        <div style="text-align:center; margin-bottom:8px;">
                            ${logoHtml}
                            <div style="font-size:16px; font-weight:bold;"><b>${this.restaurantName}</b></div>
                            <div style="font-size:11px; font-weight:bold; margin-top:2px;"><b>${this.restaurantAddress || ''}</b></div>
                            <div style="font-size:11px; font-weight:bold; margin-top:2px;"><b>Phone: ${this.restaurantPhone || ''}</b></div>
                            <div style="font-size:13px; font-weight:bold; color:red; margin-top:6px; border:1px solid red; padding:2px; display:inline-block;"><b>* UNPAID DRAFT *</b></div>
                        </div>
                        <div style="border-top: 1px dashed #000; padding-top:6px; margin-bottom:6px; font-size:11px; font-weight:bold;">
                            <div><b>Order #: ${order.order_number || order.id}</b></div>
                            <div><b>Table: ${order.table_name || '—'}${order.floor_name ? ' (' + order.floor_name + ')' : ''}</b></div>
                            <div><b>Waiter: ${order.waiter_name || '—'}</b></div>
                            <div><b>Date: ${order.created_at || ''}</b></div>
                        </div>
                        <div style="border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 6px 0; margin-bottom:6px;">
                            ${itemsHtml}
                        </div>
                        <div style="font-size:11px; font-weight:bold;">
                            <div style="display:flex; justify-content:space-between;"><span><b>Subtotal</b></span><span><b>${sym}${parseFloat(order.subtotal).toFixed(2)}</b></span></div>
                            ${discountLine}
                            <div style="display:flex; justify-content:space-between;"><span><b>Tax</b></span><span><b>${sym}${parseFloat(order.tax).toFixed(2)}</b></span></div>
                            <div style="display:flex; justify-content:space-between; font-weight:bold; font-size:14px; margin-top:4px; padding-top:4px; border-top:1px dashed #000;"><span><b>TOTAL</b></span><span><b>${sym}${parseFloat(order.total).toFixed(2)}</b></span></div>
                        </div>
                        <div style="text-align:center; margin-top:12px; font-size:10px; color:#000;">
                            <div style="font-weight: bold; font-size:14px; color:red; border:2px solid red; padding:4px; display:inline-block; margin-bottom:6px;"><b>NOT PAID</b></div>
                            <div style="margin-top:4px; font-weight:bold;"><b>Please present this draft to Cashier.</b></div>
                            <div style="margin-top:4px; font-size:9px; color:#000; font-weight:bold;"><b>Powered By RESTPO</b></div>
                        </div>
                    </div>
                `;
                
                if (this.popupBill === 'preview') {
                    this.previewHtml = html;
                    this.previewType = 'bill';
                    this.showPrintPreview = true;
                } else {
                    this._doPrint(html, 'bill');
                }
            },

            // ── KOT Print ──
            printKotTicket(items, orderId, floorName = null) {
                if (!items || items.length === 0) return;
                const time = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
                const date = new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                const waiterObj = this.waiters.find(w => w.id == this.selectedWaiterId);
                const waiterName = waiterObj ? waiterObj.name : '—';
                let logoHtml = this.restaurantLogo ? `<center><img src="/restpo/${this.restaurantLogo}" style="max-height:45px; margin-bottom:8px; border-radius:4px; display:inline-block;" alt="logo"></center>` : '';
                
                let resolvedFloorName = floorName;
                if (!resolvedFloorName) {
                    if (this.selectedTableId) {
                        const tbl = this.tables.find(t => t.id == this.selectedTableId);
                        const fl = tbl ? this.floors.find(f => f.id == tbl.floor_id) : null;
                        resolvedFloorName = fl ? fl.name : null;
                    }
                }
                if (!resolvedFloorName) {
                    const order = this.activeOrders.find(o => o.id == orderId || o.order_number == orderId);
                    if (order) {
                        resolvedFloorName = order.floor_name || null;
                    }
                }
                const floorStr = resolvedFloorName ? ` (${resolvedFloorName})` : '';

                let html = `
                    <div style="font-family: 'Courier New', monospace; font-size: 12px; width: 100%; box-sizing: border-box; padding: 15px; color: #000; background: #fff;">
                        <div style="text-align:center; border-bottom: 2px dashed #000; padding-bottom: 8px; margin-bottom: 8px;">
                            ${logoHtml}
                            <div style="font-size:16px; font-weight:bold; letter-spacing:2px;"><b>KITCHEN ORDER</b></div>
                            <div style="font-size:12px; font-weight:bold; margin-top:2px;"><b>${this.restaurantName}</b></div>
                            <div style="font-size:10px; font-weight:bold; margin-top:2px;"><b>${this.restaurantAddress || ''}</b></div>
                        </div>
                        <div style="display:flex; justify-content:space-between; font-size:11px; margin-bottom:4px; font-weight:bold;">
                            <span><b>Table: ${this.selectedTableName || '—'}${floorStr}</b></span>
                            <span><b>Order #${orderId}</b></span>
                        </div>
                        <div style="display:flex; justify-content:space-between; font-size:11px; margin-bottom:8px; font-weight:bold;">
                            <span><b>Waiter: ${waiterName}</b></span>
                            <span><b>${time}</b></span>
                        </div>
                        <div style="border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 8px 0; margin-bottom: 8px;">
                `;
                items.forEach(item => {
                    html += `<div style="display:flex; justify-content:space-between; padding:3px 0; font-size:12px; font-weight:bold;"><span><b>${item.qty}x ${item.name}</b></span></div>`;
                });
                html += `
                        </div>
                        <div style="text-align:center; font-size:10px; color:#000; font-weight:bold;"><b>Printed: ${date} ${time}</b></div>
                        <div style="text-align:center; font-size:9px; color:#000; margin-top:4px; font-weight:bold;"><b>Powered By RESTPO</b></div>
                    </div>
                `;
                
                if (this.popupKot === 'preview') {
                    this.previewHtml = html;
                    this.previewType = 'kot';
                    this.showPrintPreview = true;
                } else {
                    this._doPrint(html, 'kot');
                }
            },

            // ── Invoice Print ──
            printInvoice(inv) {
                const sym = this.currency;
                let itemsHtml = '';
                (inv.items || []).forEach(i => {
                    const sub = (parseFloat(i.price) * parseInt(i.quantity)).toFixed(2);
                    itemsHtml += `<div style="display:flex; justify-content:space-between; padding:2px 0; font-size:11px; font-weight:bold;"><span><b>${i.quantity}x ${i.name}</b></span><span><b>${sym}${sub}</b></span></div>`;
                });
                const discountLabel = inv.coupon_code ? `Discount (${inv.coupon_code})` : 'Discount';
                const discountLine = parseFloat(inv.discount) > 0 ? `<div style="display:flex; justify-content:space-between; font-size:11px; font-weight:bold;"><span><b>${discountLabel}</b></span><span><b>-${sym}${parseFloat(inv.discount).toFixed(2)}</b></span></div>` : '';
                let logoHtml = inv.restaurant_logo ? `<center><img src="/restpo/${inv.restaurant_logo}" style="max-height:55px; margin-bottom:8px; border-radius:4px; display:inline-block;" alt="logo"></center>` : '';
                const html = `
                    <div style="font-family: 'Courier New', monospace; font-size: 12px; width: 100%; box-sizing: border-box; padding: 15px; color: #000; background: #fff;">
                        <div style="text-align:center; margin-bottom:8px;">
                            ${logoHtml}
                            <div style="font-size:16px; font-weight:bold;"><b>${inv.restaurant_name}</b></div>
                            <div style="font-size:11px; font-weight:bold; margin-top:2px;"><b>${inv.restaurant_address || ''}</b></div>
                            <div style="font-size:11px; font-weight:bold; margin-top:2px;"><b>Phone: ${inv.restaurant_phone || ''}</b></div>
                        </div>
                        <div style="border-top: 1px dashed #000; padding-top:6px; margin-bottom:6px; font-size:11px; font-weight:bold;">
                            <div><b>Order #: ${inv.order_id}</b></div>
                            <div><b>Table: ${inv.table_name || '—'}${inv.floor_name ? ' (' + inv.floor_name + ')' : ''}</b></div>
                            <div><b>Waiter: ${inv.waiter_name || '—'}</b></div>
                            <div><b>Date: ${inv.created_at || ''}</b></div>
                        </div>
                        <div style="border-top: 1px dashed #000; border-bottom: 1px dashed #000; padding: 6px 0; margin-bottom:6px;">
                            ${itemsHtml}
                        </div>
                        <div style="font-size:11px; font-weight:bold;">
                            <div style="display:flex; justify-content:space-between;"><span><b>Subtotal</b></span><span><b>${sym}${parseFloat(inv.subtotal).toFixed(2)}</b></span></div>
                            ${discountLine}
                            <div style="display:flex; justify-content:space-between;"><span><b>Tax</b></span><span><b>${sym}${parseFloat(inv.tax).toFixed(2)}</b></span></div>
                            <div style="display:flex; justify-content:space-between; font-weight:bold; font-size:14px; margin-top:4px; padding-top:4px; border-top:1px dashed #000;"><span><b>TOTAL</b></span><span><b>${sym}${parseFloat(inv.total).toFixed(2)}</b></span></div>
                        </div>
                        <div style="border-top: 1px dashed #000; margin-top:6px; padding-top:6px; font-size:11px; font-weight:bold;">
                            <div style="display:flex; justify-content:space-between;"><span><b>Paid (${inv.payment_method.charAt(0).toUpperCase() + inv.payment_method.slice(1)})</b></span><span><b>${sym}${parseFloat(inv.given_amount).toFixed(2)}</b></span></div>
                            <div style="display:flex; justify-content:space-between;"><span><b>Change</b></span><span><b>${sym}${parseFloat(inv.change_amount).toFixed(2)}</b></span></div>
                        </div>
                        <div style="text-align:center; margin-top:10px; font-size:10px; color:#000;">
                            <div style="font-weight: bold; font-size:14px;"><b>PAID</b></div>
                            <div style="margin-top:4px; font-weight:bold;"><b>Thank you! Visit again.</b></div>
                            <div style="margin-top:4px; font-size:9px; color:#000; font-weight:bold;"><b>Powered By RESTPO</b></div>
                        </div>
                    </div>
                `;
                
                if (this.popupReceipt === 'preview') {
                    this.previewHtml = html;
                    this.previewType = 'receipt';
                    this.showPrintPreview = true;
                } else {
                    this._doPrint(html, 'receipt');
                }
            },

            _doPrint(html, type = 'receipt') {
                const width = this.printSize === '58mm' ? '200px' : '280px';
                const wrappedHtml = `<div style="width: ${width}; margin: 0 auto; box-sizing: border-box; font-family: sans-serif;">${html}</div>`;
                
                if (this.qzConnected) {
                    let printerName = (type === 'kot') ? this.qzKitchenPrinter : this.qzCashierPrinter;
                    
                    if (printerName) {
                        qz.printers.find(printerName).then((foundPrinter) => {
                            let config = qz.configs.create(foundPrinter, {
                                margins: 0,
                                scaleContent: false
                            });
                            
                            let data = [];
                            
                            // Cash Drawer Kick (Only for Paid Bill if enabled)
                            if (type === 'receipt' && this.qzEnableCashDrawer) {
                                // Standard ESC/POS pulse command
                                data.push({ type: 'raw', format: 'command', flavor: 'escpos', data: '\x1B\x70\x00\x19\xFA' });
                            }
                            
                            // Print HTML
                            data.push({ type: 'pixel', format: 'html', flavor: 'plain', data: wrappedHtml });
                            
                            return qz.print(config, data);
                        }).catch((e) => {
                            console.error("QZ Tray Print Error:", e);
                            this._fallbackPrint(wrappedHtml);
                        });
                        return;
                    }
                }
                
                this._fallbackPrint(wrappedHtml);
            },
            
            _fallbackPrint(wrappedHtml) {
                const el = document.getElementById('print-area');
                el.innerHTML = wrappedHtml;
                el.style.display = 'block';
                setTimeout(() => {
                    window.print();
                    setTimeout(() => { el.style.display = 'none'; }, 500);
                }, 200);
            }
        }));
    });
    </script>
    <!-- Session Error Toast -->
    <?php if(isset($_GET['error'])): ?>
    <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 5000)" class="fixed bottom-6 right-6 z-50 flex items-center gap-3 px-4 py-3 rounded-xl shadow-xl text-sm font-medium border animate-bounce" style="background: #ef4444; color: white; border-color: rgba(239,68,68,0.3)">
        <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($_GET['error']); ?>
    </div>
    <?php endif; ?>
</body>
</html>
