<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Waiter Terminal - RestiPO</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>window.BASE_URL = '<?= BASE_URL ?>';</script>
    <link href="https://fonts.googleapis.com/css2?family=Outfit: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: 'Outfit', sans-serif; margin: 0; padding: 0; box-sizing: border-box; }
        
        :root {
            --bg-base: #060913;
            --bg-panel: rgba(255, 255, 255, 0.02);
            --bg-panel-hover: rgba(255, 255, 255, 0.05);
            --bg-header: #090d1b;
            --border-color: rgba(255, 255, 255, 0.06);
            --border-hover: rgba(139, 92, 246, 0.35);
            --text-1: #f8fafc;
            --text-2: #94a3b8;
            --text-3: #475569;
            --accent: #8b5cf6;
            --accent-grad: linear-gradient(135deg, #8b5cf6, #6366f1);
            --accent-soft: rgba(139, 92, 246, 0.12);
            --accent-shadow: rgba(139, 92, 246, 0.25);
            --card-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5);
            --input-bg: rgba(255, 255, 255, 0.02);
        }

        .light-theme {
            --bg-base: #f1f5f9;
            --bg-panel: #ffffff;
            --bg-panel-hover: #f8fafc;
            --bg-header: #ffffff;
            --border-color: rgba(15, 23, 42, 0.08);
            --border-hover: rgba(79, 70, 229, 0.4);
            --text-1: #0f172a;
            --text-2: #475569;
            --text-3: #94a3b8;
            --accent: #4f46e5;
            --accent-grad: linear-gradient(135deg, #6366f1, #4f46e5);
            --accent-soft: rgba(79, 70, 229, 0.08);
            --accent-shadow: rgba(79, 70, 229, 0.15);
            --card-shadow: 0 8px 30px rgba(0, 0, 0, 0.04);
            --input-bg: #ffffff;
        }

        body { 
            background: var(--bg-base) !important; 
            color: var(--text-1) !important; 
            transition: background-color 0.3s ease, color 0.3s ease; 
        }

        header {
            background: var(--bg-header) !important;
            border-bottom: 1px solid var(--border-color) !important;
            transition: background-color 0.3s ease, border-color 0.3s ease;
        }

        /* Glass Panel */
        .glass-panel { 
            background: var(--bg-panel) !important; 
            backdrop-filter: blur(16px); 
            border: 1px solid var(--border-color) !important; 
            box-shadow: var(--card-shadow); 
            color: var(--text-1) !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .glass-hover:hover { 
            background: var(--bg-panel-hover) !important; 
            border-color: var(--border-hover) !important; 
            transform: translateY(-2px); 
            box-shadow: 0 12px 24px -10px var(--accent-shadow);
        }

        /* Active selection tabs */
        .active-tab { 
            background: var(--accent-grad) !important; 
            color: #ffffff !important;
            box-shadow: 0 4px 20px var(--accent-shadow); 
            border-color: transparent !important; 
        }

        .btn-gradient { 
            background: var(--accent-grad) !important; 
            color: #ffffff !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
            box-shadow: 0 4px 14px var(--accent-shadow);
        }
        .btn-gradient:hover { 
            filter: brightness(110%); 
            transform: translateY(-1px); 
            box-shadow: 0 8px 25px var(--accent-shadow); 
        }
        .btn-gradient:active {
            transform: translateY(0);
        }

        /* Dynamic Statuses */
        .pulse-green { animation: pulseGreen 2s infinite; }
        @keyframes pulseGreen { 
            0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); } 
            50% { box-shadow: 0 0 0 8px rgba(16, 185, 129, 0); } 
        }
        .pulse-gold { animation: pulseGold 2s infinite; }
        @keyframes pulseGold { 
            0%, 100% { box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.35); } 
            50% { box-shadow: 0 0 0 8px rgba(245, 158, 11, 0); } 
        }

        /* Scrollbar */
        ::-webkit-scrollbar { width: 5px; height: 5px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: var(--text-3); }

        /* Typography & layout custom colors overriders for Light Theme */
        .light-theme .text-white,
        .light-theme .text-slate-100 {
            color: #0f172a !important;
        }
        .light-theme .text-slate-300 {
            color: #334155 !important;
        }
        .light-theme .text-slate-400 {
            color: #475569 !important;
        }
        .light-theme .text-slate-500 {
            color: #64748b !important;
        }
        .light-theme .bg-[#080d1a],
        .light-theme .bg-[#0a0f1d],
        .light-theme .bg-[#090d1b] {
            background: #f8fafc !important;
            border-color: rgba(15, 23, 42, 0.06) !important;
        }
        .light-theme .border-white\/5 {
            border-color: rgba(15, 23, 42, 0.06) !important;
        }
        
        /* Dropdowns, forms and selectors styling overrides */
        select, input, textarea {
            background: var(--input-bg) !important;
            border: 1px solid var(--border-color) !important;
            color: var(--text-1) !important;
            transition: all 0.2s;
            outline: none;
        }
        select:focus, input:focus, textarea:focus {
            border-color: var(--accent) !important;
            box-shadow: 0 0 0 3px var(--accent-soft) !important;
        }
    </style>
</head>
<body class="h-screen overflow-hidden flex flex-col relative" x-data="waiterApp" :class="theme === 'light' ? 'light-theme' : ''">

    <!-- Top floating notifications -->
    <div class="fixed top-4 right-4 z-50 space-y-3 pointer-events-auto max-w-sm w-full">
        <template x-for="notif in notifications" :key="notif.id">
            <div class="glass-panel p-4 rounded-2xl shadow-2xl flex items-center gap-4 animate-slide-in border-l-4 border-emerald-500"
                 style="background: rgba(10, 20, 35, 0.92); border-left-color: #10b981;">
                <div class="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center text-emerald-400 animate-bounce">
                    <i class="fas fa-bell animate-swing"></i>
                </div>
                <div class="flex-1">
                    <div class="text-sm font-bold text-white">Order Ready!</div>
                    <div class="text-xs text-slate-400 mt-0.5">Table <span x-text="notif.tableName" class="font-semibold text-emerald-400"></span> is ready to serve.</div>
                </div>
                <button @click="removeNotification(notif.id)" class="text-slate-500 hover:text-slate-300 text-xs">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </template>
    </div>

    <!-- Header -->
    <header class="h-16 flex items-center justify-between px-4 md:px-6 flex-shrink-0 relative z-30 bg-[#090d1b]" style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
        <div class="flex items-center gap-3">
            <div class="w-8 h-8 md:w-9 md:h-9 rounded-xl bg-gradient-to-tr from-purple-600 to-indigo-600 flex items-center justify-center shadow-lg shadow-purple-500/20">
                <i class="fas fa-concierge-bell text-white text-xs md:text-sm"></i>
            </div>
            <div>
                <h1 class="text-sm md:text-base font-extrabold text-white leading-none tracking-tight">Waiter Terminal</h1>
                <p class="text-[9px] md:text-[10px] text-purple-400 font-semibold mt-1">Real-time KDS Integrated</p>
            </div>
        </div>

        <div class="flex items-center gap-2 md:gap-3">
            <!-- Theme Toggle -->
            <button @click="toggleTheme()" class="glass-panel p-2.5 rounded-xl hover:bg-white/5 transition text-slate-300">
                <i class="fas" :class="theme === 'dark' ? 'fa-sun' : 'fa-moon'"></i>
            </button>

            <!-- Audio Chime controller -->
            <button @click="toggleSound()" class="px-2.5 md:px-3.5 py-2 rounded-xl text-[10px] md:text-xs font-bold border transition duration-200 flex items-center gap-1.5"
                    :class="audioEnabled ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/25 pulse-green' : 'bg-rose-500/10 text-rose-400 border-rose-500/25'">
                <i class="fas" :class="audioEnabled ? 'fa-volume-high' : 'fa-volume-xmark'"></i>
                <span x-text="audioEnabled ? 'Alarms On' : 'Muted'" class="hidden sm:inline"></span>
            </button>

            <!-- Active Orders status badge -->
            <button @click="showMyOrders = true" class="relative glass-panel p-2.5 rounded-xl hover:bg-white/5 transition">
                <i class="fas fa-receipt text-slate-300"></i>
                <span x-show="myOrders.length > 0" class="absolute -top-1.5 -right-1.5 bg-indigo-500 text-white text-[9px] font-black rounded-full h-5 w-5 flex items-center justify-center shadow-lg shadow-indigo-500/30" x-text="myOrders.length"></span>
            </button>

            <a href="<?= BASE_URL ?>/logout" class="glass-panel hover:bg-red-500/10 hover:border-red-500/20 text-red-400 px-3 md:px-4 py-2 rounded-xl text-[10px] md:text-xs font-bold transition">Sign Out</a>
        </div>
    </header>

    <!-- Main Working Grid -->
    <div class="flex-1 flex overflow-hidden relative z-25">
        
        <!-- Left panel: Tables Selection & Product Categories Menu -->
        <div class="flex-1 flex flex-col bg-[#080d1a] relative overflow-hidden">
            <div class="absolute -top-40 -left-40 w-96 h-96 rounded-full bg-purple-500/5 blur-3xl pointer-events-none"></div>
            
            <!-- Dashboard View (When no table is selected) -->
            <div x-show="!selectedTableId" class="flex-1 flex flex-col overflow-hidden relative z-10">
                <div class="flex-1 grid grid-cols-1 lg:grid-cols-3 gap-6 p-4 md:p-6 overflow-y-auto">
                    
                    <!-- Left: Table Selection Grid -->
                    <div class="lg:col-span-2 space-y-6">
                        <h2 class="text-base md:text-lg font-bold text-white tracking-tight flex items-center gap-2">
                            <i class="fas fa-border-all text-purple-400"></i> Select Dining Table
                        </h2>
                        
                        <template x-for="floor in floors" :key="floor.id">
                            <div class="glass-panel p-4 md:p-5 rounded-2xl space-y-4">
                                <div class="flex items-center gap-2 border-b border-white/5 pb-3">
                                    <i class="fas fa-layer-group text-slate-500 text-xs"></i>
                                    <h4 class="text-[10px] md:text-xs font-extrabold text-slate-400 uppercase tracking-widest" x-text="floor.name"></h4>
                                </div>
                                <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-3">
                                    <template x-for="table in tables.filter(t => t.floor_id === floor.id)" :key="table.id">
                                        <button @click="selectTable(table)" 
                                            :class="table.status === 'occupied' ? 'border-amber-500/30 bg-amber-500/[0.02] cursor-not-allowed pulse-gold opacity-95' : 'glass-panel hover:bg-white/5 border border-emerald-500/10 hover:border-purple-500'"
                                            :disabled="table.status === 'occupied'"
                                            class="rounded-2xl p-4 text-center transition-all duration-300 flex flex-col items-center justify-center h-24 relative group">
                                            
                                            <!-- Status Dot Badge -->
                                            <div class="absolute top-2.5 left-3 flex items-center gap-1.5">
                                                <span class="w-1.5 h-1.5 rounded-full" :class="table.status === 'occupied' ? 'bg-amber-500 animate-pulse' : 'bg-emerald-500'"></span>
                                                <span class="text-[9px] font-bold tracking-wider uppercase" :class="table.status === 'occupied' ? 'text-amber-400' : 'text-emerald-400'" x-text="table.status === 'occupied' ? 'Occupied' : 'Free'"></span>
                                            </div>
                                            
                                            <span class="text-xl font-extrabold tracking-tight text-white mt-2 group-hover:scale-105 transition-transform" x-text="table.name"></span>
                                            <span class="text-[10px] text-slate-500 mt-1 flex items-center gap-1"><i class="fas fa-users text-[8px]"></i> <span x-text="table.capacity"></span> seats</span>
                                        </button>
                                    </template>
                                </div>
                            </div>
                        </template>
                        
                        <div x-show="floors.length === 0" class="glass-panel p-10 rounded-2xl text-center space-y-3">
                            <i class="fas fa-layer-group text-4xl text-slate-700"></i>
                            <p class="text-slate-500 text-sm">No floors or tables assigned to your cashier branch.</p>
                        </div>
                    </div>

                    <!-- Right: Real-time Kitchen Prep Progress -->
                    <div class="space-y-4 lg:border-l lg:border-white/5 lg:pl-6">
                        <h2 class="text-base md:text-lg font-bold text-white tracking-tight flex items-center gap-2">
                            <i class="fas fa-fire-burner text-purple-400"></i> Kitchen Live Status
                        </h2>
                        
                        <div class="space-y-3 max-h-[70vh] overflow-y-auto pr-1">
                            <template x-for="order in myOrders" :key="order.id">
                                <div class="glass-panel p-4 rounded-2xl space-y-3 border"
                                     :class="order.kitchen_status === 'ready' ? 'border-emerald-500/30 bg-emerald-500/5' : 'border-white/5'">
                                    
                                    <div class="flex justify-between items-start">
                                        <div>
                                            <h4 class="font-extrabold text-white flex items-center gap-1.5 text-xs md:text-sm">
                                                Table <span x-text="order.table_name" class="text-purple-400"></span>
                                            </h4>
                                            <div class="text-[9px] md:text-[10px] text-slate-500 mt-1">Order #<span x-text="order.order_number || order.id"></span> • <span x-text="order.items.length"></span> items
                                                <span x-show="order.waiter_name" class="text-slate-400"> • Waiter: <span x-text="order.waiter_name"></span></span>
                                                <span x-show="!order.waiter_id" class="text-emerald-400 font-bold"> • QR Menu Order</span>
                                            </div>
                                        </div>
                                        
                                        <!-- Realtime Badge status -->
                                        <span class="px-2 py-0.5 rounded-lg text-[8px] md:text-[9px] font-black uppercase tracking-wider border shadow"
                                              :class="{
                                                  'bg-slate-500/10 text-slate-400 border-slate-500/20': order.status === 'pending',
                                                  'bg-blue-500/10 text-blue-400 border-blue-500/20': order.status === 'accepted' && order.kitchen_status === 'queued',
                                                  'bg-amber-500/10 text-amber-400 border-amber-500/20': order.kitchen_status === 'preparing',
                                                  'bg-emerald-500/10 text-emerald-400 border-emerald-500/20 animate-pulse border-emerald-500/30': order.kitchen_status === 'ready'
                                              }">
                                            <span x-text="order.status === 'pending' ? 'Unaccepted' : (order.kitchen_status === 'queued' ? 'Queued' : (order.kitchen_status === 'preparing' ? 'Cooking' : 'Ready!'))"></span>
                                        </span>
                                    </div>

                                    <!-- Segmented Progress Bar -->
                                    <div class="space-y-1.5">
                                        <div class="flex justify-between text-[8px] md:text-[9px] font-bold text-slate-500">
                                            <span>Accepted</span>
                                            <span>In Kitchen</span>
                                            <span>Ready</span>
                                        </div>
                                        <div class="h-2 rounded-full bg-white/5 flex overflow-hidden border border-white/5 p-0.5">
                                            <div class="h-full rounded-full transition-all duration-500"
                                                 :class="{
                                                     'w-[20%] bg-slate-400': order.status === 'pending',
                                                     'w-[40%] bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.3)]': order.status === 'accepted' && order.kitchen_status === 'queued',
                                                     'w-[70%] bg-amber-500 shadow-[0_0_10px_rgba(245,158,11,0.3)]': order.kitchen_status === 'preparing',
                                                     'w-[100%] bg-emerald-500 shadow-[0_0_10px_rgba(16,185,129,0.5)] animate-pulse': order.kitchen_status === 'ready'
                                                 }">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Items loop inside card -->
                                    <div class="border-y border-white/5 py-2.5 text-[10px] md:text-[11px] text-slate-400 space-y-1">
                                        <template x-for="item in order.items">
                                            <div class="flex justify-between font-medium">
                                                <span><span x-text="item.quantity"></span>x <span x-text="item.name"></span></span>
                                                <span x-show="item.kitchen_note" class="text-[8px] md:text-[9px] italic text-amber-400" x-text="'(' + item.kitchen_note + ')'"></span>
                                            </div>
                                        </template>
                                    </div>

                                    <!-- Waiter Delivery Action -->
                                    <div x-show="order.kitchen_status === 'ready'" class="pt-1.5 flex justify-end">
                                        <button @click="markAsDelivered(order.id)" 
                                                class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-[10px] md:text-xs font-bold transition flex items-center gap-1.5 shadow-md shadow-emerald-950/20 active:scale-95">
                                            <i class="fas fa-check-double"></i> Mark Served
                                        </button>
                                    </div>
                                </div>
                            </template>
                            
                            <div x-show="myOrders.length === 0" class="text-center py-12 text-slate-600 glass-panel rounded-2xl">
                                <i class="fas fa-hourglass text-2xl mb-2"></i>
                                <p class="text-xs">No active kitchen orders placed.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Menu / Ordering View (When a table is selected) -->
            <div x-show="selectedTableId" class="flex-1 flex flex-col overflow-hidden relative z-10" style="display: none;">
                <!-- Category Select Tabbar -->
                <div class="p-3 md:p-4 border-b border-white/5 bg-slate-900/40 flex gap-2 overflow-x-auto">
                    <button @click="activeCategory = null" 
                            :class="!activeCategory ? 'active-tab text-white' : 'glass-panel text-slate-400 hover:text-white'" 
                            class="px-4 md:px-5 py-2.5 rounded-xl font-bold text-[10px] md:text-xs whitespace-nowrap transition border border-white/5">
                        <i class="fas fa-utensils mr-1.5"></i> All Items
                    </button>
                    <template x-for="cat in categories" :key="cat.id">
                        <button @click="activeCategory = cat.id" 
                                :class="activeCategory === cat.id ? 'active-tab text-white' : 'glass-panel text-slate-400 hover:text-white'" 
                                class="px-4 md:px-5 py-2.5 rounded-xl font-bold text-[10px] md:text-xs whitespace-nowrap transition border border-white/5" 
                                x-text="cat.name">
                        </button>
                    </template>
                </div>
                
                <!-- Products list -->
                <div class="flex-1 p-4 md:p-6 overflow-y-auto">
                    <div class="flex justify-between items-center glass-panel p-3.5 md:p-4 rounded-2xl mb-6 border border-purple-500/10 animate-fade-in" style="background: rgba(139,92,246,0.02);">
                        <div class="flex items-center gap-3">
                            <div class="w-8 h-8 md:w-10 md:h-10 rounded-xl bg-purple-500/10 border border-purple-500/25 flex items-center justify-center text-purple-400">
                                <i class="fas fa-chair text-xs md:text-sm"></i>
                            </div>
                            <div>
                                <span class="text-[9px] md:text-[10px] text-slate-500 font-bold uppercase tracking-wider">Ordering Table</span>
                                <h3 class="text-sm md:text-base font-extrabold text-white mt-0.5">Table <span x-text="selectedTableName" class="text-purple-400"></span></h3>
                            </div>
                        </div>
                        <button @click="selectedTableId = null" class="px-3 md:px-4 py-2 rounded-xl text-[10px] md:text-xs font-bold transition glass-panel hover:bg-red-500/10 hover:text-red-400 hover:border-red-500/20">
                            Change Table
                        </button>
                    </div>
                    
                    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-3.5 md:gap-4">
                        <template x-for="product in filteredProducts" :key="product.id">
                            <button @click="addToCart(product)" class="glass-panel glass-hover rounded-2xl text-left transition flex flex-col h-48 md:h-52 relative overflow-hidden group">
                                <!-- Item Selected Count Badge -->
                                <div x-show="cart.find(x => x.id === product.id)" 
                                     class="absolute top-2 right-2 z-10 w-6 h-6 rounded-full bg-purple-600 border border-white/20 text-white text-[10px] font-black flex items-center justify-center shadow-lg"
                                     x-text="cart.find(x => x.id === product.id)?.qty"
                                     x-cloak>
                                </div>

                                <!-- Product Image Aspect Ratio card -->
                                <div class="w-full h-24 md:h-28 relative overflow-hidden bg-slate-900 flex items-center justify-center">
                                    <template x-if="product.image">
                                        <img :src="baseUrl + '/public/' + product.image" class="w-full h-full object-cover transition duration-300 group-hover:scale-108" alt="dish">
                                    </template>
                                    <template x-if="!product.image">
                                        <div class="w-full h-full bg-[#0a0f1d] flex flex-col items-center justify-center text-slate-700 group-hover:text-purple-400/50 transition">
                                            <i class="fas fa-bowl-food text-2xl md:text-3xl"></i>
                                        </div>
                                    </template>
                                </div>
                                
                                <div class="flex-1 p-3 flex flex-col justify-between">
                                    <h4 class="font-extrabold text-white text-[11px] md:text-xs leading-snug truncate group-hover:text-purple-300 transition" x-text="product.name"></h4>
                                    <div class="flex justify-between items-end">
                                        <div class="text-purple-400 font-extrabold text-xs md:text-sm"><span x-text="currency"></span><span x-text="parseFloat(product.price).toFixed(2)"></span></div>
                                        <div class="w-6 h-6 rounded-lg bg-purple-600/10 border border-purple-500/20 flex items-center justify-center text-purple-400 group-hover:bg-purple-600 group-hover:text-white transition">
                                            <i class="fas fa-plus text-[10px]"></i>
                                        </div>
                                    </div>
                                </div>
                            </button>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Sidebar Drawer: Desktop Tray Cart (Only active when table is selected) -->
        <div class="hidden lg:flex w-80 flex-col bg-[#0a0f1d] border-l border-white/5 shadow-2xl flex-shrink-0 relative" x-show="selectedTableId" style="display: none;">
            <div class="absolute top-0 right-0 w-48 h-48 rounded-full bg-purple-500/5 blur-3xl pointer-events-none"></div>
            
            <div class="p-5 border-b border-white/5 bg-slate-900/20 flex justify-between items-center">
                <div>
                    <h2 class="text-xs font-black text-white tracking-wider uppercase">Order Tray</h2>
                    <p class="text-[10px] text-slate-500 font-semibold mt-0.5" x-text="cart.length + ' items selected'"></p>
                </div>
                <button @click="cart = []" class="text-red-400 hover:text-red-300 text-xs font-bold transition">Clear All</button>
            </div>
            
            <!-- Cart items loop -->
            <div class="flex-1 overflow-y-auto p-5 space-y-3 relative z-10">
                <div x-show="cart.length === 0" class="text-center text-slate-600 py-16 flex flex-col items-center gap-3">
                    <i class="fas fa-receipt text-3xl"></i>
                    <p class="text-xs">Select dishes from the left menu to build your order tray.</p>
                </div>
                <template x-for="(item, index) in cart" :key="index">
                    <div class="glass-panel p-3 rounded-xl flex justify-between items-center border border-white/5">
                        <div class="flex-1 min-w-0 pr-2">
                            <h4 class="font-extrabold text-white text-xs truncate" x-text="item.name"></h4>
                            <div class="text-purple-400 font-extrabold text-xs mt-1"><span x-text="currency"></span><span x-text="(item.price * item.qty).toFixed(2)"></span></div>
                        </div>
                        <div class="flex items-center bg-[#070b16] rounded-xl border border-white/10 overflow-hidden shadow-md">
                            <button @click="updateQty(index, -1)" class="px-2.5 py-1.5 hover:bg-white/5 text-slate-400 transition font-bold text-xs">-</button>
                            <span class="px-2 text-white font-extrabold text-xs w-6 text-center" x-text="item.qty"></span>
                            <button @click="updateQty(index, 1)" class="px-2.5 py-1.5 hover:bg-white/5 text-slate-400 transition font-bold text-xs">+</button>
                        </div>
                    </div>
                </template>
            </div>
            
            <!-- Coupon Selection & Totals inside Tray -->
            <div x-show="cart.length > 0" class="p-5 border-t border-white/5 bg-slate-900/10 space-y-3">
                <div>
                    <label class="text-[10px] font-bold uppercase tracking-wider text-slate-500 mb-1 block">Apply Coupon</label>
                    <select x-model="selectedCouponCode" @change="applyCouponByCode()" 
                            class="w-full text-xs bg-slate-950 border border-white/10 rounded-xl px-3 py-2 text-white outline-none focus:border-purple-500 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)) + ' OFF)'"></option>
                        </template>
                    </select>
                    <p x-show="couponMessage" class="text-[10px] mt-1 font-semibold" :class="couponSuccess ? 'text-emerald-400' : 'text-rose-400'" x-text="couponMessage"></p>
                </div>

                <div class="text-xs text-slate-400 space-y-1.5 pt-2 border-t border-white/5">
                    <div class="flex justify-between">
                        <span>Subtotal</span>
                        <span class="text-white font-bold"><span x-text="currency"></span><span x-text="subtotal.toFixed(2)"></span></span>
                    </div>
                    <div x-show="discountAmount > 0" class="flex justify-between text-emerald-400">
                        <span>Discount</span>
                        <span class="font-bold">-<span x-text="currency"></span><span x-text="discountAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between">
                        <span>Tax (<span x-text="taxRate"></span>%)</span>
                        <span class="text-white font-bold"><span x-text="currency"></span><span x-text="taxAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between text-sm text-white font-extrabold pt-2 border-t border-white/5">
                        <span>Total</span>
                        <span class="text-purple-400"><span x-text="currency"></span><span x-text="grandTotal.toFixed(2)"></span></span>
                    </div>
                </div>
            </div>

            <!-- Actions trigger tray -->
            <div class="p-5 border-t border-white/5 bg-slate-900/10">
                <button @click="placeOrder" :disabled="cart.length === 0 || isProcessing" 
                        :class="cart.length === 0 ? 'bg-white/5 border border-white/5 text-slate-600 cursor-not-allowed' : 'btn-gradient text-white'" 
                        class="w-full py-3.5 rounded-2xl font-black text-[11px] uppercase tracking-wider shadow-lg transition flex justify-center items-center gap-2">
                    <i class="fas fa-paper-plane text-xs" x-show="!isProcessing"></i>
                    <span x-text="isProcessing ? 'Transmitting...' : 'Send to Cashier'"></span>
                </button>
            </div>
        </div>
    </div>

    <!-- Floating Order Tray Drawer for Mobile Screen sizes (lg:hidden) -->
    <div class="fixed bottom-6 right-6 z-40 lg:hidden" x-show="selectedTableId" style="display: none;">
        <button @click="showMobileCart = true" 
                class="w-14 h-14 rounded-full bg-gradient-to-r from-purple-600 to-indigo-600 hover:scale-105 active:scale-95 text-white flex items-center justify-center shadow-lg shadow-purple-500/40 relative">
            <i class="fas fa-shopping-basket text-lg animate-wiggle"></i>
            <span x-show="cart.length > 0" class="absolute -top-1 -right-1 bg-rose-500 border border-white text-white text-[9px] font-black rounded-full h-5 w-5 flex items-center justify-center" x-text="cart.reduce((s,i)=>s+i.qty, 0)"></span>
        </button>
    </div>

    <!-- Mobile Drawer Tray Modal Sheet -->
    <div x-show="showMobileCart" class="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 lg:hidden flex items-end justify-center" style="display: none;" x-transition>
        <div class="bg-[#0a0f1d] border-t border-white/10 w-full max-h-[80vh] rounded-t-3xl flex flex-col" @click.away="showMobileCart = false">
            <div class="w-12 h-1.5 rounded-full bg-white/10 mx-auto my-3 cursor-pointer" @click="showMobileCart = false"></div>
            
            <div class="px-5 pb-4 border-b border-white/5 flex justify-between items-center">
                <div>
                    <h3 class="font-extrabold text-white text-base">Order Tray</h3>
                    <p class="text-[10px] text-slate-500 mt-0.5" x-text="cart.length + ' items selected for Table ' + selectedTableName"></p>
                </div>
                <button @click="cart = []" class="text-red-400 hover:text-red-300 text-xs font-bold transition">Clear All</button>
            </div>

            <!-- Items list -->
            <div class="flex-1 overflow-y-auto p-5 space-y-3">
                <template x-for="(item, index) in cart" :key="index">
                    <div class="glass-panel p-3.5 rounded-2xl flex justify-between items-center border border-white/5">
                        <div class="flex-1 min-w-0 pr-2">
                            <h4 class="font-extrabold text-white text-xs truncate" x-text="item.name"></h4>
                            <div class="text-purple-400 font-extrabold text-xs mt-1"><span x-text="currency"></span><span x-text="(item.price * item.qty).toFixed(2)"></span></div>
                        </div>
                        <div class="flex items-center bg-[#070b16] rounded-xl border border-white/10 overflow-hidden shadow-md">
                            <button @click="updateQty(index, -1)" class="px-3 py-2 hover:bg-white/5 text-slate-400 transition font-bold text-xs">-</button>
                            <span class="px-2 text-white font-extrabold text-xs w-6 text-center" x-text="item.qty"></span>
                            <button @click="updateQty(index, 1)" class="px-3 py-2 hover:bg-white/5 text-slate-400 transition font-bold text-xs">+</button>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Mobile Coupon & Totals -->
            <div class="p-5 border-t border-white/5 bg-slate-900/20 space-y-3" x-show="cart.length > 0">
                <div>
                    <label class="text-[10px] font-bold uppercase tracking-wider text-slate-500 mb-1 block">Apply Coupon</label>
                    <select x-model="selectedCouponCode" @change="applyCouponByCode()" 
                            class="w-full text-xs bg-slate-950 border border-white/10 rounded-xl px-3 py-2 text-white outline-none focus:border-purple-500 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)) + ' OFF)'"></option>
                        </template>
                    </select>
                    <p x-show="couponMessage" class="text-[10px] mt-1 font-semibold" :class="couponSuccess ? 'text-emerald-400' : 'text-rose-400'" x-text="couponMessage"></p>
                </div>

                <div class="text-xs text-slate-400 space-y-1.5 pt-2 border-t border-white/5">
                    <div class="flex justify-between">
                        <span>Subtotal</span>
                        <span class="text-white font-bold"><span x-text="currency"></span><span x-text="subtotal.toFixed(2)"></span></span>
                    </div>
                    <div x-show="discountAmount > 0" class="flex justify-between text-emerald-400">
                        <span>Discount</span>
                        <span class="font-bold">-<span x-text="currency"></span><span x-text="discountAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between">
                        <span>Tax (<span x-text="taxRate"></span>%)</span>
                        <span class="text-white font-bold"><span x-text="currency"></span><span x-text="taxAmount.toFixed(2)"></span></span>
                    </div>
                    <div class="flex justify-between text-sm text-white font-extrabold pt-2 border-t border-white/5">
                        <span>Total</span>
                        <span class="text-purple-400"><span x-text="currency"></span><span x-text="grandTotal.toFixed(2)"></span></span>
                    </div>
                </div>
            </div>

            <div class="p-5 border-t border-white/5 bg-slate-900/20">
                <button @click="placeOrder(); showMobileCart = false" :disabled="cart.length === 0 || isProcessing" 
                        class="w-full py-4 rounded-2xl font-black text-xs uppercase tracking-wider btn-gradient text-white shadow-lg flex justify-center items-center gap-2">
                    <i class="fas fa-paper-plane text-xs"></i>
                    <span>Send to Cashier</span>
                </button>
            </div>
        </div>
    </div>

    <!-- My Orders Modal (Detailed full screen status) -->
    <div x-show="showMyOrders" class="fixed inset-0 bg-black/75 backdrop-blur-sm z-50 flex items-center justify-center p-4" style="display: none;">
        <div class="bg-[#0a0f1d] border border-white/10 w-full max-w-2xl max-h-[85vh] rounded-3xl shadow-2xl flex flex-col relative" @click.away="showMyOrders = false">
            
            <div class="p-5 border-b border-white/5 flex justify-between items-center bg-slate-900/40 rounded-t-3xl relative z-10">
                <div>
                    <h2 class="text-sm md:text-base font-black text-white tracking-wide uppercase">Floor Active Orders</h2>
                    <p class="text-[10px] md:text-xs text-slate-500 mt-1">Live status tracking for active floor tables</p>
                </div>
                <button @click="showMyOrders = false" class="w-8 h-8 rounded-full glass-panel hover:bg-white/5 flex items-center justify-center text-slate-400 hover:text-white transition"><i class="fas fa-times text-xs"></i></button>
            </div>
            
            <div class="p-6 overflow-y-auto space-y-4 relative z-10">
                <template x-for="order in myOrders" :key="order.id">
                    <div class="glass-panel p-4 md:p-5 rounded-2xl flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                        <div>
                            <h3 class="font-extrabold text-white text-base md:text-lg flex items-center gap-2">Table <span x-text="order.table_name" class="text-purple-400"></span></h3>
                            <div class="text-[10px] md:text-xs text-slate-500 mt-1 flex flex-wrap items-center gap-1.5">
                                <span>Order #<span x-text="order.order_number || order.id"></span></span>
                                <span>•</span>
                                <span><span x-text="order.items.length"></span> dishes</span>
                                <span>•</span>
                                <span class="font-extrabold text-purple-400"><span x-text="currency"></span><span x-text="parseFloat(order.total).toFixed(2)"></span></span>
                                <span x-show="order.waiter_name" class="text-slate-400"> • Waiter: <span x-text="order.waiter_name"></span></span>
                                <span x-show="!order.waiter_id" class="text-emerald-400 font-bold"> • QR Menu Order</span>
                            </div>
                        </div>
                        <div class="flex items-center gap-3">
                            <span class="px-2.5 py-1 rounded-xl text-[9px] md:text-[10px] font-black uppercase border tracking-wider shadow" 
                                :class="{
                                    'bg-slate-500/10 text-slate-400 border-slate-500/25': order.status === 'pending',
                                    'bg-indigo-500/10 text-indigo-400 border-indigo-500/25': order.status === 'accepted' && order.kitchen_status === 'queued',
                                    'bg-amber-500/10 text-amber-400 border-amber-500/25': order.kitchen_status === 'preparing',
                                    'bg-emerald-500/10 text-emerald-400 border-emerald-500/25 pulse-green': order.kitchen_status === 'ready'
                                }">
                                <span x-text="order.status === 'pending' ? 'Unaccepted' : (order.kitchen_status === 'queued' ? 'Queued' : (order.kitchen_status === 'preparing' ? 'Cooking' : 'Ready to Serve! 🔔'))"></span>
                            </span>
                            <button x-show="order.kitchen_status === 'ready'" 
                                    @click="markAsDelivered(order.id); showMyOrders = false" 
                                    class="px-3.5 py-1.5 bg-emerald-600 hover:bg-emerald-500 text-white rounded-xl text-[10px] font-extrabold transition flex items-center gap-1">
                                <i class="fas fa-check"></i> Serve
                            </button>
                        </div>
                    </div>
                </template>
                <div x-show="myOrders.length === 0" class="text-center py-16 text-slate-500 flex flex-col items-center gap-3">
                    <i class="fas fa-receipt text-4xl text-slate-700"></i>
                    <p class="text-xs">No active orders placed by you.</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Alpine.js Application Logic -->
    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.data('waiterApp', () => ({
                categories: [], 
                products: [], 
                floors: [], 
                tables: [], 
                myOrders: [],
                notifications: [],
                playedAlarmOrders: [],
                activeCategory: null, 
                selectedTableId: null, 
                selectedTableName: '',
                cart: [], 
                isProcessing: false, 
                showMyOrders: false, 
                showMobileCart: false,
                currency: '<?php echo FeatureGate::currency($_SESSION['restaurant_id']); ?>',
                theme: localStorage.getItem('waiter-theme') || 'dark',
                audioEnabled: localStorage.getItem('waiter-sound') === 'enabled',
                audioCtx: null,
                baseUrl: window.BASE_URL !== undefined ? window.BASE_URL : '/RestiPO',

                coupons: [],
                taxRate: 5,
                discountRate: 0,
                selectedCouponCode: '',
                selectedCoupon: null,
                couponMessage: '',
                couponSuccess: false,

                init() {
                    this.fetchData();
                    setInterval(() => { this.fetchData(); }, 3000); // Polling every 3 sec for real-time alerts

                    this.$watch('subtotal', () => {
                        if (this.selectedCouponCode) {
                            this.applyCouponByCode();
                        }
                    });

                    // Unlocks browser AudioContext on first page click if alarms are enabled
                    const unlock = () => {
                        if (this.audioEnabled) {
                            this.initAudioContext();
                            this.playReadyAlarm(true);
                        }
                        window.removeEventListener('click', unlock);
                        window.removeEventListener('touchstart', unlock);
                    };
                    window.addEventListener('click', unlock);
                    window.addEventListener('touchstart', unlock);
                },

                toggleTheme() {
                    this.theme = this.theme === 'dark' ? 'light' : 'dark';
                    localStorage.setItem('waiter-theme', this.theme);
                },

                toggleSound() {
                    this.audioEnabled = !this.audioEnabled;
                    localStorage.setItem('waiter-sound', this.audioEnabled ? 'enabled' : 'disabled');
                    if (this.audioEnabled) {
                        this.initAudioContext();
                        this.playReadyAlarm(true); // silent note to unlock AudioContext
                    }
                },

                initAudioContext() {
                    if (!this.audioCtx) {
                        this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                    }
                },

                fetchData() {
                    fetch(window.BASE_URL + '/waiter/api/data')
                        .then(res => res.json())
                        .then(data => {
                            if(data.error) { window.location = window.BASE_URL + '/lsign'; return; }
                            this.categories = data.categories; 
                            this.products = data.products;
                            this.floors = data.floors; 
                            this.tables = data.tables;
                            this.myOrders = data.my_orders || [];
                            this.currency = data.currency || '$';
                            this.taxRate = parseFloat(data.tax_rate) || 0;
                            this.discountRate = parseFloat(data.discount_rate) || 0;
                            this.coupons = data.coupons || [];

                            // Realtime kitchen connectivity sound checks
                            this.checkReadyOrders();
                        });
                },

                checkReadyOrders() {
                    this.myOrders.forEach(order => {
                        if (order.kitchen_status === 'ready') {
                            const orderId = order.id;
                            if (!this.playedAlarmOrders.includes(orderId)) {
                                this.playedAlarmOrders.push(orderId);
                                
                                // Spawn top-floating toast
                                const notifId = Date.now() + Math.random();
                                this.notifications.push({
                                    id: notifId,
                                    tableName: order.table_name || '—'
                                });
                                
                                // Play Audio Alarm
                                if (this.audioEnabled) {
                                    this.playReadyAlarm();
                                }
                                
                                // Automatically dismiss toast after 8 seconds
                                setTimeout(() => {
                                    this.removeNotification(notifId);
                                }, 8000);
                            }
                        }
                    });
                },

                removeNotification(id) {
                    this.notifications = this.notifications.filter(n => n.id !== id);
                },

                playReadyAlarm(silent = false) {
                    if (!this.audioEnabled) return;
                    try {
                        this.initAudioContext();
                        const ctx = this.audioCtx;

                        const volume = silent ? 0.0001 : 0.35;

                        const playTone = (freq, delay, duration) => {
                            setTimeout(() => {
                                if (ctx.state === 'suspended') {
                                    ctx.resume();
                                }
                                const osc = ctx.createOscillator();
                                const gain = ctx.createGain();
                                
                                osc.type = 'sine';
                                osc.frequency.value = freq;
                                
                                gain.gain.setValueAtTime(volume, ctx.currentTime);
                                gain.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + duration);
                                
                                osc.connect(gain);
                                gain.connect(ctx.destination);
                                
                                osc.start();
                                osc.stop(ctx.currentTime + duration);
                            }, delay);
                        };

                        // High fidelity E5 and A5 chime tones
                        playTone(659.25, 0, 0.4);
                        playTone(880.00, 150, 0.6);
                    } catch (e) {
                        console.error("Audio Context alarm failed: ", e);
                    }
                },

                markAsDelivered(orderId) {
                    fetch(window.BASE_URL + '/kitchen/api/status', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ order_id: orderId, status: 'served' })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            this.fetchData();
                        } else {
                            alert('Error updating delivery status');
                        }
                    });
                },

                get subtotal() {
                    return this.cart.reduce((s, i) => s + (i.price * i.qty), 0);
                },
                get couponDiscountAmount() {
                    if (!this.selectedCoupon) return 0;
                    let restrictedSubtotal = 0;
                    let hasRestriction = false;

                    if (this.selectedCoupon.product_id) {
                        hasRestriction = true;
                        this.cart.forEach(item => {
                            if (item.id == this.selectedCoupon.product_id) {
                                restrictedSubtotal += (item.price * item.qty);
                            }
                        });
                    } else if (this.selectedCoupon.category_id) {
                        hasRestriction = true;
                        this.cart.forEach(item => {
                            const prod = this.products.find(p => p.id == item.id);
                            if (prod && prod.category_id == this.selectedCoupon.category_id) {
                                restrictedSubtotal += (item.price * item.qty);
                            }
                        });
                    }

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

                    if (this.selectedCoupon.type === 'percentage') {
                        return restrictedSubtotal * (parseFloat(this.selectedCoupon.value) / 100);
                    } else {
                        return Math.min(restrictedSubtotal, parseFloat(this.selectedCoupon.value));
                    }
                },
                get discountAmount() {
                    const baseDiscount = this.subtotal * (this.discountRate / 100);
                    return baseDiscount + this.couponDiscountAmount;
                },
                get taxAmount() {
                    return Math.max(0, this.subtotal - this.discountAmount) * (this.taxRate / 100);
                },
                get grandTotal() {
                    return Math.max(0, this.subtotal - this.discountAmount) + this.taxAmount;
                },
                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;
                    });
                },

                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;
                    }

                    // Check minimum order amount
                    if (parseFloat(coupon.min_order_amount) > 0 && this.subtotal < parseFloat(coupon.min_order_amount)) {
                        this.selectedCoupon = null;
                        this.couponMessage = `Min subtotal is ${this.currency}${parseFloat(coupon.min_order_amount).toFixed(2)}`;
                        this.couponSuccess = false;
                        return;
                    }

                    // Check day of week
                    if (coupon.applicable_days) {
                        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
                        const currentDay = days[new Date().getDay()];
                        const allowedDays = coupon.applicable_days.split(',');
                        if (!allowedDays.includes(currentDay)) {
                            this.selectedCoupon = null;
                            this.couponMessage = `Not active on ${currentDay}s`;
                            this.couponSuccess = false;
                            return;
                        }
                    }

                    // Check Category restriction
                    if (coupon.category_id) {
                        const hasCat = this.cart.some(item => {
                            const prod = this.products.find(p => p.id == item.id);
                            return prod && prod.category_id == coupon.category_id;
                        });
                        if (!hasCat) {
                            this.selectedCoupon = null;
                            this.couponMessage = `Requires items from restricted category`;
                            this.couponSuccess = false;
                            return;
                        }
                    }

                    // Check Product restriction
                    if (coupon.product_id) {
                        const hasProd = this.cart.some(item => item.id == coupon.product_id);
                        if (!hasProd) {
                            this.selectedCoupon = null;
                            const pName = (this.products.find(p => p.id == coupon.product_id) || { name: 'restricted product' }).name;
                            this.couponMessage = `Requires ${pName} in cart`;
                            this.couponSuccess = false;
                            return;
                        }
                    }

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

                get filteredProducts() {
                    let p = this.products;
                    if (this.activeCategory) p = p.filter(x => x.category_id == this.activeCategory);
                    return p;
                },

                selectTable(table) {
                    this.selectedTableId = table.id;
                    this.selectedTableName = table.name;
                    this.selectedCouponCode = '';
                    this.selectedCoupon = null;
                    this.couponMessage = '';
                    this.couponSuccess = false;
                },

                addToCart(product) {
                    const existing = this.cart.find(x => x.id === product.id);
                    if (existing) { 
                        existing.qty++; 
                    } else { 
                        this.cart.push({ id: product.id, name: product.name, price: parseFloat(product.price), qty: 1 }); 
                    }
                },

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

                placeOrder() {
                    this.isProcessing = true;
                    const orderItems = this.cart.map(item => ({
                        id: item.id,
                        name: item.name,
                        price: item.price,
                        quantity: item.qty
                    }));

                    fetch(window.BASE_URL + '/waiter/api/order', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            table_id: this.selectedTableId, 
                            items: orderItems,
                            notes: '',
                            coupon_code: this.selectedCouponCode || null
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        this.isProcessing = false;
                        if (data.success) {
                            this.cart = []; 
                            this.selectedTableId = null;
                            this.selectedCouponCode = '';
                            this.selectedCoupon = null;
                            this.couponMessage = '';
                            this.couponSuccess = false;
                            this.fetchData();
                        } else {
                            alert(data.message);
                        }
                    });
                }
            }));
        });
    </script>
</body>
</html>

