<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="Granny Restaurant">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Server Dashboard - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <!-- Server Styles -->
    <link rel="stylesheet" href="server-styles.css">

    <title>Server Dashboard - Granny Restaurant</title>
</head>

<body>
    <!-- Sidebar Overlay (for mobile) -->
    <div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebarMenu()"></div>

    <!-- Sidebar -->
    <aside class="sidebar">
        <div class="logo">
            <i class="fas fa-utensils"></i>
            <span>Granny Restaurant</span>
        </div>

        <ul class="sidebar-nav">
            <li><a href="dashboard.php" class="active"><i class="fas fa-home"></i> Dashboard</a></li>
            <li><a href="#" onclick="viewMyProfile()"><i class="fas fa-user"></i> My Profile</a></li>
        </ul>

        <div class="sidebar-section">
            <div class="sidebar-section-title">Actions</div>
            <button class="logout-btn" onclick="logout()">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </aside>

    <!-- Main Content -->
    <div class="dashboard-container">
        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <button id="hamburgerBtn" class="hamburger-btn" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 id="pageTitle">My Assigned Tables</h1>
            </div>
            <div class="header-right">
                <div class="user-info">
                    <span id="serverName">Loading...</span>
                    <!-- Ready Orders Notification Bell -->
                    <div class="notification-bell" onclick="showReadyOrdersModal()" style="position: relative; cursor: pointer; font-size: 20px;">
                        <i class="fas fa-bell"></i>
                        <span id="readyOrdersCount" class="notification-badge" style="display: none; position: absolute; top: -5px; right: -10px; background: #ff4444; color: white; border-radius: 50%; width: 20px; height: 20px; font-size: 12px; display: flex; align-items: center; justify-content: center; font-weight: bold;">0</span>
                    </div>
                    <span class="status-badge" id="statusBadge">
                        <span class="status-dot"></span>
                        <span id="statusText">Online</span>
                    </span>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Stats Section -->
            <div class="stats-section">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-table"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="assignedTablesCount">0</div>
                        <div class="stat-label">Assigned Tables</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-shopping-cart"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="activeOrdersCount">0</div>
                        <div class="stat-label">Active Orders</div>
                    </div>
                </div>

                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-list-check"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value" id="completedOrdersCount">0</div>
                        <div class="stat-label">Completed Orders</div>
                    </div>
                </div>
            </div>

            <!-- Tables Grid -->
            <div class="page-header">
                <h2>Your Tables</h2>
                <span class="refresh-btn" onclick="loadDashboardData()" title="Refresh"><i class="fas fa-sync-alt"></i></span>
            </div>

            <div class="tables-container">
                <div id="tablesGrid" class="tables-grid">
                    <div class="loading-message">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p>Loading your tables...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Table Modal -->
    <div id="tableModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTableTitle">Table Details</h2>
                <button class="close-btn" onclick="closeTableModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="modalContent">Loading...</div>
            </div>
        </div>
    </div>

    <!-- Order Taking Modal - Two Section Layout -->
    <div id="orderModal" class="modal order-modal">
        <div class="modal-content order-modal-content two-section-layout">
            <div class="modal-header order-modal-header">
                <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                    <h2 style="margin: 0;">Take Order - Table <span id="orderTableNumber">0</span></h2>
                    <button onclick="sendOrderToKitchen()" class="btn btn-submit" id="sendToKitchenBtn" disabled style="background-color: #ff9800; opacity: 0.5; cursor: not-allowed; margin-right: 10px;">
                        <i class="fas fa-fire"></i> Send to Kitchen
                    </button>
                </div>
                <button class="close-btn" onclick="closeOrderModal()">&times;</button>
            </div>

            <!-- Kitchen Status Notice -->
            <div id="kitchenStatusNotice" style="display: none; background: #e3f2fd; border-left: 4px solid #2196f3; padding: 12px; margin: 10px; border-radius: 4px; color: #1565c0; font-size: 13px;">
                <i class="fas fa-fire"></i> <strong>Note:</strong> Items already sent to kitchen are shown below. You can add more items for this table.
            </div>

            <div class="modal-body order-modal-body two-section-body">
                <!-- LEFT SECTION: Menu Items -->
                <div class="menu-section left-section">
                    <!-- Category Tabs -->
                    <div class="category-tabs">
                        <div id="categoryTabsContainer" class="tabs-container">
                            Loading categories...
                        </div>
                    </div>

                    <!-- Menu Items Display -->
                    <div id="menuItemsContainer" class="menu-items-container">
                        <!-- Subcategory sections will be rendered here -->
                    </div>
                </div>

                <!-- RIGHT SECTION: Selected Items & Summary -->
                <div class="selected-items-section right-section">
                    <div class="selected-items-header">
                        <h3>Order Summary</h3>
                        <span class="items-badge" id="itemsCount">0</span>
                    </div>

                    <!-- Selected Items List -->
                    <div id="selectedItemsList" class="selected-items-list">
                        <p class="empty-order-message">No items selected yet</p>
                    </div>

                    <!-- Order Footer with Total -->
                    <div class="order-footer-summary">
                        <div class="summary-row existing-total-row" id="existingTotalRow" style="display: none;">
                            <span class="summary-label">Existing Total:</span>
                            <span class="summary-value existing-total-value" id="existingTotal">₹ 0.00</span>
                        </div>
                        <div class="summary-row new-total-row" id="newTotalRow" style="display: none;">
                            <span class="summary-label">New Items Total:</span>
                            <span class="summary-value new-total-value" id="newTotal">₹ 0.00</span>
                        </div>
                        <div class="summary-row total-row" id="overallTotalRow">
                            <span class="summary-label">Overall Total:</span>
                            <span class="summary-value total-value" id="totalAmount">₹ 0.00</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal-footer order-modal-footer">
                <button onclick="cancelOrder()" class="btn btn-cancel">Cancel</button>
                <button onclick="submitOrder()" class="btn btn-submit" id="submitOrderBtn">Place Order</button>
                <button onclick="sendOrderToManager()" class="btn btn-submit" id="sendToManagerBtn" style="display: none; background-color: #e74c3c;">
                    <i class="fas fa-envelope"></i> Send to Manager
                </button>
                <button onclick="generateBill()" class="btn btn-submit" id="generateBillBtn" style="display: none; background-color: #27ae60;">
                    <i class="fas fa-receipt"></i> Generate Bill
                </button>
            </div>
        </div>
    </div>

    <!-- Item Detail Modal -->
    <div id="itemDetailModal" class="modal item-modal">
        <div class="modal-content item-modal-content">
            <div class="modal-header">
                <h2 id="itemDetailName">Item Name</h2>
                <button class="close-btn" onclick="closeItemDetail()">&times;</button>
            </div>
            <div class="modal-body item-modal-body">
                <img id="itemDetailImage" src="" alt="Item" class="item-detail-image" onerror="this.onerror=null; this.src='data:image/svg+xml,%3Csvg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;300&quot; height=&quot;200&quot;%3E%3Crect fill=&quot;%23e9ecef&quot; width=&quot;300&quot; height=&quot;200&quot;/%3E%3Ctext x=&quot;50%25&quot; y=&quot;50%25&quot; font-family=&quot;Arial&quot; font-size=&quot;14&quot; fill=&quot;%23999&quot; text-anchor=&quot;middle&quot; dy=&quot;.3em&quot;%3ENo Image%3C/text%3E%3C/svg%3E'">
                <p id="itemDetailDescription" class="item-detail-description"></p>
                <div class="item-detail-price">
                    <span>Price: </span>
                    <span id="itemDetailPrice">₹ 0</span>
                </div>
                <div class="item-detail-quantity">
                    <label>Quantity:</label>
                    <div class="quantity-selector">
                        <button onclick="decreaseQuantity()" class="qty-btn">-</button>
                        <input type="number" id="itemQuantity" value="1" min="1" max="50">
                        <button onclick="increaseQuantity()" class="qty-btn">+</button>
                    </div>
                </div>
            </div>
            <div class="modal-footer item-modal-footer">
                <button onclick="closeItemDetail()" class="btn btn-cancel">Close</button>
                <button onclick="addItemToOrder()" class="btn btn-submit">Add to Order</button>
            </div>
        </div>
    </div>

    <!-- Ready Orders Modal -->
    <div id="readyOrdersModal" class="modal">
        <div class="modal-content" style="width: 90%; max-width: 700px;">
            <div class="modal-header">
                <h2>Orders Ready for Pickup <span id="readyOrdersCountModal" class="badge badge-ready">0</span></h2>
                <button class="close-btn" onclick="closeReadyOrdersModal()">&times;</button>
            </div>
            <div class="modal-body" id="readyOrdersListContainer">
                <p class="empty-order-message">No orders ready for pickup</p>
            </div>
            <div class="modal-footer">
                <button onclick="closeReadyOrdersModal()" class="btn btn-cancel">Close</button>
            </div>
        </div>
    </div>

    <!-- Bill Modal -->
    <div id="billModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h2>Bill - <span id="billOrderNumber">Order #0</span></h2>
                <button class="close-btn" onclick="closeBillModal()">&times;</button>
            </div>
            <div class="modal-body" style="padding: 20px;">
                <!-- Bill Header -->
                <div style="border-bottom: 2px solid #ddd; padding-bottom: 15px; margin-bottom: 15px;">
                    <h3 style="margin: 0 0 10px 0; color: #333;">Table <span id="billTableNumber">0</span></h3>
                    <p style="margin: 5px 0; font-size: 13px; color: #666;">
                        Order: <strong id="billOrderNum">-</strong>
                    </p>
                    <p style="margin: 5px 0; font-size: 13px; color: #666;">
                        Time: <strong id="billOrderTime">-</strong>
                    </p>
                </div>

                <!-- Items List -->
                <div style="margin-bottom: 20px;">
                    <h4 style="margin: 0 0 15px 0; color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">Items</h4>
                    <div id="billItemsList"></div>
                </div>

                <!-- Bill Summary -->
                <div style="background: #f9f9f9; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #ddd;">
                        <span>Subtotal:</span>
                        <strong id="billSubtotal">₹ 0.00</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 16px; font-weight: bold; color: #2c3e50;">
                        <span>Total Amount:</span>
                        <strong style="color: #27ae60; font-size: 18px;" id="billTotal">₹ 0.00</strong>
                    </div>
                </div>

                <!-- Order Status -->
                <div style="background: #e3f2fd; border-left: 3px solid #2196f3; padding: 10px; border-radius: 3px; margin-bottom: 15px;">
                    <p style="margin: 0; font-size: 13px; color: #1565c0;">
                        <i class="fas fa-info-circle"></i>
                        <strong id="billStatus">Status: Ready for Delivery</strong>
                    </p>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeBillModal()" class="btn btn-cancel">Close</button>
                <button onclick="completeBillAndOrder()" class="btn btn-submit" style="background: #27ae60;">
                    <i class="fas fa-check"></i> Confirm Payment & Complete
                </button>
            </div>
        </div>
    </div>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

    <script>
        // Check if server is logged in
        async function checkServerSession() {
            try {
                const response = await fetch('../backend/server_session_check.php');
                const data = await response.json();

                if (!data.success) {
                    window.location.href = 'login.php';
                    return;
                }

                // Update header with server name
                document.getElementById('serverName').textContent = data.data.name;

                // Update stats
                loadDashboardData();

                // Check for ready orders immediately
                checkReadyOrders();

                // Check for ready orders every 10 seconds
                setInterval(checkReadyOrders, 10000);
            } catch (error) {
                console.error('Session check error:', error);
                window.location.href = 'login.php';
            }
        }

        // Load dashboard data
        async function loadDashboardData() {
            try {
                const response = await fetch('../backend/server_session_check.php');
                const data = await response.json();

                console.log('Dashboard data response:', data);

                if (!data.success) {
                    window.location.href = 'login.php';
                    return;
                }

                const serverData = data.data;
                console.log('Server data:', serverData);
                console.log('Assigned tables:', serverData.assigned_tables);
                console.log('Assigned tables count:', serverData.assigned_tables_count);

                // Log debug info if available
                if (serverData._debug && serverData._debug.length > 0) {
                    console.warn('DEBUG INFO:', serverData._debug);
                }

                // Update counts
                document.getElementById('assignedTablesCount').textContent = serverData.assigned_tables_count;
                document.getElementById('serverName').textContent = serverData.name;

                // Load tables grid
                loadTablesGrid(serverData.assigned_tables);

                // Get order statistics
                await updateOrderStats();
            } catch (error) {
                console.error('Error loading dashboard:', error);
                Swal.fire('Error', 'Failed to load dashboard', 'error');
            }
        }

        // Load tables grid
        async function loadTablesGrid(tables) {
            const grid = document.getElementById('tablesGrid');

            if (!tables || tables.length === 0) {
                grid.innerHTML = '<div class="empty-message"><i class="fas fa-inbox"></i><p>No tables assigned to you yet</p></div>';
                return;
            }

            grid.innerHTML = tables.map((table, index) => {
                console.log(`Table ${index}:`, {
                    id: table.id,
                    table_number: table.table_number,
                    type_id: typeof table.id,
                    type_number: typeof table.table_number
                });

                const tableId = parseInt(table.table_id ?? table.id, 10) || null;
                const assignmentId = parseInt(table.assignment_id, 10) || null;
                const tableNumber = String(table.table_number) || null;

                if (!tableId || !tableNumber || !assignmentId) {
                    console.warn(`Skipping table ${index} - missing table_id, assignment_id, or table_number`, table);
                    return '';
                }

                const assignedSeatsRaw = parseInt(table.assigned_seats, 10);
                const guestCountRaw = parseInt(table.number_of_guests, 10);
                const capacityRaw = parseInt(table.capacity, 10);
                const remainingSeatsRaw = parseInt(table.remaining_seats, 10);

                const assignedSeats = Number.isFinite(assignedSeatsRaw)
                    ? assignedSeatsRaw
                    : (Number.isFinite(guestCountRaw) ? guestCountRaw : 0);
                const capacity = Number.isFinite(capacityRaw) ? capacityRaw : 0;
                const remainingSeats = Number.isFinite(remainingSeatsRaw)
                    ? remainingSeatsRaw
                    : Math.max(0, capacity - assignedSeats);

                return `
                <div class="table-card" data-table-id="${tableId}" data-assignment-id="${assignmentId}" data-table-number="${tableNumber}">
                    <div class="table-header">
                        <h3>Table ${table.table_number}</h3>
                        <span class="badge badge-${table.status}">${table.status.capitalize()}</span>
                    </div>
                    <div class="table-info">
                        <p><i class="fas fa-layer-group"></i> Customer Group: <strong>#${assignmentId}</strong></p>
                        <p><i class="fas fa-user-check"></i> Assigned Seats: <strong>${assignedSeats}</strong> / ${capacity}</p>
                        ${remainingSeats > 0 ? `<p><i class="fas fa-chair"></i> Remaining Seats: <strong style="color: #28a745;">${remainingSeats}</strong></p>` : ''}
                        <p><i class="fas fa-map-marker"></i> Floor ${table.floor} - ${table.section}</p>
                    </div>
                    <div class="table-actions" style="display: flex; gap: 10px;">
                        <button class="btn-table-action" data-action="take-order" data-has-order="false" style="flex: 1;">
                            <i class="fas fa-plus"></i> Take Order
                        </button>
                        <button class="btn-table-action btn-remove-order" data-action="remove-order" style="display: none; background-color: #dc3545; flex: 0.5;" title="Remove Order">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>
                `;
            }).filter(item => item !== '').join('');

            // Add event listeners to table cards and check for existing orders
            grid.querySelectorAll('.table-card').forEach(card => {
                const tableId = parseInt(card.dataset.tableId, 10);
                const assignmentId = parseInt(card.dataset.assignmentId, 10);

                // Check if table has existing order
                checkTableOrder(tableId, assignmentId, card);

                // View details on card click (including reopening order if exists)
                card.addEventListener('click', function(e) {
                    if (e.target.closest('.btn-table-action')) return; // Don't trigger if clicking button
                    const tableId = parseInt(this.dataset.tableId, 10);
                    const assignmentId = parseInt(this.dataset.assignmentId, 10);
                    const tableNumber = String(this.dataset.tableNumber);
                    takeOrder(tableId, tableNumber, assignmentId);
                });

                // Take order on button click
                const takeOrderBtn = card.querySelector('[data-action="take-order"]');
                takeOrderBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const tableId = parseInt(card.dataset.tableId, 10);
                    const assignmentId = parseInt(card.dataset.assignmentId, 10);
                    const tableNumber = String(card.dataset.tableNumber);
                    console.log('Take order clicked:', {
                        tableId: tableId,
                        assignmentId: assignmentId,
                        tableNumber: tableNumber,
                        rawTableId: card.dataset.tableId,
                        rawAssignmentId: card.dataset.assignmentId,
                        rawTableNumber: card.dataset.tableNumber
                    });
                    takeOrder(tableId, tableNumber, assignmentId);
                });

                // Remove order on button click
                const removeOrderBtn = card.querySelector('[data-action="remove-order"]');
                removeOrderBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const orderId = parseInt(this.dataset.orderId);
                    const tableNumber = String(card.dataset.tableNumber);
                    removeOrder(orderId, tableNumber);
                });
            });
        }

        // Check if table has existing order
        async function checkTableOrder(tableId, assignmentId, card) {
            try {
                const query = new URLSearchParams({
                    table_id: String(tableId),
                    assignment_id: String(assignmentId)
                });
                const response = await fetch(`../backend/server_get_table_orders.php?${query.toString()}`);
                const data = await response.json();
                const button = card.querySelector('[data-action="take-order"]');
                const removeBtn = card.querySelector('[data-action="remove-order"]');

                if (data.success && data.has_existing_order) {
                    button.dataset.hasOrder = 'true';
                    button.innerHTML = '<i class="fas fa-check"></i> Order Taken';
                    button.classList.add('order-exists');
                    button.dataset.orderId = data.order_id;

                    // Show remove button and store order ID
                    removeBtn.style.display = 'block';
                    removeBtn.dataset.orderId = data.order_id;
                } else {
                    button.dataset.hasOrder = 'false';
                    button.innerHTML = '<i class="fas fa-plus"></i> Take Order';
                    button.classList.remove('order-exists');
                    button.dataset.orderId = '';
                    removeBtn.style.display = 'none';
                    removeBtn.dataset.orderId = '';
                }
            } catch (error) {
                console.error('Error checking table order:', error);
            }
        }

        // View table details modal
        function viewTableDetails(tableId) {
            // Implement table details modal
            Swal.fire('Table Details', `Table ${tableId} details coming soon`, 'info');
        }

        // Global variables for order taking
        let currentOrderData = {
            tableId: null,
            assignmentId: null,
            tableNumber: null,
            orderId: null, // Add order ID for tracking if it's an existing order
            isExistingOrder: false, // Track if this is an existing order
            kitchenSent: false, // Track if items have been sent to kitchen
            initialKitchenSent: false, // Track if the FIRST send to kitchen has been done
            existingItemIds: [], // Track which items were already in the order
            items: [],
            currentCategory: null,
            menu: {}
        };

        let selectedItem = {
            id: null,
            name: null,
            price: null,
            image: null,
            quantity: 1
        };

        let lastItemAddTime = 0; // Track last item add time for debounce

        // Take order for table - Opens order modal with menu
        async function takeOrder(tableId, tableNumber, assignmentId = null) {
            console.log('takeOrder called with:', {
                tableId,
                tableNumber,
                assignmentId
            });

            // Validate inputs
            if (tableId === null || tableId === undefined || isNaN(tableId)) {
                console.error('Invalid tableId:', {
                    tableId,
                    parsed: parseInt(tableId)
                });
                Swal.fire('Error', 'Invalid table ID - table not found or not assigned. Please refresh the page.', 'error');
                return;
            }
            if (!tableNumber || tableNumber === '' || typeof tableNumber !== 'string') {
                console.error('Invalid tableNumber:', {
                    tableNumber,
                    type: typeof tableNumber
                });
                Swal.fire('Error', 'Invalid table number - table data corrupted. Please refresh the page.', 'error');
                return;
            }

            currentOrderData.tableId = tableId;
            currentOrderData.assignmentId = assignmentId;
            currentOrderData.tableNumber = tableNumber;
            currentOrderData.items = [];
            currentOrderData.orderId = null;
            currentOrderData.isExistingOrder = false;
            currentOrderData.kitchenSent = false; // Reset kitchen sent flag for new/existing orders
            let orderStatus = null;

            // Check for existing order
            try {
                const query = new URLSearchParams({
                    table_id: String(tableId)
                });
                if (assignmentId && !isNaN(assignmentId)) {
                    query.set('assignment_id', String(assignmentId));
                }
                const response = await fetch(`../backend/server_get_table_orders.php?${query.toString()}`);
                const data = await response.json();

                if (data.success && data.has_existing_order) {
                    currentOrderData.orderId = data.order_id;
                    currentOrderData.isExistingOrder = true;
                    orderStatus = data.order_status;

                    // Load existing items into the order
                    if (data.items && data.items.length > 0) {
                        // We'll populate these items after loading the menu
                        currentOrderData.items = data.items;
                        console.log('Loaded existing items:', data.items);
                    }
                }
            } catch (error) {
                console.error('Error checking for existing order:', error);
            }

            console.log('Opening order modal for table:', tableNumber, 'with ID:', tableId, 'isExisting:', currentOrderData.isExistingOrder, 'orderStatus:', orderStatus);

            document.getElementById('orderTableNumber').textContent = tableNumber;
            document.getElementById('itemsCount').textContent = '0';
            document.getElementById('totalAmount').textContent = '₹ 0';

            // Update button visibility and text
            const submitBtn = document.getElementById('submitOrderBtn');
            const sendToKitchenBtn = document.getElementById('sendToKitchenBtn');
            const generateBillBtn = document.getElementById('generateBillBtn');

            if ((orderStatus === 'completed' || orderStatus === 'ready') && currentOrderData.isExistingOrder) {
                // Existing order that is ready/completed - still allow adding more items
                currentOrderData.initialKitchenSent = true; // Items have been sent
                submitBtn.textContent = 'Add Items';
                submitBtn.style.backgroundColor = '#28a745';
                submitBtn.style.display = 'block';
                // Keep button ENABLED for auto-send of new items
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = false;
                sendToKitchenBtn.style.opacity = '1';
                sendToKitchenBtn.style.cursor = 'pointer';
                sendToKitchenBtn.style.backgroundColor = '#ff6b35';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-check-circle"></i> Send to Kitchen is Enabled';
                generateBillBtn.style.display = 'none';
            } else if (orderStatus === 'completed') {
                // Order has been completed - show bill and option to start new order
                currentOrderData.initialKitchenSent = true; // Items have been sent
                submitBtn.style.display = 'none';
                // Keep button ENABLED for reference, but don't need to click it
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = false;
                sendToKitchenBtn.style.opacity = '0.7';
                sendToKitchenBtn.style.cursor = 'default';
                sendToKitchenBtn.style.backgroundColor = '';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                generateBillBtn.style.display = 'block';
                generateBillBtn.textContent = '📄 View Bill / Start New Order';
            } else if (orderStatus === 'ready') {
                // Order is ready - show bill generation button
                currentOrderData.initialKitchenSent = true; // Items have been sent
                submitBtn.style.display = 'none';
                // Keep button ENABLED for reference, but don't need to click it
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = false;
                sendToKitchenBtn.style.opacity = '0.7';
                sendToKitchenBtn.style.cursor = 'default';
                sendToKitchenBtn.style.backgroundColor = '';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                generateBillBtn.style.display = 'block';
            } else if (currentOrderData.isExistingOrder && orderStatus === 'pending') {
                // Existing order that hasn't been sent to kitchen yet
                currentOrderData.kitchenSent = false; // Items NOT sent yet
                submitBtn.textContent = 'Add Items';
                submitBtn.style.backgroundColor = '#28a745';
                submitBtn.style.display = 'block';
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = false;
                sendToKitchenBtn.style.opacity = '1';
                sendToKitchenBtn.style.cursor = 'pointer';
                sendToKitchenBtn.style.backgroundColor = '';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                generateBillBtn.style.display = 'none';
            } else if (currentOrderData.isExistingOrder) {
                // Existing order that has been sent to kitchen
                currentOrderData.initialKitchenSent = true; // Items have been sent
                submitBtn.textContent = 'Add Items';
                submitBtn.style.backgroundColor = '#28a745';
                submitBtn.style.display = 'block';
                // Keep button ENABLED for auto-send of new items
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = false;
                sendToKitchenBtn.style.opacity = '1';
                sendToKitchenBtn.style.cursor = 'pointer';
                sendToKitchenBtn.style.backgroundColor = '#ff6b35';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-check-circle"></i> Send to Kitchen is Enabled';
                generateBillBtn.style.display = 'none';
            } else {
                // New order
                submitBtn.textContent = 'Place Order';
                submitBtn.style.backgroundColor = '#d4a574';
                submitBtn.style.display = 'block';
                sendToKitchenBtn.style.display = 'block';
                sendToKitchenBtn.disabled = true;
                sendToKitchenBtn.style.opacity = '0.5';
                sendToKitchenBtn.style.cursor = 'not-allowed';
                sendToKitchenBtn.style.backgroundColor = '';
                sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                generateBillBtn.style.display = 'none';
            }

            // Show modal
            document.getElementById('orderModal').classList.add('show');

            // Fetch menu data
            await loadMenuItems();
        }

        // Load menu items from API
        async function loadMenuItems() {
            try {
                const response = await fetch('../backend/menu_api.php?action=get_menu');
                const data = await response.json();

                console.log('Menu API Response:', data);

                if (!data.success) {
                    Swal.fire('Error', 'Failed to load menu', 'error');
                    closeOrderModal();
                    return;
                }

                console.log('Menu data received with', data.data.length, 'categories');
                data.data.forEach((cat, idx) => {
                    console.log(`Category ${idx}:`, cat.filter_name, 'has', cat.subcategories?.length, 'subcategories');
                    if (cat.subcategories) {
                        cat.subcategories.forEach((subcat, subidx) => {
                            console.log(`  Subcategory ${subidx}:`, subcat.subcategory_name, 'has', subcat.items?.length, 'items');
                            if (subcat.items && subcat.items.length > 0) {
                                const firstItem = subcat.items[0];
                                console.log(`    First item: ${firstItem.item_name}, image_path:`, firstItem.image_path);
                            }
                        });
                    }
                });

                currentOrderData.menu = data.data;
                renderMenuInterface(data.data);

                // If this is an existing order, populate the items after menu is rendered
                if (currentOrderData.isExistingOrder && currentOrderData.items.length > 0) {
                    populateExistingItems();
                }
            } catch (error) {
                console.error('Error loading menu:', error);
                Swal.fire('Error', 'Failed to load menu. Please try again.', 'error');
                closeOrderModal();
            }
        }

        // Remove/Cancel order
        async function removeOrder(orderId, tableNumber) {
            Swal.fire({
                title: 'Remove Order?',
                text: `Are you sure you want to remove the order for Table ${tableNumber}? This action cannot be undone.`,
                icon: 'warning',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Remove Order',
                cancelButtonText: 'Cancel'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_remove_order.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                order_id: orderId
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Order removed successfully',
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                // Reload tables to refresh the UI
                                loadAssignedTables();
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to remove order', 'error');
                        }
                    } catch (error) {
                        console.error('Error removing order:', error);
                        Swal.fire('Error', 'Failed to remove order. Please try again.', 'error');
                    }
                }
            });
        }

        // Remove specific item from existing order
        async function removeExistingItem(itemId, itemName) {
            Swal.fire({
                title: 'Remove Item?',
                text: `Remove ${itemName} from the order?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Remove'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_remove_order_item.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                order_id: currentOrderData.orderId,
                                item_id: itemId
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            // Remove item from local data
                            currentOrderData.items = currentOrderData.items.filter(item => item.id !== itemId);
                            currentOrderData.existingItemIds = currentOrderData.existingItemIds.filter(id => id !== itemId);

                            // Update UI
                            updateOrderSummary();
                            renderSelectedItems();

                            Swal.fire({
                                title: 'Success!',
                                text: `${itemName} removed from order`,
                                icon: 'success',
                                timer: 1500,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to remove item', 'error');
                        }
                    } catch (error) {
                        console.error('Error removing item:', error);
                        Swal.fire('Error', 'Failed to remove item. Please try again.', 'error');
                    }
                }
            });
        }

        // Toggle item served status
        async function toggleItemServed(itemIndex) {
            if (itemIndex >= 0 && itemIndex < currentOrderData.items.length) {
                const item = currentOrderData.items[itemIndex];
                const newServedStatus = !item.served;

                try {
                    // Update status on backend - send row_id for specific row updates (reorder handling)
                    const response = await fetch('../backend/server_update_item_served_status.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            order_id: currentOrderData.orderId,
                            item_id: item.id,
                            row_id: item.row_id,
                            served: newServedStatus
                        })
                    });

                    const data = await response.json();

                    if (data.success) {
                        // Update local state only after successful backend update
                        item.served = newServedStatus;

                        const status = newServedStatus ? 'Served' : 'Not Served';

                        Swal.fire({
                            title: 'Status Updated',
                            text: `${item.name} marked as ${status}`,
                            icon: 'success',
                            timer: 1000,
                            showConfirmButton: false,
                            toast: true,
                            position: 'top-end'
                        });

                        renderSelectedItems();
                        updateOrderSummary();
                        
                        // Update completed orders count immediately
                        updateOrderStats();
                    } else {
                        Swal.fire('Error', data.message || 'Failed to update status', 'error');
                    }
                } catch (error) {
                    console.error('Error updating item status:', error);
                    Swal.fire('Error', 'Failed to update item status. Please try again.', 'error');
                }
            }
        }


        // Update quantity of existing order item
        async function updateExistingItemQuantity(itemIndex, itemId, newQuantity) {
            // Validate quantity
            if (newQuantity < 0) {
                Swal.fire('Warning', 'Quantity cannot be negative', 'warning');
                return;
            }

            // Get the item to find its name
            const item = currentOrderData.items[itemIndex];
            const itemName = item.name;

            console.log('Updating item quantity:', {
                itemIndex: itemIndex,
                itemId: itemId,
                oldQuantity: item.quantity,
                newQuantity: newQuantity,
                itemName: itemName
            });

            try {
                const response = await fetch('../backend/server_update_order_item_quantity.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        order_id: currentOrderData.orderId,
                        item_id: itemId,
                        new_quantity: newQuantity
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // Update item in local data
                    if (newQuantity === 0) {
                        // Remove item if quantity is 0
                        currentOrderData.items = currentOrderData.items.filter(item => item.id !== itemId);
                        currentOrderData.existingItemIds = currentOrderData.existingItemIds.filter(id => id !== itemId);

                        Swal.fire({
                            title: 'Success!',
                            text: `${itemName} removed from order`,
                            icon: 'success',
                            timer: 1200,
                            showConfirmButton: false
                        });
                    } else {
                        // Update quantity for the item
                        currentOrderData.items[itemIndex].quantity = newQuantity;

                        console.log('Item quantity updated:', newQuantity);
                    }

                    // Update UI
                    updateOrderSummary();
                    renderSelectedItems();

                } else {
                    Swal.fire('Error', data.message || 'Failed to update quantity', 'error');
                    // Re-render to reset the UI to last known good state
                    renderSelectedItems();
                }
            } catch (error) {
                console.error('Error updating quantity:', error);
                Swal.fire('Error', 'Failed to update quantity. Please try again.', 'error');
                renderSelectedItems();
            }
        }

        // Populate existing items from previous order
        function populateExistingItems() {
            console.log('Populating existing items:', currentOrderData.items);

            // Build items array with information from backend
            // The backend now provides item_name and status, so we use those
            const fullyPopulatedItems = [];
            const existingIds = [];

            currentOrderData.items.forEach(existingItem => {
                // Try to get price information from the menu if available
                let itemDetails = null;
                let unitPrice = parseFloat(existingItem.unit_price || 0);

                // Search in menu for price and any other details
                if (currentOrderData.menu) {
                    for (let category of currentOrderData.menu) {
                        if (category.subcategories) {
                            for (let subcat of category.subcategories) {
                                if (subcat.items) {
                                    const found = subcat.items.find(item => parseInt(item.item_id) === parseInt(existingItem.id));
                                    if (found) {
                                        itemDetails = found;
                                        if (!unitPrice) {
                                            unitPrice = parseFloat(found.price);
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                        if (itemDetails) break;
                    }
                }

                // Use name from backend or from menu
                const itemName = existingItem.name || (itemDetails ? itemDetails.item_name : 'Unknown Item');

                fullyPopulatedItems.push({
                    row_id: parseInt(existingItem.row_id) || null,
                    id: parseInt(existingItem.id),
                    name: itemName,
                    price: unitPrice || (itemDetails ? parseFloat(itemDetails.price) : 0),
                    quantity: parseInt(existingItem.quantity),
                    originalQuantity: parseInt(existingItem.quantity),
                    isExisting: true,
                    isReordered: existingItem.is_reorder || false,
                    served: existingItem.served, // Use actual database status without forcing reordered items to false
                    status: existingItem.status // Track actual status for reference (pending, preparing, ready, served)
                });
                existingIds.push(parseInt(existingItem.id));
            });

            // Update the current order with fully populated items
            currentOrderData.items = fullyPopulatedItems;
            currentOrderData.existingItemIds = existingIds;

            console.log('Existing items loaded:', currentOrderData.items);
            console.log('Existing item IDs:', currentOrderData.existingItemIds);

            // Update the UI
            updateOrderSummary();
            renderSelectedItems();
        }

        // Render menu interface with category tabs and items
        function renderMenuInterface(menu) {
            if (!menu || menu.length === 0) {
                document.getElementById('categoryTabsContainer').innerHTML = '<p>No menu available</p>';
                document.getElementById('menuItemsContainer').innerHTML = '<p>No items available</p>';
                return;
            }

            // Render category tabs using data attributes
            const tabsHTML = menu.map((category, index) => `
                <button class="category-tab ${index === 0 ? 'active' : ''}" 
                    data-category-index="${index}">
                    ${category.filter_name}
                </button>
            `).join('');

            const tabsContainer = document.getElementById('categoryTabsContainer');
            tabsContainer.innerHTML = tabsHTML;

            // Add event listeners to category tabs
            tabsContainer.querySelectorAll('.category-tab').forEach(button => {
                button.addEventListener('click', function() {
                    const index = parseInt(this.dataset.categoryIndex);
                    selectCategory(index, currentOrderData.menu[index].filter_name);
                });
            });

            // Render first category items
            if (menu.length > 0) {
                selectCategory(0, menu[0].filter_name);
            }
        }

        // Select and display items for a category
        function selectCategory(categoryIndex, categoryName) {
            currentOrderData.currentCategory = categoryIndex;

            // Update active tab
            document.querySelectorAll('.category-tab').forEach((tab, idx) => {
                tab.classList.toggle('active', idx === categoryIndex);
            });

            const category = currentOrderData.menu[categoryIndex];
            if (!category || !category.subcategories) return;

            // Render subcategories and items using data attributes
            let itemsHTML = '';

            category.subcategories.forEach(subcategory => {
                itemsHTML += `
                    <div class="subcategory-section">
                        <h3 class="subcategory-name">${subcategory.subcategory_name}</h3>
                        <div class="items-grid">
                `;

                if (subcategory.items && subcategory.items.length > 0) {
                    subcategory.items.forEach(item => {
                        // Construct proper image path
                        let itemImage = 'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22300%22 height=%22200%22%3E%3Crect fill=%22%23e9ecef%22 width=%22300%22 height=%22200%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 font-family=%22Arial%22 font-size=%2214%22 fill=%22%23999%22 text-anchor=%22middle%22 dy=%22.3em%22%3ENo Image%3C/text%3E%3C/svg%3E';

                        if (item.image_path) {
                            let cleanPath = item.image_path.trim();

                            // Check if path already starts with various prefixes
                            if (cleanPath.startsWith('http://') || cleanPath.startsWith('https://')) {
                                // Already a full URL
                                itemImage = cleanPath;
                            } else if (cleanPath.startsWith('assets/uploads/')) {
                                // Already has assets/uploads prefix, just prepend ../
                                itemImage = '../' + cleanPath;
                            } else if (cleanPath.startsWith('/assets/uploads/')) {
                                // Has full path with leading slash
                                itemImage = '..' + cleanPath;
                            } else {
                                // Just a filename, add full path
                                itemImage = `../assets/uploads/${cleanPath}`;
                            }

                            console.log('Item image URL for', item.item_name, ':', itemImage, '(original:', item.image_path + ')');
                        } else {
                            console.warn('No image_path for item:', item.item_name);
                        }
                        const price = parseFloat(item.price) || 0;

                        itemsHTML += `
                            <div class="menu-item-card" data-item-id="${item.item_id}" data-item-name="${item.item_name}" data-item-price="${price}" data-item-image="${itemImage}" data-item-description="${item.description || ''}">
                                <div class="item-image-wrapper">
                                    <img src="${itemImage}" alt="${item.item_name}" class="item-image" onerror="this.onerror=null; this.src='data:image/svg+xml,%3Csvg xmlns=&quot;http://www.w3.org/2000/svg&quot; width=&quot;300&quot; height=&quot;200&quot;%3E%3Crect fill=&quot;%23e9ecef&quot; width=&quot;300&quot; height=&quot;200&quot;/%3E%3Ctext x=&quot;50%25&quot; y=&quot;50%25&quot; font-family=&quot;Arial&quot; font-size=&quot;14&quot; fill=&quot;%23999&quot; text-anchor=&quot;middle&quot; dy=&quot;.3em&quot;%3ENo Image%3C/text%3E%3C/svg%3E'">
                                </div>
                                <div class="item-info">
                                    <h4 class="item-name">${item.item_name}</h4>
                                    <p class="item-description">${item.description || ''}</p>
                                    <div class="item-footer">
                                        <span class="item-price">₹ ${price.toFixed(2)}</span>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    itemsHTML += '<p class="no-items">No items available</p>';
                }

                itemsHTML += `
                        </div>
                    </div>
                `;
            });

            const menuContainer = document.getElementById('menuItemsContainer');
            menuContainer.innerHTML = itemsHTML;

            // Add event listeners to item cards - use event delegation to prevent duplicate listeners
            menuContainer.querySelectorAll('.menu-item-card').forEach(card => {
                // Remove any existing listeners by cloning and replacing
                const newCard = card.cloneNode(true);
                card.parentNode.replaceChild(newCard, card);
            });

            // Now add single listener with event delegation
            menuContainer.querySelectorAll('.menu-item-card').forEach(card => {
                card.addEventListener('click', function() {
                    addItemDirectly(
                        this.dataset.itemId,
                        this.dataset.itemName,
                        this.dataset.itemPrice
                    );
                });
            });
        }

        function addItemDirectly(itemId, itemName, itemPrice) {
            // Debounce: prevent duplicate clicks within 300ms
            const now = Date.now();
            if (now - lastItemAddTime < 300) {
                console.log('Debounced - click too soon');
                return;
            }
            lastItemAddTime = now;

            itemId = parseInt(itemId);
            itemPrice = parseFloat(itemPrice);

            console.log('addItemDirectly called:', {
                itemId,
                itemName,
                itemPrice,
                currentItems: currentOrderData.items.map(i => ({
                    id: i.id,
                    qty: i.quantity
                }))
            });

            // Check if item already in order
            const existingItem = currentOrderData.items.find(item => item.id === itemId);

            if (existingItem) {
                console.log('Item exists - OLD qty:', existingItem.quantity, 'Adding 1');
                // Store original quantity if not already marked as reordered
                if (!existingItem.isReordered) {
                    existingItem.originalQuantity = existingItem.quantity;
                }
                existingItem.quantity += 1;
                console.log('Item exists - NEW qty:', existingItem.quantity);
                // IMPORTANT: Mark item as modified (not "existing" anymore) so it gets sent to backend
                // Track original quantity to calculate the actual increment when submitting
                existingItem.isExisting = false;
                existingItem.isReordered = true; // Flag to indicate this is a reorder
            } else {
                console.log('New item - adding with qty 1');
                currentOrderData.items.push({
                    id: itemId,
                    name: itemName,
                    price: itemPrice,
                    quantity: 1,
                    isExisting: false, // Mark as new item
                    isReordered: false
                });
            }

            console.log('After add - items:', currentOrderData.items.map(i => ({
                id: i.id,
                qty: i.quantity,
                isReordered: i.isReordered
            })));

            // Do NOT re-enable Send to Kitchen button - user must click "Add Items" first
            // This prevents error "Order is already sent to kitchen"
            // Correct workflow: Add Items -> Click "Add Items" button -> Items submitted -> Then Send to Kitchen becomes enabled

            updateOrderSummary();
            renderSelectedItems();

            // Show toast notification
            Swal.fire({
                title: 'Added!',
                text: `${itemName} added to order`,
                icon: 'success',
                timer: 1200,
                showConfirmButton: false,
                position: 'top-end',
                toast: true
            });
        }

        // Open item detail modal
        function openItemDetail(itemId, itemName, price, image, description) {
            itemId = parseInt(itemId);
            price = parseFloat(price);

            selectedItem.id = itemId;
            selectedItem.name = itemName;
            selectedItem.price = price;
            selectedItem.image = image;
            selectedItem.quantity = 1;

            document.getElementById('itemDetailName').textContent = itemName;
            document.getElementById('itemDetailDescription').textContent = description || '';
            document.getElementById('itemDetailPrice').textContent = '₹ ' + price.toFixed(2);
            document.getElementById('itemDetailImage').src = image;
            document.getElementById('itemQuantity').value = 1;

            document.getElementById('itemDetailModal').style.display = 'block';
        }

        // Close item detail modal
        function closeItemDetail() {
            document.getElementById('itemDetailModal').style.display = 'none';
            selectedItem.quantity = 1;
        }

        // Increase quantity
        function increaseQuantity() {
            const input = document.getElementById('itemQuantity');
            const current = parseInt(input.value) || 1;
            if (current < 50) {
                input.value = current + 1;
            }
        }

        // Decrease quantity
        function decreaseQuantity() {
            const input = document.getElementById('itemQuantity');
            const current = parseInt(input.value) || 1;
            if (current > 1) {
                input.value = current - 1;
            }
        }

        // Add item to order
        function addItemToOrder() {
            const quantity = parseInt(document.getElementById('itemQuantity').value) || 1;

            // Check if item already in order
            const existingItem = currentOrderData.items.find(item => item.id === selectedItem.id);

            if (existingItem) {
                // Store original quantity if not already marked as reordered
                if (!existingItem.isReordered) {
                    existingItem.originalQuantity = existingItem.quantity;
                }
                existingItem.quantity += quantity;
                // IMPORTANT: Mark item as modified (not "existing" anymore) so it gets sent to backend
                existingItem.isExisting = false;
                existingItem.isReordered = true;
            } else {
                currentOrderData.items.push({
                    id: selectedItem.id,
                    name: selectedItem.name,
                    price: selectedItem.price,
                    image: selectedItem.image,
                    quantity: quantity,
                    isExisting: false, // Mark as new item
                    isReordered: false,
                    served: false // Track if item has been served
                });
            }

            // Do NOT re-enable Send to Kitchen button - user must click "Add Items" first
            // This prevents error "Order is already sent to kitchen"
            // Correct workflow: Add Items -> Click "Add Items" button -> Items submitted -> Then Send to Kitchen becomes enabled

            updateOrderSummary();
            renderSelectedItems();
            closeItemDetail();

            // Show toast notification
            Swal.fire({
                title: 'Added!',
                text: `${selectedItem.name} added to order`,
                icon: 'success',
                timer: 1500,
                showConfirmButton: false,
                position: 'top-end',
                toast: true
            });
        }

        // Render selected items in the right section
        function renderSelectedItems() {
            const selectedItemsList = document.getElementById('selectedItemsList');

            // Separate existing and new items
            const existingItems = currentOrderData.items.filter(item => item.isExisting);
            const newItems = currentOrderData.items.filter(item => !item.isExisting);

            console.log('Rendering items - Existing:', existingItems.length, 'New:', newItems.length);

            let itemsHTML = '';

            // Show existing items (editable now)
            if (existingItems.length > 0) {
                itemsHTML += '<div class="existing-items-section"><h4 style="color: #17a2b8; margin-bottom: 10px;"><i class="fas fa-info-circle"></i> Already Ordered Items (Edit Quantity)</h4>';
                existingItems.forEach((item, index) => {
                    const itemTotal = (item.price * item.quantity).toFixed(2);
                    const itemIndex = currentOrderData.items.indexOf(item);

                    // Get actual status from database (pending, preparing, ready, served)
                    const actualStatus = item.status || (item.served ? 'served' : 'pending');
                    let statusColor, statusIcon, statusText;

                    switch (actualStatus) {
                        case 'served':
                            statusColor = '#4caf50';
                            statusIcon = 'fa-check-circle';
                            statusText = 'Served';
                            break;
                        case 'ready':
                            statusColor = '#2196f3';
                            statusIcon = 'fa-check';
                            statusText = 'Ready';
                            break;
                        case 'preparing':
                            statusColor = '#ff9800';
                            statusIcon = 'fa-hourglass-half';
                            statusText = 'Preparing';
                            break;
                        case 'pending':
                        default:
                            statusColor = '#9c27b0';
                            statusIcon = 'fa-clock';
                            statusText = 'Pending';
                    }

                    const statusBadge = `<span style="background: ${statusColor}; color: white; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: bold;"><i class="fas ${statusIcon}"></i> ${statusText}</span>`;

                    itemsHTML += `
                        <div class="selected-item-row existing-item-row" style="display: flex; justify-content: space-between; align-items: flex-start; background: ${actualStatus === 'served' ? '#e8f5e9' : '#e8f4f8'}; padding: 10px; border-radius: 4px; margin-bottom: 8px; border-left: 3px solid ${actualStatus === 'served' ? '#4caf50' : '#17a2b8'};">
                            <div class="item-row-info" style="flex: 1;">
                                <div class="item-row-name" style="display: flex; justify-content: space-between; align-items: center;">
                                    <span>${item.name}${item.isReordered ? ' <span style="font-size: 10px; color: #ff9800; font-weight: bold;">[REORDER]</span>' : ''}</span>
                                    ${statusBadge}
                                </div>
                                <div class="item-row-price">₹ ${item.price.toFixed(2)}</div>
                            </div>
                            <div class="item-controls" style="display: flex; gap: 6px; align-items: center;">
                                <div style="display: flex; gap: 3px; align-items: center; background: white; padding: 4px 6px; border-radius: 3px; border: 1px solid #17a2b8;">
                                    <button class="qty-adjust-btn" onclick="updateExistingItemQuantity(${itemIndex}, ${item.id}, ${item.quantity - 1})" style="background: transparent; border: none; cursor: pointer; color: #17a2b8; font-size: 14px; padding: 0 4px;">−</button>
                                    <span class="qty-display" style="min-width: 25px; text-align: center; font-weight: bold;">${item.quantity}</span>
                                    <button class="qty-adjust-btn" onclick="updateExistingItemQuantity(${itemIndex}, ${item.id}, ${item.quantity + 1})" style="background: transparent; border: none; cursor: pointer; color: #17a2b8; font-size: 14px; padding: 0 4px;">+</button>
                                </div>
                                <span class="item-row-total" style="min-width: 50px; text-align: right; font-weight: bold;">₹ ${itemTotal}</span>
                                <button class="item-remove-btn" onclick="reorderExistingItem(${itemIndex})" title="Reorder this item" style="background-color: #ff9800; color: white; border: none; padding: 6px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                                    <i class="fas fa-plus"></i>
                                </button>
                                <button class="item-remove-btn" onclick="toggleItemServed(${itemIndex})" title="${actualStatus === 'served' ? 'Mark as Pending' : 'Mark as Served'}" style="background-color: ${actualStatus === 'served' ? '#4caf50' : '#ff9800'}; color: white; border: none; padding: 6px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                                    <i class="fas ${actualStatus === 'served' ? 'fa-check' : 'fa-clock'}"></i>
                                </button>
                                <button class="item-remove-btn" onclick="removeExistingItem(${item.id}, '${item.name}')" title="Remove item" style="background-color: #dc3545; color: white; border: none; padding: 6px 8px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </div>
                    `;
                });
                itemsHTML += '</div>';
            }

            // Show new items (editable)
            if (newItems.length > 0) {
                // Separate new items and reordered items
                const reorderedItems = newItems.filter(item => item.isReordered);
                const brandNewItems = newItems.filter(item => !item.isReordered);

                if (existingItems.length > 0) {
                    itemsHTML += '<div class="new-items-section" style="margin-top: 15px; border-top: 1px solid #eee; padding-top: 10px;">';

                    // Show reordered items
                    if (reorderedItems.length > 0) {
                        itemsHTML += '<h4 style="color: #ff9800; margin-bottom: 10px;">Additional Quantity</h4>';
                        reorderedItems.forEach((item, index) => {
                            const originalIndex = currentOrderData.items.indexOf(item);
                            const additionalQty = item.quantity - item.originalQuantity;
                            const additionalTotal = (item.price * additionalQty).toFixed(2);
                            const currentTotal = (item.price * item.quantity).toFixed(2);

                            itemsHTML += `
                                <div class="selected-item-row reordered-item" data-item-index="${originalIndex}" style="background-color: #fff3e0; border-left: 3px solid #ff9800; padding: 10px;">
                                    <div class="item-row-info">
                                        <div class="item-row-name">${item.name} <span style="font-size: 11px; color: #ff9800; font-weight: bold;">[Reorder]</span></div>
                                        <div class="item-row-price">₹ ${item.price.toFixed(2)}</div>
                                        <div style="font-size: 12px; color: #666; margin-top: 4px;">Current: ${item.originalQuantity} | Adding: +${additionalQty} | Total: ${item.quantity}</div>
                                    </div>
                                    <div class="item-controls" style="flex-shrink: 0;">
                                        <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, -1)">−</button>
                                        <span class="qty-display">${additionalQty}</span>
                                        <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, 1)">+</button>
                                    </div>
                                    <div class="item-row-total" style="min-width: 80px; text-align: right;">
                                        <div style="font-size: 12px; color: #666;">Add: ₹ ${additionalTotal}</div>
                                    </div>
                                    <button class="item-remove-btn" onclick="removeItemFromOrder(${originalIndex})" title="Remove item">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </div>
                            `;
                        });
                    }

                    // Show new items
                    if (brandNewItems.length > 0) {
                        itemsHTML += '<h4 style="color: #333; margin-bottom: 10px; margin-top: 12px;">New Items to Add</h4>';
                        brandNewItems.forEach((item, index) => {
                            const originalIndex = currentOrderData.items.indexOf(item);
                            const itemTotal = (item.price * item.quantity).toFixed(2);
                            itemsHTML += `
                                <div class="selected-item-row" data-item-index="${originalIndex}">
                                    <div class="item-row-info">
                                        <div class="item-row-name">${item.name}</div>
                                        <div class="item-row-price">₹ ${item.price.toFixed(2)}</div>
                                    </div>
                                    <div class="item-controls">
                                        <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, -1)">−</button>
                                        <span class="qty-display">${item.quantity}</span>
                                        <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, 1)">+</button>
                                    </div>
                                    <div class="item-row-total">₹ ${itemTotal}</div>
                                    <button class="item-remove-btn" onclick="removeItemFromOrder(${originalIndex})" title="Remove item">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </div>
                            `;
                        });
                    }

                    itemsHTML += '</div>';
                } else {
                    // No existing items, show all new items normally
                    itemsHTML += '<div class="new-items-section"><h4 style="color: #333; margin-bottom: 10px;">Items to Add</h4>';

                    newItems.forEach((item, index) => {
                        const originalIndex = currentOrderData.items.indexOf(item);
                        const itemTotal = (item.price * item.quantity).toFixed(2);
                        itemsHTML += `
                            <div class="selected-item-row" data-item-index="${originalIndex}">
                                <div class="item-row-info">
                                    <div class="item-row-name">${item.name}</div>
                                    <div class="item-row-price">₹ ${item.price.toFixed(2)}</div>
                                </div>
                                <div class="item-controls">
                                    <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, -1)">−</button>
                                    <span class="qty-display">${item.quantity}</span>
                                    <button class="qty-adjust-btn" onclick="adjustItemQuantity(${originalIndex}, 1)">+</button>
                                </div>
                                <div class="item-row-total">₹ ${itemTotal}</div>
                                <button class="item-remove-btn" onclick="removeItemFromOrder(${originalIndex})" title="Remove item">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        `;
                    });

                    itemsHTML += '</div>';
                }
            } else if (existingItems.length === 0) {
                itemsHTML = '<p class="empty-order-message">No items selected yet</p>';
            } else {
                itemsHTML += '<p style="color: #999; font-size: 13px; margin-top: 10px;">Click menu items above to add new items</p>';
            }

            selectedItemsList.innerHTML = itemsHTML;
        }

        // Adjust item quantity in the order
        function adjustItemQuantity(index, change) {
            if (index >= 0 && index < currentOrderData.items.length) {
                const item = currentOrderData.items[index];

                // Prevent adjusting existing items
                if (item.isExisting) {
                    Swal.fire('Cannot Adjust', 'You cannot adjust quantities for already ordered items.', 'warning');
                    return;
                }

                const newQuantity = item.quantity + change;
                if (newQuantity >= 1 && newQuantity <= 50) {
                    item.quantity = newQuantity;
                    updateOrderSummary();
                    renderSelectedItems();
                } else if (newQuantity < 1) {
                    removeItemFromOrder(index);
                }
            }
        }

        // Remove item from order
        function removeItemFromOrder(index) {
            if (index >= 0 && index < currentOrderData.items.length) {
                const item = currentOrderData.items[index];

                // Prevent removing existing items
                if (item.isExisting) {
                    Swal.fire('Cannot Remove', 'You cannot remove items that are already ordered. Edit quantities only.', 'warning');
                    return;
                }

                const itemName = item.name;
                currentOrderData.items.splice(index, 1);
                updateOrderSummary();
                renderSelectedItems();

                Swal.fire({
                    title: 'Removed',
                    text: `${itemName} removed from order`,
                    icon: 'info',
                    timer: 1200,
                    showConfirmButton: false,
                    position: 'top-end',
                    toast: true
                });
            }
        }

        // Add one extra quantity as a reorder for an already ordered item.
        // Works even if the item is no longer in the live menu list.
        function reorderExistingItem(index) {
            if (index < 0 || index >= currentOrderData.items.length) {
                return;
            }

            const item = currentOrderData.items[index];
            if (!item || !item.isExisting) {
                Swal.fire('Warning', 'Only existing items can be reordered from this list.', 'warning');
                return;
            }

            if (!item.isReordered) {
                item.originalQuantity = item.quantity;
            }

            item.quantity += 1;
            item.isExisting = false;
            item.isReordered = true;

            updateOrderSummary();
            renderSelectedItems();

            Swal.fire({
                title: 'Reorder Added',
                text: `${item.name} added as reorder`,
                icon: 'success',
                timer: 1200,
                showConfirmButton: false,
                position: 'top-end',
                toast: true
            });
        }

        // Update order summary display
        function updateOrderSummary() {
            // Separate existing and new items
            const existingItems = currentOrderData.items.filter(item => item.isExisting);
            const newItems = currentOrderData.items.filter(item => !item.isExisting);

            // Calculate totals
            let existingTotal = 0;
            existingItems.forEach(item => {
                existingTotal += item.price * item.quantity;
            });

            let newTotal = 0;
            newItems.forEach(item => {
                newTotal += item.price * item.quantity;
            });

            const overallTotal = existingTotal + newTotal;

            // Update item count (only count new items)
            document.getElementById('itemsCount').textContent = newItems.length;

            // Update totals display
            document.getElementById('existingTotal').textContent = '₹ ' + existingTotal.toFixed(2);
            document.getElementById('newTotal').textContent = '₹ ' + newTotal.toFixed(2);
            document.getElementById('totalAmount').textContent = '₹ ' + overallTotal.toFixed(2);

            // Show/hide rows based on whether we have existing items
            document.getElementById('existingTotalRow').style.display = existingItems.length > 0 ? 'flex' : 'none';
            document.getElementById('newTotalRow').style.display = existingItems.length > 0 && newItems.length > 0 ? 'flex' : 'none';

            // Show/hide kitchen status notice if items have been sent to kitchen
            const kitchenNotice = document.getElementById('kitchenStatusNotice');
            kitchenNotice.style.display = currentOrderData.initialKitchenSent ? 'block' : 'none';

            // Update overall total row styling based on context
            const overallTotalRow = document.getElementById('overallTotalRow');
            if (existingItems.length > 0 && newItems.length > 0) {
                overallTotalRow.style.borderTop = '1px solid #ddd';
                overallTotalRow.style.paddingTop = '10px';
                overallTotalRow.style.marginTop = '10px';
                overallTotalRow.style.fontWeight = 'bold';
            } else {
                overallTotalRow.style.borderTop = 'none';
                overallTotalRow.style.paddingTop = '0';
                overallTotalRow.style.marginTop = '0';
                overallTotalRow.style.fontWeight = 'normal';
            }

            // Show/hide Send to Manager button when order has items and has been sent to kitchen
            const sendToManagerBtn = document.getElementById('sendToManagerBtn');
            if (currentOrderData.initialKitchenSent && currentOrderData.items.length > 0) {
                sendToManagerBtn.style.display = 'block';
                sendToManagerBtn.disabled = false;
                sendToManagerBtn.style.opacity = '1';
                sendToManagerBtn.style.cursor = 'pointer';
            } else {
                sendToManagerBtn.style.display = 'none';
                sendToManagerBtn.disabled = true;
                sendToManagerBtn.style.opacity = '0.5';
                sendToManagerBtn.style.cursor = 'not-allowed';
            }

            // Render the items list as well  
            renderSelectedItems();

            console.log('Order summary updated - Existing:', existingItems.length, existingTotal.toFixed(2), 'New:', newItems.length, newTotal.toFixed(2), 'Total:', overallTotal.toFixed(2));
        }

        // Submit order (new or add items to existing)
        async function submitOrder() {
            // Validate data before submission
            if (!currentOrderData.tableId || isNaN(currentOrderData.tableId)) {
                console.error('Invalid table ID:', currentOrderData.tableId);
                Swal.fire('Error', 'Invalid table ID. Please try again.', 'error');
                return;
            }

            // Ensure all items have isExisting property (defensive)
            currentOrderData.items.forEach(item => {
                if (item.isExisting === undefined) {
                    item.isExisting = false;
                }
                if (item.isReordered === undefined) {
                    item.isReordered = false;
                }
            });

            console.log('SubmitOrder called - isExistingOrder:', currentOrderData.isExistingOrder, 'orderId:', currentOrderData.orderId, 'items:', currentOrderData.items.length);

            // For new orders, check all items
            // For existing orders, check only new items
            const itemsToCheck = currentOrderData.isExistingOrder ?
                currentOrderData.items.filter(item => !item.isExisting) :
                currentOrderData.items;

            if (itemsToCheck.length === 0) {
                Swal.fire('Warning', 'Please add at least one item to the order', 'warning');
                return;
            }

            // Log order data for debugging
            console.log('Order data:', {
                table_id: currentOrderData.tableId,
                items_count: itemsToCheck.length,
                items: itemsToCheck,
                isExistingOrder: currentOrderData.isExistingOrder,
                orderId: currentOrderData.orderId,
                existingItemIds: currentOrderData.existingItemIds
            });

            const actionText = currentOrderData.isExistingOrder ? 'Add items to' : 'Place';
            const confirmText = currentOrderData.isExistingOrder ? 'Yes, Add Items' : 'Place Order';

            Swal.fire({
                title: 'Confirm Order',
                text: `${actionText} order for Table ${currentOrderData.tableNumber} with ${itemsToCheck.length} item(s)?`,
                icon: 'question',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#6c757d',
                confirmButtonText: confirmText
            }).then(async (result) => {
                if (result.isConfirmed) {
                    // Prepare order data
                    let endpoint;
                    let orderData;

                    if (currentOrderData.isExistingOrder) {
                        // For existing orders, send ONLY NEW ITEMS (not marked as isExisting)
                        endpoint = '../backend/server_add_items_to_order.php';

                        // Filter to get only new items
                        const newItems = currentOrderData.items
                            .filter(item => !item.isExisting)
                            .map(item => {
                                // For reordered items, calculate the actual additional quantity
                                const additionalQty = item.isReordered ?
                                    (item.quantity - item.originalQuantity) :
                                    item.quantity;

                                return {
                                    id: item.id,
                                    quantity: additionalQty,
                                    name: item.name // Include item name for reordered items
                                };
                            });

                        console.log('New items being sent to API:', newItems);
                        console.log('Existing items NOT being sent:', currentOrderData.items.filter(item => item.isExisting));

                        orderData = {
                            order_id: currentOrderData.orderId,
                            items: newItems
                        };
                    } else {
                        // Creating new order - send all items
                        endpoint = '../backend/server_create_order.php';
                        orderData = {
                            table_id: currentOrderData.tableId,
                            assignment_id: currentOrderData.assignmentId,
                            items: currentOrderData.items.map(item => ({
                                id: item.id,
                                quantity: item.quantity,
                                name: item.name // Include item name for consistency
                            }))
                        };
                    }

                    console.log(`Submitting to ${endpoint}:`, JSON.stringify(orderData));

                    try {
                        const response = await fetch(endpoint, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(orderData)
                        });

                        // First check if response is ok
                        if (!response.ok) {
                            console.error('Response status:', response.status, response.statusText);
                            Swal.fire('Error', `Server error: ${response.status} ${response.statusText}`, 'error');
                            return;
                        }

                        // Get response text first to debug
                        const responseText = await response.text();
                        console.log('Server response text:', responseText);

                        // Try to parse JSON
                        let responseData;
                        try {
                            responseData = JSON.parse(responseText);
                        } catch (jsonError) {
                            console.error('JSON parsing failed:', jsonError);
                            console.error('Response text was:', responseText);
                            Swal.fire('Error', 'Invalid response from server. Check console for details.', 'error');
                            return;
                        }

                        console.log('Parsed response data:', responseData);

                        if (responseData.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: currentOrderData.isExistingOrder ? 'Items added to order successfully' : 'Order placed successfully',
                                icon: 'success',
                                confirmButtonColor: '#d4a574'
                            }).then(() => {
                                // For new orders, store the order ID
                                if (!currentOrderData.isExistingOrder) {
                                    // Store the new order ID (nested in data object)
                                    const orderId = responseData.data?.order_id;

                                    if (!orderId) {
                                        console.error('ERROR: No order_id in response!', responseData);
                                        Swal.fire('Error', 'Order was created but missing ID. Refresh page.', 'error');
                                        return;
                                    }

                                    currentOrderData.orderId = orderId;
                                    console.log('=== New order created ===');
                                    console.log('New order ID:', currentOrderData.orderId);
                                    console.log('Items in order:', currentOrderData.items.map(i => ({
                                        id: i.id,
                                        isExisting: i.isExisting
                                    })));

                                    // DO NOT mark items as isExisting yet - they're just placed, not sent to kitchen
                                    // Track which items were part of the original placement
                                    currentOrderData.existingItemIds = currentOrderData.items.map(item => item.id);

                                    // Mark as existing order so we can add more items
                                    currentOrderData.isExistingOrder = true;

                                    // Kitchen has NOT been sent yet
                                    currentOrderData.kitchenSent = false;

                                    // Enable Send to Kitchen button since we now have an order
                                    const sendToKitchenBtn = document.getElementById('sendToKitchenBtn');
                                    sendToKitchenBtn.disabled = false;
                                    sendToKitchenBtn.style.opacity = '1';
                                    sendToKitchenBtn.style.cursor = 'pointer';
                                    sendToKitchenBtn.style.backgroundColor = '';
                                    sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                                    console.log('Send to Kitchen button ENABLED');

                                    // Update the submit button to "Add Items"
                                    const submitBtn = document.getElementById('submitOrderBtn');
                                    submitBtn.textContent = 'Add Items';
                                    submitBtn.style.backgroundColor = '#28a745';

                                    // Keep items in the array - do NOT clear them
                                    // Items stay visible for review before sending to kitchen

                                    // Update the display
                                    renderSelectedItems();
                                    updateOrderSummary();
                                } else {
                                    // For adding items to existing order
                                    console.log('=== Adding items to existing order ===');
                                    console.log('Order ID:', currentOrderData.orderId);
                                    console.log('Items before processing:', currentOrderData.items.map(i => ({
                                        id: i.id,
                                        isExisting: i.isExisting
                                    })));

                                    // Items are added successfully to the order database
                                    // BUT DO NOT mark them as isExisting yet!
                                    // They should only be marked as isExisting AFTER they're sent to kitchen
                                    // Right now they're ready to be sent, so keep isExisting = false

                                    // Keep all items in the array for display
                                    currentOrderData.items = currentOrderData.items;

                                    // DO NOT change isExisting here - items are ready to send, not yet sent
                                    console.log('Items after processing (unchanged):', currentOrderData.items.map(i => ({
                                        id: i.id,
                                        isExisting: i.isExisting
                                    })));

                                    // NOW enable the Send to Kitchen button if there are new items to send
                                    const sendToKitchenBtn = document.getElementById('sendToKitchenBtn');

                                    // Items that were just added still have isExisting = false - they're ready to send
                                    const newItemsToSend = currentOrderData.items.filter(item => {
                                        return item.isExisting === false; // Items ready to send to kitchen
                                    });

                                    console.log('After adding items - newItemsToSend:', newItemsToSend.length, 'total items:', currentOrderData.items.length);

                                    // Check if kitchen has already been sent at least once
                                    if (currentOrderData.initialKitchenSent === true) {
                                        console.log('Initial send already done - AUTO-SENDING new items to kitchen');
                                        // Only enable if there are items waiting to be sent
                                        if (newItemsToSend.length > 0) {
                                            // Auto-send the new items to kitchen without confirmation
                                            sendOrderToKitchen(true);
                                        } else {
                                            console.log('No new items to auto-send');
                                        }
                                    } else {
                                        // First send not yet done - enable button for manual send
                                        // Only enable if there are items waiting to be sent
                                        if (newItemsToSend.length > 0) {
                                            sendToKitchenBtn.disabled = false;
                                            sendToKitchenBtn.style.opacity = '1';
                                            sendToKitchenBtn.style.cursor = 'pointer';
                                            sendToKitchenBtn.style.backgroundColor = '';
                                            sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
                                            console.log('Send to Kitchen button ENABLED - ready to send ' + newItemsToSend.length + ' items');
                                        } else {
                                            console.log('No new items to send - button remains disabled');
                                        }
                                    }

                                    // Update the display
                                    renderSelectedItems();
                                    updateOrderSummary();
                                }

                                // Keep the modal open - don't close it
                                // closeOrderModal();
                                // loadDashboardData();
                            });
                        } else {
                            console.error('Order submission failed:', responseData);
                            Swal.fire('Error', responseData.message || 'Failed to process order', 'error');
                        }
                    } catch (error) {
                        console.error('Error submitting order:', error);
                        Swal.fire('Error', 'Failed to process order. Please try again.', 'error');
                    }
                }
            });
        }

        // Send order to kitchen
        // Refresh order display (called after sending to kitchen)
        function refreshOrderDisplay() {
            console.log('Refreshing order display...');
            console.log('Current items:', currentOrderData.items);
            console.log('Current items count:', currentOrderData.items.length);

            // Ensure items have all required properties
            currentOrderData.items.forEach((item, index) => {
                console.log(`Item ${index}:`, {
                    id: item.id,
                    name: item.name,
                    price: item.price,
                    quantity: item.quantity,
                    isExisting: item.isExisting
                });
            });

            // Update the display
            updateOrderSummary();

            // Force a re-render of the items list
            const selectedItemsList = document.getElementById('selectedItemsList');
            console.log('selectedItemsList element:', selectedItemsList);
            console.log('selectedItemsList content before render:', selectedItemsList?.innerHTML);
        }

        async function sendOrderToKitchen(skipConfirmation = false) {
            console.log('=== sendOrderToKitchen called ===');
            console.log('Order ID:', currentOrderData.orderId);
            console.log('Kitchen Sent flag:', currentOrderData.kitchenSent);
            console.log('Skip Confirmation:', skipConfirmation);

            if (!currentOrderData.orderId) {
                console.error('ERROR: Order ID is missing!');
                Swal.fire('Error', 'Order ID is missing', 'error');
                return;
            }

            // Check if there are items that NOT sent to kitchen yet
            const itemsToSend = currentOrderData.items.filter(item => item.isExisting === false);
            console.log('sendOrderToKitchen - Items to send:', itemsToSend.length, 'total items:', currentOrderData.items.length);

            if (itemsToSend.length === 0) {
                console.warn('No new items to send to kitchen');
                if (!skipConfirmation) {
                    Swal.fire('Info', 'All items have already been sent to kitchen', 'info');
                }
                return;
            }

            // Skip confirmation if auto-sending
            if (skipConfirmation) {
                console.log('Auto-sending to kitchen without confirmation...');
                try {
                    const response = await fetch('../backend/server_send_order_to_kitchen.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            order_id: currentOrderData.orderId
                        })
                    });

                    const data = await response.json();

                    if (data.success) {
                        console.log('=== Order SUCCESSFULLY auto-sent to kitchen ===');

                        // Mark all items that were sent
                        const itemsSent = currentOrderData.items.filter(item => item.isExisting === false);
                        itemsSent.forEach(item => {
                            item.isExisting = true;
                            item.isReordered = false;
                        });

                        currentOrderData.existingItemIds = currentOrderData.items.map(item => item.id);

                        Swal.fire({
                            title: 'Success!',
                            text: `New items sent to kitchen. You can continue adding more items.`,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false,
                            toast: true,
                            position: 'top-end'
                        });

                        renderSelectedItems();
                        updateOrderSummary();
                    } else {
                        console.error('Auto-send failed:', data);
                    }
                } catch (error) {
                    console.error('Error auto-sending to kitchen:', error);
                }
                return;
            }

            Swal.fire({
                title: 'Send to Kitchen?',
                text: `Send order for Table ${currentOrderData.tableNumber} to the kitchen for preparation?`,
                icon: 'question',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showCancelButton: true,
                confirmButtonColor: '#ff9800',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Send to Kitchen'
            }).then(async (result) => {
                console.log('=== CONFIRMATION DIALOG RESULT ===');
                console.log('User clicked:', result.isConfirmed ? 'CONFIRM' : 'CANCEL/DISMISS');

                if (result.isConfirmed) {
                    console.log('Proceeding with send to kitchen...');
                    try {
                        const response = await fetch('../backend/server_send_order_to_kitchen.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                order_id: currentOrderData.orderId
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            console.log('=== Order SUCCESSFULLY sent to kitchen ===');
                            console.log('API Response:', data);
                            console.log('Items before marking:', currentOrderData.items.length, 'items:', currentOrderData.items.map(i => ({
                                id: i.id,
                                isExisting: i.isExisting
                            })));

                            // Mark all items that were sent (those without isExisting originally marked as false become true)
                            // Find which items were actually sent (those that had isExisting = false before)
                            const itemsSent = currentOrderData.items.filter(item => item.isExisting === false);
                            console.log('Items being sent to kitchen:', itemsSent.length);

                            // Mark only the items that were sent as isExisting
                            itemsSent.forEach(item => {
                                item.isExisting = true;
                                item.isReordered = false;
                            });

                            // Update the existingItemIds to include all current items
                            currentOrderData.existingItemIds = currentOrderData.items.map(item => item.id);

                            console.log('Items after marking sent:', currentOrderData.items.length, 'items:', currentOrderData.items.map(i => ({
                                id: i.id,
                                isExisting: i.isExisting
                            })));

                            Swal.fire({
                                title: 'Success!',
                                text: 'Order sent to kitchen. You can continue adding more items for this table.',
                                icon: 'success',
                                confirmButtonColor: '#d4a574'
                            }).then(() => {
                                console.log('=== POST-SEND: Updating UI ===');

                                // Mark that initial send to kitchen is done
                                currentOrderData.initialKitchenSent = true;

                                // Update button text to "Add Items"
                                const submitBtn = document.getElementById('submitOrderBtn');
                                submitBtn.textContent = 'Add Items';
                                submitBtn.style.backgroundColor = '#28a745';
                                submitBtn.style.display = 'block';

                                // KEEP send to kitchen button ENABLED and ACTIVE after first send
                                // No need to disable it - it stays ready for the automatic sends when items are added
                                const sendToKitchenBtn = document.getElementById('sendToKitchenBtn');
                                sendToKitchenBtn.disabled = false;
                                sendToKitchenBtn.style.opacity = '1';
                                sendToKitchenBtn.style.cursor = 'pointer';
                                sendToKitchenBtn.style.backgroundColor = '#ff6b35'; // Slightly darker when active
                                sendToKitchenBtn.innerHTML = '<i class="fas fa-check-circle"></i> Send to Kitchen is Enabled';
                                console.log('Send to Kitchen button REMAINS ENABLED - Ready for auto-send of new items');

                                // Mark order as now having been sent to kitchen
                                currentOrderData.isExistingOrder = true;
                                console.log('Order state - isExistingOrder:', currentOrderData.isExistingOrder);

                                // Clear the item detail modal if open
                                closeItemDetail();

                                // Refresh the order display to show existing items
                                refreshOrderDisplay();

                                // Keep items marked as isExisting for display - don't clear them
                                // This allows the server to see what was sent and add more items if needed
                                currentOrderData.items = currentOrderData.items.filter(item => item.isExisting);
                                renderSelectedItems();
                                updateOrderSummary();
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to send order to kitchen', 'error');
                        }
                    } catch (error) {
                        console.error('Error sending order to kitchen:', error);
                        Swal.fire('Error', 'Failed to send order to kitchen. Please try again.', 'error');
                    }
                }
            });
        }

        // Cancel order
        function cancelOrder() {
            Swal.fire({
                title: 'Cancel Order?',
                text: 'All items will be discarded',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    closeOrderModal();
                }
            });
        }

        // Close order modal
        function closeOrderModal() {
            document.getElementById('orderModal').classList.remove('show');
            // Reset all order data
            currentOrderData.items = [];
            currentOrderData.tableId = null;
            currentOrderData.assignmentId = null;
            currentOrderData.tableNumber = null;
            currentOrderData.orderId = null;
            currentOrderData.isExistingOrder = false;
            currentOrderData.initialKitchenSent = false;
            currentOrderData.kitchenSent = false;
            currentOrderData.existingItemIds = [];
            currentOrderData.currentCategory = null;

            // Reset buttons
            const submitBtn = document.getElementById('submitOrderBtn');
            const sendToKitchenBtn = document.getElementById('sendToKitchenBtn');
            submitBtn.style.display = 'block';
            submitBtn.textContent = 'Place Order';
            submitBtn.style.backgroundColor = '#d4a574';
            sendToKitchenBtn.disabled = true;
            sendToKitchenBtn.style.opacity = '0.5';
            sendToKitchenBtn.style.cursor = 'not-allowed';
            sendToKitchenBtn.style.backgroundColor = '';
            sendToKitchenBtn.innerHTML = '<i class="fas fa-fire"></i> Send to Kitchen';
        }

        // Send order to manager for billing
        async function sendOrderToManager() {
            if (!currentOrderData.orderId) {
                Swal.fire('Error', 'No order ID found', 'error');
                return;
            }

            // Check if there are items in the order
            if (currentOrderData.items.length === 0) {
                Swal.fire('Warning', 'Please add items to the order before sending to manager', 'warning');
                return;
            }

            Swal.fire({
                title: 'Send to Manager?',
                text: `Send the order for Table ${currentOrderData.tableNumber} to manager for billing?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Send'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_send_order_to_manager.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                order_id: currentOrderData.orderId,
                                table_id: currentOrderData.tableId,
                                table_number: currentOrderData.tableNumber,
                                items: currentOrderData.items
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Order sent to manager for billing.',
                                icon: 'success',
                                confirmButtonColor: '#d4a574'
                            }).then(() => {
                                // Show Send to Manager button is disabled after sending
                                const sendToManagerBtn = document.getElementById('sendToManagerBtn');
                                sendToManagerBtn.disabled = true;
                                sendToManagerBtn.style.opacity = '0.5';
                                sendToManagerBtn.style.cursor = 'not-allowed';
                                sendToManagerBtn.innerHTML = '<i class="fas fa-check"></i> Sent to Manager';
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to send order to manager', 'error');
                        }
                    } catch (error) {
                        console.error('Error sending order to manager:', error);
                        Swal.fire('Error', 'Failed to send order to manager. Please try again.', 'error');
                    }
                }
            });
        }

        // Update order statistics
        async function updateOrderStats() {
            try {
                const response = await fetch('../backend/server_session_check.php');
                const data = await response.json();

                if (data.success) {
                    const serverData = data.data;
                    const activeOrders = parseInt(serverData.active_orders_count || 0);
                    const completedOrders = parseInt(serverData.completed_orders_count || 0);
                    document.getElementById('activeOrdersCount').textContent = activeOrders;
                    document.getElementById('completedOrdersCount').textContent = completedOrders;
                }
            } catch (error) {
                console.error('Error updating order stats:', error);
            }
        }

        // Close table modal
        function closeTableModal() {
            document.getElementById('tableModal').style.display = 'none';
        }

        // View profile
        function viewMyProfile() {
            Swal.fire({
                title: 'Profile Coming Soon',
                text: 'Profile management will be available soon',
                icon: 'info',
                confirmButtonColor: '#d4a574'
            });
        }

        // Logout
        function logout() {
            Swal.fire({
                title: 'Confirm Logout',
                text: 'Are you sure you want to logout?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Logout'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_logout.php');
                        const data = await response.json();

                        if (data.success) {
                            localStorage.removeItem('serverData');
                            Swal.fire({
                                title: 'Logged Out',
                                text: 'You have been logged out successfully',
                                icon: 'success',
                                timer: 1500,
                                showConfirmButton: false
                            }).then(() => {
                                window.location.href = 'login.php';
                            });
                        }
                    } catch (error) {
                        console.error('Logout error:', error);
                        window.location.href = 'login.php';
                    }
                }
            });
        }

        // Check for ready orders periodically
        async function checkReadyOrders() {
            try {
                const response = await fetch('../backend/server_get_ready_orders.php');
                
                if (!response.ok) {
                    console.error('Response status:', response.status);
                    return;
                }
                
                const data = await response.json();

                if (data.success) {
                    const readyOrders = data.data || [];
                    const unreadCount = data.unread_notifications || 0;

                    const badge = document.getElementById('readyOrdersCount');
                    if (readyOrders.length > 0) {
                        badge.textContent = readyOrders.length;
                        badge.style.display = 'flex';
                    } else {
                        badge.style.display = 'none';
                    }

                    console.log('Ready orders check:', {
                        count: readyOrders.length,
                        unread: unreadCount
                    });
                }
            } catch (error) {
                console.error('Error checking ready orders:', error);
            }
        }

        // Show ready orders modal
        async function showReadyOrdersModal() {
            try {
                const response = await fetch('../backend/server_get_ready_orders.php');
                
                // Check if response is ok
                if (!response.ok) {
                    console.error('Response status:', response.status, response.statusText);
                    Swal.fire('Error', `Server error: ${response.status}`, 'error');
                    return;
                }
                
                const data = await response.json();

                if (!data.success) {
                    Swal.fire('Error', data.message || 'Failed to load ready orders', 'error');
                    return;
                }

                const readyOrders = data.data || [];
                const container = document.getElementById('readyOrdersListContainer');

                document.getElementById('readyOrdersCountModal').textContent = readyOrders.length;

                if (readyOrders.length === 0) {
                    container.innerHTML = '<p class="empty-order-message">No orders ready for pickup</p>';
                } else {
                    container.innerHTML = readyOrders.map(order => `
                        <div class="ready-order-card" style="background: #f9f9f9; border-left: 4px solid #4caf50; padding: 15px; margin-bottom: 12px; border-radius: 4px;">
                            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                <div>
                                    <h3 style="margin: 0; color: #333; font-size: 16px;">
                                        <i class="fas fa-check-circle" style="color: #4caf50;"></i> 
                                        ${order.order_number}
                                    </h3>
                                    <p style="margin: 5px 0 0 0; color: #666; font-size: 13px;">
                                        Table ${order.table_number} • ${order.section}
                                    </p>
                                </div>
                                <span class="badge badge-ready" style="background: #4caf50; padding: 5px 10px; border-radius: 20px;">Ready</span>
                            </div>
                            <p style="margin: 8px 0; font-size: 13px; color: #666;">
                                <i class="fas fa-box"></i> ${order.item_count} item(s) • <i class="fas fa-indian-rupee-sign"></i> ${parseFloat(order.total_amount).toFixed(2)}
                            </p>
                            <p style="margin: 8px 0; font-size: 12px; color: #999; font-style: italic;">
                                ${order.items_summary}
                            </p>
                            <button onclick="pickupOrder(${order.id})" class="btn btn-submit" style="width: 100%; margin-top: 10px; background: #4caf50;">
                                <i class="fas fa-hand-holding-box"></i> Collect & Deliver
                            </button>
                        </div>
                    `).join('');
                }

                document.getElementById('readyOrdersModal').classList.add('show');
            } catch (error) {
                console.error('Error loading ready orders:', error);
                const errorMsg = error.message || 'Failed to load ready orders. Please try again.';
                Swal.fire('Error', errorMsg, 'error');
            }
        }

        // Close ready orders modal
        function closeReadyOrdersModal() {
            document.getElementById('readyOrdersModal').classList.remove('show');
            checkReadyOrders(); // Refresh badge count
        }

        // Helper to reopen table for new order after existing order completed
        function reopenTableForNewOrder() {
            if (currentOrderData.tableId && currentOrderData.tableNumber) {
                // Small delay to allow UI to update
                setTimeout(() => {
                    takeOrder(currentOrderData.tableId, currentOrderData.tableNumber, currentOrderData.assignmentId);
                }, 500);
            }
        }

        // Pickup and deliver ready order
        async function pickupOrder(orderId) {
            Swal.fire({
                title: 'Collect Order?',
                text: 'Are you collecting this order to deliver to the customer?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4caf50',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Collect'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_pickup_order.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                order_id: orderId
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            Swal.fire({
                                title: 'Success!',
                                text: data.message || 'Order collected and marked as delivered',
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                                showReadyOrdersModal();
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to collect order', 'error');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to collect order', 'error');
                    }
                }
            });
        }


        // Generate and display bill
        async function generateBill() {
            if (!currentOrderData.orderId) {
                Swal.fire('Error', 'No order ID found', 'error');
                return;
            }

            try {
                const response = await fetch('../backend/kitchen_get_order_details.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        order_id: currentOrderData.orderId,
                        include_all_items: true
                    })
                });

                const data = await response.json();

                if (!data.success) {
                    Swal.fire('Error', data.message || 'Failed to load order details', 'error');
                    return;
                }

                const order = data.order;
                const items = data.items;

                // Populate bill modal
                document.getElementById('billOrderNumber').textContent = order.order_number;
                document.getElementById('billTableNumber').textContent = order.table_number;
                document.getElementById('billOrderNum').textContent = order.order_number;
                document.getElementById('billOrderTime').textContent = new Date(order.created_at).toLocaleString();

                // Render items
                let subtotal = 0;
                const itemsHTML = items.map(item => {
                    const itemTotal = parseFloat(item.unit_price) * parseInt(item.quantity);
                    subtotal += itemTotal;

                    // Determine status badge color
                    let statusBg, statusColor;
                    if (item.status === 'served') {
                        statusBg = '#c8e6c9';
                        statusColor = '#2e7d32';
                    } else if (item.status === 'ready') {
                        statusBg = '#b3e5fc';
                        statusColor = '#01579b';
                    } else if (item.status === 'preparing') {
                        statusBg = '#ffe0b2';
                        statusColor = '#e65100';
                    } else {
                        statusBg = '#e1bee7';
                        statusColor = '#6a1b9a';
                    }

                    return `
                        <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; font-size: 14px;">
                            <div style="flex: 1;">
                                <div style="font-weight: bold; color: #333;">${item.item_name}</div>
                                <div style="font-size: 12px; color: #999;">x${item.quantity} @ ₹${parseFloat(item.unit_price).toFixed(2)} each</div>
                                <div style="font-size: 12px; background: ${statusBg}; color: ${statusColor}; display: inline-block; padding: 3px 8px; border-radius: 3px; margin-top: 5px; font-weight: bold;">
                                    ${item.status.toUpperCase()}
                                </div>
                            </div>
                            <div style="text-align: right; font-weight: bold;">
                                ₹${itemTotal.toFixed(2)}
                            </div>
                        </div>
                    `;
                }).join('');

                document.getElementById('billItemsList').innerHTML = itemsHTML;
                document.getElementById('billSubtotal').textContent = '₹ ' + subtotal.toFixed(2);
                document.getElementById('billTotal').textContent = '₹ ' + subtotal.toFixed(2);
                document.getElementById('billStatus').textContent = 'Status: ' + (order.status.charAt(0).toUpperCase() + order.status.slice(1));

                // Update button text based on order status
                const completeBtn = document.querySelector('#billModal .modal-footer button[onclick="completeBillAndOrder()"]');
                if (completeBtn) {
                    if (order.status === 'completed') {
                        completeBtn.innerHTML = '<i class="fas fa-plus"></i> Start New Order';
                        completeBtn.style.background = '#007bff';
                    } else {
                        completeBtn.innerHTML = '<i class="fas fa-check"></i> Confirm Payment & Complete';
                        completeBtn.style.background = '#27ae60';
                    }
                }

                // Show bill modal
                document.getElementById('billModal').classList.add('show');

                // Hide order modal
                document.getElementById('orderModal').classList.remove('show');

            } catch (error) {
                console.error('Error generating bill:', error);
                Swal.fire('Error', 'Failed to generate bill', 'error');
            }
        }

        // Close bill modal
        function closeBillModal() {
            document.getElementById('billModal').classList.remove('show');
            // Reopen order modal if needed
            if (currentOrderData.tableId) {
                document.getElementById('orderModal').classList.add('show');
            }
        }

        // Mark order as completed after payment or start new order
        async function completeBillAndOrder() {
            // Check current order status
            const response = await fetch('../backend/kitchen_get_order_details.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    order_id: currentOrderData.orderId,
                    include_all_items: true
                })
            });

            const data = await response.json();
            const order = data.order;

            if (order.status === 'completed') {
                // Already completed - start new order
                Swal.fire({
                    title: 'Start New Order?',
                    text: 'Would you like to take a new order for this table?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#007bff',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Yes, New Order'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Clear current order and start fresh
                        currentOrderData.orderId = null;
                        currentOrderData.isExistingOrder = false;
                        currentOrderData.items = [];
                        currentOrderData.existingItemIds = [];

                        // Close bill modal and reopen table for new order
                        closeBillModal();
                        takeOrder(currentOrderData.tableId, currentOrderData.tableNumber, currentOrderData.assignmentId);
                    }
                });
            } else {
                // Order is ready - mark as completed
                Swal.fire({
                    title: 'Confirm Payment',
                    text: 'Mark order as completed and paid?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#27ae60',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Yes, Mark Completed'
                }).then(async (result) => {
                    if (result.isConfirmed) {
                        try {
                            const pickupResponse = await fetch('../backend/server_pickup_order.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    order_id: currentOrderData.orderId
                                })
                            });

                            const pickupData = await pickupResponse.json();

                            if (pickupData.success) {
                                Swal.fire({
                                    title: 'Success!',
                                    text: 'Order completed and payment confirmed',
                                    icon: 'success',
                                    timer: 2000,
                                    showConfirmButton: false
                                }).then(() => {
                                    closeBillModal();
                                    closeOrderModal();
                                    loadDashboardData();
                                });
                            } else {
                                Swal.fire('Error', pickupData.message || 'Failed to complete order', 'error');
                            }
                        } catch (error) {
                            console.error('Error:', error);
                            Swal.fire('Error', 'Failed to complete order', 'error');
                        }
                    }
                });
            }
        }


        // Hamburger Menu Toggle
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            
            sidebar.classList.toggle('show');
            overlay.classList.toggle('show');
        }

        function closeSidebarMenu() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            
            sidebar.classList.remove('show');
            overlay.classList.remove('show');
        }

        // Close sidebar when a nav link is clicked (for mobile)
        document.addEventListener('DOMContentLoaded', function() {
            const navLinks = document.querySelectorAll('.sidebar-nav a');
            navLinks.forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        closeSidebarMenu();
                    }
                });
            });
        });


        // String capitalize helper
        String.prototype.capitalize = function() {
            return this.charAt(0).toUpperCase() + this.slice(1);
        };

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', checkServerSession);

        // Refresh dashboard every 30 seconds
        setInterval(loadDashboardData, 30000);
    </script>
</body>

</html>
