// Professional Tablet Order System JavaScript
// Handles screen transitions, data management, and user interactions

class TabletOrderSystem {
    constructor(itemsData, categoriesData, tablesData) {
        this.items = itemsData || [];
        this.categories = categoriesData || [];
        this.tables = tablesData || [];
        this.cart = [];
        this.currentOrderType = null;
        this.selectedTable = null;
        this.currentCategory = null;
        this.currentSubCategory = null;
        this.subCategories = [];
        this.taxSettings = null;
        
        // Running order properties
        this.isRunningOrder = false;
        this.runningOrderTableId = null;
        this.runningOrderTableName = null;
        
        // Context menu properties
        this.contextMenu = null;
        this.currentTableData = null;
        this.currentOrdersData = null;
        
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadSubCategories();
        this.loadTaxSettings();
        this.showOrderModeScreen();
        this.initContextMenu();
    }

    bindEvents() {
        // Order mode buttons
        document.querySelectorAll('.btn-order-mode').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const orderType = e.currentTarget.dataset.type;
                this.selectOrderType(orderType);
            });
        });

        // Navigation buttons
        document.addEventListener('click', (e) => {
            if (e.target.matches('[onclick*="goBackToOrderMode"]')) {
                this.goBackToOrderMode();
            } else if (e.target.matches('[onclick*="goToOrderMode"]')) {
                this.goToOrderMode();
            } else if (e.target.matches('[onclick*="goBackToTableSelection"]')) {
                this.goBackToTableSelection();
            }
        });

        // Close context menu when clicking outside
        document.addEventListener('click', (e) => {
            if (this.contextMenu && !this.contextMenu.contains(e.target)) {
                // Don't hide if clicking on a context menu button
                if (!e.target.closest('.context-menu-btn')) {
                    this.hideContextMenu();
                }
            }
        });
    }

    // Screen Management
    showScreen(screenId) {
        // Hide all screens
        document.querySelectorAll('.order-screen').forEach(screen => {
            screen.classList.remove('active');
        });
        
        // Show target screen
        const targetScreen = document.getElementById(screenId);
        if (targetScreen) {
            targetScreen.classList.add('active');
        }
    }

    showOrderModeScreen() {
        this.showScreen('order-mode-screen');
    }

    showTableSelectionScreen() {
        this.showScreen('table-selection-screen');
        this.loadTables();
    }

    showTakeAwaySelectionScreen() {
        this.showScreen('takeaway-selection-screen');
        this.loadTakeAwayOrders();
    }

    showItemCartScreen() {
        this.showScreen('item-cart-screen');
        this.loadCategories();
        this.loadItems();
        this.updateOrderInfo();
    }

    // Order Type Selection
    selectOrderType(orderType) {
        this.currentOrderType = orderType;
        
        if (orderType === 'dine_in') {
            this.showTableSelectionScreen();
        } else if (orderType === 'take_away') {
            this.showTakeAwaySelectionScreen();
        } else {
            // For delivery and other modes, go directly to item selection
            this.showItemCartScreen();
        }
    }

    // Table Selection
    loadTables() {
        const tableGrid = document.getElementById('table-grid');
        if (!tableGrid) return;

        tableGrid.innerHTML = '';

        // Group tables by floor
        const floors = {};
        this.tables.forEach(table => {
            const floorName = table.floor_name || 'Main Floor';
            if (!floors[floorName]) {
                floors[floorName] = [];
            }
            floors[floorName].push(table);
        });

        Object.keys(floors).forEach(floorName => {
            // Add floor header
            const floorHeader = document.createElement('div');
            floorHeader.className = 'floor-header';
            floorHeader.innerHTML = `<h4 style="color: white; margin: 20px 0 15px 0; text-align: center;">${floorName}</h4>`;
            tableGrid.appendChild(floorHeader);

            // Add tables for this floor
            floors[floorName].forEach(table => {
                const tableItem = this.createTableItem(table);
                tableGrid.appendChild(tableItem);
            });
        });
    }

    createTableItem(table) {
        const tableItem = document.createElement('div');
        tableItem.className = 'table-item';
        
        let statusClass = '';
        let statusText = 'Available';
        
        if (table.status === 'occupied') {
            statusClass = 'occupied';
            statusText = 'Occupied';
        } else if (table.status === 'reserved') {
            statusClass = 'reserved';
            statusText = 'Reserved';
        }

        if (statusClass) {
            tableItem.classList.add(statusClass);
        }

        tableItem.innerHTML = `
            <div class="table-number">${table.table_name}</div>
            <div class="table-seats">${table.seats} Seats</div>
            <div class="table-status">${statusText}</div>
            ${table.status === 'occupied' ? '<div class="table-running-order-hint">Tap to view orders</div>' : ''}
        `;

        // Add click functionality based on table status
        if (table.status === 'available') {
            // Only allow selection of available tables
            tableItem.style.cursor = 'pointer';
            tableItem.addEventListener('click', () => {
                this.selectTable(table);
            });
        } else if (table.status === 'occupied') {
            // Show occupied table orders
            tableItem.style.cursor = 'pointer';
            tableItem.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.showOccupiedTableOrders(table, e);
            });
        }

        return tableItem;
    }

    selectTable(table) {
        this.selectedTable = table;
        this.showItemCartScreen();
    }

    // Take-Away Orders Management
    loadTakeAwayOrders() {
        const ordersContainer = document.getElementById('takeaway-orders-container');
        if (!ordersContainer) return;

        ordersContainer.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-spinner fa-spin"></i>
                <p class="mt-2">Loading take-away orders...</p>
            </div>
        `;

        fetch('ajax/get_take_away_orders.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.displayTakeAwayOrders(data.orders);
                } else {
                    ordersContainer.innerHTML = `
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-exclamation-triangle"></i>
                            <p class="mt-2">Error loading orders: ${data.message}</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error loading take-away orders:', error);
                ordersContainer.innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p class="mt-2">Failed to load take-away orders</p>
                    </div>
                `;
            });
    }

    displayTakeAwayOrders(orders) {
        const ordersContainer = document.getElementById('takeaway-orders-container');
        if (!ordersContainer) return;

        if (!orders || orders.length === 0) {
            ordersContainer.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-shopping-bag"></i>
                    <p class="mt-2">No take-away orders found</p>
                </div>
            `;
            return;
        }

        let html = '<div class="takeaway-orders-grid">';
        orders.forEach(order => {
            html += this.createTakeAwayOrderCard(order);
        });
        html += '</div>';

        ordersContainer.innerHTML = html;
        
        // Add event listeners for context menu buttons
        this.bindTakeAwayContextMenuEvents();
    }

    createTakeAwayOrderCard(order) {
        const orderDate = new Date(order.created_at).toLocaleString();
        const totalAmount = parseFloat(order.total_amount).toFixed(2);
        const itemCount = order.item_count || 0;
        
        return `
            <div class="takeaway-order-card" 
                 data-order-id="${order.id}" 
                 data-order-reference="${order.reference}" 
                 data-customer-name="${order.customer_name}"
                 onclick="tabletOrderSystem.showTakeAwayContextMenu(event, ${order.id}, '${order.reference}', '${order.customer_name}')">
                <div class="order-header">
                    <div class="order-reference">${order.reference}</div>
                    <div class="order-time">${orderDate}</div>
                </div>
                <div class="order-details">
                    <div class="customer-name">
                        <i class="fas fa-user"></i>
                        ${order.customer_name}
                    </div>
                    <div class="order-summary">
                        <span class="item-count">${itemCount} items</span>
                        <span class="total-amount">Rs ${totalAmount}</span>
                    </div>
                </div>
            </div>
        `;
    }

    // Category Management
    loadCategories() {
        const categoriesContainer = document.getElementById('main-categories');
        if (!categoriesContainer) return;

        categoriesContainer.innerHTML = '';

        // Add other categories (removed "All" button)
        this.categories.forEach(category => {
            const categoryBtn = document.createElement('button');
            categoryBtn.className = 'main-category-btn';
            categoryBtn.textContent = category.name;
            categoryBtn.addEventListener('click', () => {
                this.selectCategory(category.id);
            });
            categoriesContainer.appendChild(categoryBtn);
        });
    }

    selectCategory(categoryId) {
        this.currentCategory = categoryId;
        
        // Update active state
        document.querySelectorAll('.main-category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // Load sub-categories
        this.loadSubCategoriesForCategory(categoryId);
        
        // Load items
        this.loadItems();
    }

    loadSubCategories() {
        // This will be loaded dynamically when categories are selected
        this.subCategories = [];
    }

    loadTaxSettings() {
        // Load tax settings from server
        fetch('ajax/get_tax_settings.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.taxSettings = data;
                    console.log('Tax settings loaded:', this.taxSettings);
                } else {
                    console.error('Error loading tax settings:', data.error);
                }
            })
            .catch(error => {
                console.error('Error loading tax settings:', error);
            });
    }

    loadSubCategoriesForCategory(categoryId) {
        const subCategoriesContainer = document.getElementById('sub-categories');
        if (!subCategoriesContainer) return;

        subCategoriesContainer.innerHTML = '';

        if (!categoryId) {
            // Show all sub-categories when "All" is selected
            this.loadAllSubCategories();
        } else {
            // Load sub-categories for selected category from database
            this.loadSubCategoriesFromDatabase(categoryId);
        }
    }

    loadAllSubCategories() {
        const subCategoriesContainer = document.getElementById('sub-categories');
        
        // Show loading state
        subCategoriesContainer.innerHTML = `
            <div class="text-center py-3">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        `;
        
        // Fetch all subcategories
        fetch('ajax/get_subcategories.php?category_id=all')
            .then(response => response.json())
            .then(data => {
                this.displaySubCategories(data);
            })
            .catch(error => {
                console.error('Error loading subcategories:', error);
                subCategoriesContainer.innerHTML = '<div class="text-muted text-center py-3">No subcategories found</div>';
            });
    }

    loadSubCategoriesFromDatabase(categoryId) {
        const subCategoriesContainer = document.getElementById('sub-categories');
        
        // Show loading state
        subCategoriesContainer.innerHTML = `
            <div class="text-center py-3">
                <div class="spinner-border spinner-border-sm text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        `;
        
        // Fetch subcategories for the category
        fetch(`ajax/get_subcategories.php?category_id=${categoryId}`)
            .then(response => response.json())
            .then(data => {
                this.displaySubCategories(data);
            })
            .catch(error => {
                console.error('Error loading subcategories:', error);
                subCategoriesContainer.innerHTML = '<div class="text-muted text-center py-3">No subcategories found</div>';
            });
    }

    displaySubCategories(subcategories) {
        const subCategoriesContainer = document.getElementById('sub-categories');
        
        if (!subcategories || subcategories.length === 0) {
            subCategoriesContainer.innerHTML = '<div class="text-muted text-center py-3">No subcategories found</div>';
            return;
        }
        
        subCategoriesContainer.innerHTML = '';
        
        subcategories.forEach(subCat => {
            const subBtn = this.createSubCategoryButton(subCat);
            subCategoriesContainer.appendChild(subBtn);
        });
    }

    createSubCategoryButton(subCategory) {
        const subBtn = document.createElement('button');
        subBtn.className = 'sub-category-btn';
        subBtn.textContent = subCategory.name;
        subBtn.addEventListener('click', () => {
            this.selectSubCategory(subCategory.id);
        });
        return subBtn;
    }

    selectSubCategory(subCategoryId) {
        this.currentSubCategory = subCategoryId;
        
        // Update active state
        document.querySelectorAll('.sub-category-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');

        // Load items
        this.loadItems();
    }

    // Item Management
    loadItems() {
        const itemsGrid = document.getElementById('items-grid');
        if (!itemsGrid) return;

        itemsGrid.innerHTML = '';

        let filteredItems = this.items;

        // Filter by category
        if (this.currentCategory) {
            filteredItems = filteredItems.filter(item => item.category_id == this.currentCategory);
        }

        // Filter by sub-category
        if (this.currentSubCategory) {
            filteredItems = filteredItems.filter(item => item.sub_category_id == this.currentSubCategory);
        }

        // Display items
        filteredItems.forEach(item => {
            const itemCard = this.createItemCard(item);
            itemsGrid.appendChild(itemCard);
        });
    }

    createItemCard(item) {
        const itemCard = document.createElement('div');
        itemCard.className = 'item-card';
        
        itemCard.innerHTML = `
            <div class="item-name">${item.name}</div>
        `;

        // Make entire card clickable
        itemCard.addEventListener('click', () => {
            this.addToCart(item.id);
        });

        return itemCard;
    }

    // Cart Management
    addToCart(itemId) {
        const item = this.items.find(i => i.id == itemId);
        if (!item) return;

        // Check if this item has modifiers
        this.checkItemModifiers(itemId, item);
    }

    async checkItemModifiers(itemId, item) {
        try {
            const response = await fetch(`ajax/get_item_modifiers.php?item_id=${itemId}`);
            const data = await response.json();
            
            if (data.success && data.modifier_groups && data.modifier_groups.length > 0) {
                // Item has modifiers, show selection modal
                this.showModifierModal(item, data.modifier_groups);
            } else {
                // No modifiers, add directly to cart
                this.addItemToCart(item, []);
            }
        } catch (error) {
            console.error('Error checking modifiers:', error);
            // If error, add item without modifiers
            this.addItemToCart(item, []);
        }
    }

    addItemToCart(item, selectedModifiers = []) {
        // Calculate total price with modifiers
        let totalPrice = parseFloat(item.retail_price) || 0;
        selectedModifiers.forEach(modifier => {
            totalPrice += parseFloat(modifier.price_adjustment || 0);
        });

        // Create unique identifier for cart items with modifiers
        const modifierCode = selectedModifiers.map(m => m.id).sort().join('-');
        const uniqueId = modifierCode ? `${item.id}-mod-${modifierCode}` : item.id.toString();

        // Check if this exact item+modifier combination exists
        const existingItem = this.cart.find(cartItem => cartItem.uniqueId === uniqueId);
        
        if (existingItem) {
            existingItem.quantity += 1;
        } else {
            // Create modifier display text
            const modifierText = selectedModifiers.map(m => m.name).join(', ');
            
            this.cart.push({
                id: item.id,
                uniqueId: uniqueId,
                name: item.name,
                modifierText: modifierText,
                modifiers: selectedModifiers,
                price: totalPrice,
                basePrice: parseFloat(item.retail_price) || 0,
                quantity: 1,
                tax_rate: parseFloat(item.tax_rate) || 0.00, // Add tax_rate field
                remarks: '' // Add remarks field
            });
        }

        this.updateCart();
    }

    // Modifier Modal Management
    showModifierModal(item, modifierGroups) {
        // Store item data for the modal
        this.modalItemData = {
            item: item,
            modifierGroups: modifierGroups
        };

        // Set modal content
        document.getElementById('tabletModalItemName').textContent = item.name;
        document.getElementById('tabletBasePrice').textContent = parseFloat(item.retail_price).toFixed(2);
        document.getElementById('tabletTotalPrice').textContent = parseFloat(item.retail_price).toFixed(2);

        // Clear previous modifier groups
        const container = document.getElementById('tabletModifierGroupsContainer');
        container.innerHTML = '';

        // Add modifier groups
        modifierGroups.forEach(group => {
            const groupHtml = this.createTabletModifierGroupHtml(group);
            container.appendChild(groupHtml);
        });

        // Bind confirm button event
        document.getElementById('tabletConfirmModifierBtn').onclick = () => {
            this.confirmTabletModifierSelection();
        };

        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('tabletModifierModal'));
        modal.show();

        // Bind change events for price calculation
        this.bindTabletModifierEvents();
    }

    createTabletModifierGroupHtml(group) {
        const isRequired = group.is_required == 1;
        const isMultiple = group.is_multiple_choice == 1;

        const groupDiv = document.createElement('div');
        groupDiv.className = 'modifier-group card mb-3';
        groupDiv.setAttribute('data-group-id', group.id);

        const modifiersHtml = group.modifiers.map(modifier => 
            this.createTabletModifierOptionHtml(modifier, group.id, isMultiple)
        ).join('');

        groupDiv.innerHTML = `
            <div class="card-header">
                <h6 class="mb-0">
                    ${group.display_name}
                    ${isRequired ? '<span class="badge bg-danger ms-2">Required</span>' : ''}
                    ${isMultiple ? '<span class="badge bg-info ms-2">Multiple Choice</span>' : ''}
                </h6>
                ${group.description ? `<small class="text-muted">${group.description}</small>` : ''}
            </div>
            <div class="card-body">
                ${modifiersHtml}
            </div>
        `;

        return groupDiv;
    }

    createTabletModifierOptionHtml(modifier, groupId, isMultiple) {
        const inputType = isMultiple ? 'checkbox' : 'radio';
        const inputName = isMultiple ? `modifier-group-${groupId}` : `modifier-group-${groupId}`;
        const priceText = modifier.price_adjustment > 0 ? ` (+Rs ${parseFloat(modifier.price_adjustment).toFixed(2)})` : '';
        const isDefault = modifier.is_default == 1;

        return `
            <div class="form-check">
                <input class="form-check-input tablet-modifier-option" 
                       type="${inputType}" 
                       name="${inputName}" 
                       value="${modifier.id}" 
                       data-price="${modifier.price_adjustment}"
                       data-group-id="${groupId}"
                       ${isDefault ? 'checked' : ''}>
                <label class="form-check-label">
                    <span>${modifier.name}${priceText}</span>
                </label>
            </div>
        `;
    }

    bindTabletModifierEvents() {
        document.querySelectorAll('.tablet-modifier-option').forEach(input => {
            input.addEventListener('change', () => {
                this.updateTabletModifierTotal();
            });
        });

        // Initial calculation for default selections
        this.updateTabletModifierTotal();
    }

    updateTabletModifierTotal() {
        const basePrice = parseFloat(this.modalItemData.item.retail_price) || 0;
        let totalPrice = basePrice;

        document.querySelectorAll('.tablet-modifier-option:checked').forEach(input => {
            totalPrice += parseFloat(input.dataset.price || 0);
        });

        document.getElementById('tabletTotalPrice').textContent = totalPrice.toFixed(2);
    }

    confirmTabletModifierSelection() {
        // Validate required groups
        const requiredGroups = document.querySelectorAll('[data-group-id] .badge.bg-danger');
        for (let badge of requiredGroups) {
            const groupCard = badge.closest('[data-group-id]');
            const groupId = groupCard.dataset.groupId;
            const hasSelection = groupCard.querySelector('.tablet-modifier-option:checked');
            
            if (!hasSelection) {
                const groupName = groupCard.querySelector('.card-header h6').textContent.trim();
                alert(`Please select an option for: ${groupName}`);
                return;
            }
        }

        // Collect selected modifiers
        const selectedModifiers = [];
        document.querySelectorAll('.tablet-modifier-option:checked').forEach(input => {
            const modifier = {
                id: input.value,
                name: input.closest('.form-check').querySelector('label span').textContent.split('(')[0].trim(),
                price_adjustment: parseFloat(input.dataset.price || 0),
                group_id: input.dataset.groupId
            };
            selectedModifiers.push(modifier);
        });

        // Close modal
        bootstrap.Modal.getInstance(document.getElementById('tabletModifierModal')).hide();

        // Add item to cart with modifiers
        this.addItemToCart(this.modalItemData.item, selectedModifiers);
    }

    updateCart() {
        this.updateCartDisplay();
        this.updateCartSummary();
    }

    updateCartDisplay() {
        const cartItems = document.getElementById('cart-items');
        const cartCount = document.getElementById('cart-count');
        
        if (!cartItems || !cartCount) return;

        cartItems.innerHTML = '';
        cartCount.textContent = this.cart.length;

        this.cart.forEach(item => {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            cartItem.setAttribute('data-unique-id', item.uniqueId);
            
            const itemPrice = parseFloat(item.price) || 0;
            const displayName = item.name; // Keep item name clean, modifiers will show separately
            
            cartItem.innerHTML = `
                <div class="cart-item-info" style="cursor: pointer;" onclick="tabletOrderSystem.showRemarksModal('${item.uniqueId}')">
                    <div class="cart-item-name">${displayName}</div>
                    ${item.modifierText ? `<div class="cart-item-modifiers text-muted small">${item.modifierText}</div>` : ''}
                    ${item.remarks ? `<div class="cart-item-remarks text-warning small">💬 ${item.remarks}</div>` : ''}
                    <div class="cart-item-price">${itemPrice.toFixed(2)}</div>
                </div>
                <div class="cart-item-controls">
                    <button class="quantity-btn" onclick="tabletOrderSystem.updateQuantity('${item.uniqueId}', -1)">-</button>
                    <span class="quantity-display">${item.quantity}</span>
                    <button class="quantity-btn" onclick="tabletOrderSystem.updateQuantity('${item.uniqueId}', 1)">+</button>
                    <button class="template-btn" onclick="tabletOrderSystem.showTemplateSelectionModal('${item.uniqueId}', event)" title="Add Template">
                        <i class="fas fa-layer-group"></i>
                    </button>
                    <button class="remove-btn" onclick="tabletOrderSystem.removeFromCart('${item.uniqueId}')">×</button>
                </div>
            `;
            
            cartItems.appendChild(cartItem);
        });
    }

    updateQuantity(uniqueId, change) {
        const item = this.cart.find(cartItem => cartItem.uniqueId === uniqueId);
        if (!item) return;

        item.quantity += change;

        if (item.quantity <= 0) {
            // Remove item from cart
            this.cart = this.cart.filter(cartItem => cartItem.uniqueId !== uniqueId);
        }

        this.updateCart();
    }

    removeFromCart(uniqueId) {
        this.cart = this.cart.filter(cartItem => cartItem.uniqueId !== uniqueId);
        this.updateCart();
    }

    updateCartSummary() {
        const subtotal = this.cart.reduce((sum, item) => {
            const itemPrice = parseFloat(item.price) || 0;
            const itemQuantity = parseInt(item.quantity) || 0;
            return sum + (itemPrice * itemQuantity);
        }, 0);
        
        const taxRate = 0.1; // 10% tax - this should come from settings
        const tax = subtotal * taxRate;
        const total = subtotal + tax;

        document.getElementById('subtotal').textContent = `${subtotal.toFixed(2)}`;
        document.getElementById('tax-amount').textContent = `${tax.toFixed(2)}`;
        document.getElementById('total-amount').textContent = `${total.toFixed(2)}`;
    }

    clearCart() {
        if (confirm('Are you sure you want to clear the cart?')) {
            this.cart = [];
            this.updateCart();
        }
    }

    // Remarks Modal Function
    showRemarksModal(uniqueId) {
        const item = this.cart.find(cartItem => cartItem.uniqueId === uniqueId);
        if (!item) return;

        // Store the current item being edited
        this.currentRemarksItem = uniqueId;

        // Set current remarks in the modal
        document.getElementById('tabletRemarksInput').value = item.remarks || '';

        // Update modal title
        document.querySelector('#tabletRemarksModal .modal-title').textContent = `Add Remarks: ${item.name}`;

        // Bind save button event
        document.getElementById('tabletSaveRemarksBtn').onclick = () => {
            this.saveRemarks();
        };

        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('tabletRemarksModal'));
        modal.show();
    }

    saveRemarks() {
        const remarks = document.getElementById('tabletRemarksInput').value.trim();
        
        // Update the cart item
        const item = this.cart.find(cartItem => cartItem.uniqueId === this.currentRemarksItem);
        if (item) {
            item.remarks = remarks;
        }

        // Update the cart display
        this.updateCart();

        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('tabletRemarksModal'));
        modal.hide();
    }

    // Order Management

    showOccupiedTableOrders(table, event) {
        // Fetch current orders for this table
        fetch(`ajax/get_table_orders.php?table_id=${table.id}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.orders) {
                    // Get click position for context menu
                    const x = event ? event.clientX : window.innerWidth / 2;
                    const y = event ? event.clientY : window.innerHeight / 2;
                    
                    this.showContextMenu(x, y, table, data.orders);
                } else {
                    // Show context menu even if no orders (for adding running order)
                    const x = event ? event.clientX : window.innerWidth / 2;
                    const y = event ? event.clientY : window.innerHeight / 2;
                    
                    this.showContextMenu(x, y, table, []);
                }
            })
            .catch(error => {
                console.error('Error fetching table orders:', error);
                alert('Error loading table orders. Please try again.');
            });
    }

    generateOrdersHTML(orders) {
        if (!orders || orders.length === 0) {
            return '<p class="no-orders">No active orders found for this table.</p>';
        }

        let html = '';
        orders.forEach(order => {
            // Calculate subtotal from items
            const subtotal = order.items.reduce((sum, item) => {
                return sum + (parseFloat(item.price) * parseInt(item.quantity));
            }, 0);

            // Get payment method totals with tax
            const paymentTotals = this.calculatePaymentMethodTotals(subtotal);

            const runningOrderBadge = order.has_running_orders ? 
                '<span class="running-order-badge">RUNNING ORDER</span>' : '';
            
            html += `
                <div class="order-item ${order.has_running_orders ? 'running-order-item' : ''}">
                    <div class="order-header">
                        <div class="order-header-left">
                            <span class="order-id">Order #${order.id}</span>
                            ${runningOrderBadge}
                        </div>
                        <div class="order-header-right">
                            <span class="order-time">${order.created_at}</span>
                            <span class="order-status ${order.status}">${order.status}</span>
                        </div>
                    </div>
                    <div class="order-items-list">
                        ${this.generateOrderItemsHTML(order.items)}
                    </div>
                                         <div class="order-total">
                         <strong>Subtotal: ${subtotal.toFixed(2)}</strong>
                         ${paymentTotals}
                     </div>
                </div>
            `;
        });
        
        return html;
    }

    calculatePaymentMethodTotals(subtotal) {
        // Check if tax is enabled and get payment method totals
        if (!this.taxSettings) {
            return `<div class="order-total-amount"><strong>Total: ${subtotal.toFixed(2)}</strong></div>`;
        }

        if (this.taxSettings.tax_method !== 'payment_method') {
            return `<div class="order-total-amount"><strong>Total: ${subtotal.toFixed(2)}</strong></div>`;
        }

        const cashRate = this.taxSettings.payment_tax_rates.cash || 0;
        const cardRate = this.taxSettings.payment_tax_rates.card || 0;
        
        const cashTotal = subtotal + (subtotal * (cashRate / 100));
        const cardTotal = subtotal + (subtotal * (cardRate / 100));

        return `
            <div class="payment-totals">
                <div class="payment-option">
                    <span class="payment-label">Cash:</span>
                    <span class="payment-amount">${cashTotal.toFixed(2)}</span>
                </div>
                <div class="payment-option">
                    <span class="payment-label">Card:</span>
                    <span class="payment-amount">${cardTotal.toFixed(2)}</span>
                </div>
            </div>
        `;
    }

    generateOrderItemsHTML(items) {
        if (!items || items.length === 0) {
            return '<p>No items in this order.</p>';
        }

        let html = '<div class="items-list">';
        items.forEach(item => {
            // Parse modifiers if they exist
            let modifierText = '';
            if (item.modifiers) {
                try {
                    const modifiers = JSON.parse(item.modifiers);
                    if (Array.isArray(modifiers) && modifiers.length > 0) {
                        const modifierNames = modifiers.map(m => m.name).filter(name => name);
                        modifierText = modifierNames.join(', ');
                    }
                } catch (e) {
                    console.error('Error parsing modifiers:', e);
                }
            }

            // Get remarks
            const remarks = item.remarks || '';

            html += `
                <div class="item-row">
                    <div class="item-details">
                        <span class="item-name">${item.item_name}</span>
                        ${modifierText ? `<div class="item-modifiers">${modifierText}</div>` : ''}
                        ${remarks ? `<div class="item-remarks">💬 ${remarks}</div>` : ''}
                    </div>
                    <span class="item-quantity">x${item.quantity}</span>
                    <span class="item-price">${item.price}</span>
                </div>
            `;
        });
        html += '</div>';
        
        return html;
    }

    // Navigation
    goBackToOrderMode() {
        this.currentOrderType = null;
        this.selectedTable = null;
        this.showOrderModeScreen();
    }

    goToOrderMode() {
        this.goBackToOrderMode();
    }

    goBackToTableSelection() {
        if (this.currentOrderType === 'dine_in') {
            this.showTableSelectionScreen();
        } else if (this.currentOrderType === 'take_away') {
            this.showTakeAwaySelectionScreen();
        } else {
            this.goBackToOrderMode();
        }
    }

    updateOrderInfo() {
        const orderTypeElement = document.getElementById('current-order-type');
        const tableInfoElement = document.getElementById('current-table-info');
        
        if (orderTypeElement) {
            const orderTypeText = this.currentOrderType ? 
                this.currentOrderType.replace('_', ' ').toUpperCase() : 'Select Order Type';
            orderTypeElement.textContent = orderTypeText;
        }
        
        if (tableInfoElement && this.selectedTable) {
            tableInfoElement.textContent = ` - Table ${this.selectedTable.table_name}`;
            tableInfoElement.style.display = 'inline';
        } else if (tableInfoElement) {
            tableInfoElement.style.display = 'none';
        }
    }

    // Running Order Management
    startRunningOrder(tableId, tableName) {
        // Close the modal
        const modal = document.querySelector('.table-orders-modal');
        if (modal) {
            modal.remove();
        }

        // Set up running order context
        this.isRunningOrder = true;
        this.runningOrderTableId = tableId;
        this.runningOrderTableName = tableName;
        
        // Create table object for running order
        this.selectedTable = {
            id: tableId,
            table_name: tableName,
            status: 'occupied'
        };

        // Set order type to dine_in for running orders
        this.currentOrderType = 'dine_in';

        // Show resumed order indicator
        this.showResumedOrderIndicator();

        // Go to item selection screen
        this.showItemCartScreen();
    }

    showResumedOrderIndicator() {
        // Add resumed order indicator to the order info
        const orderTypeElement = document.getElementById('current-order-type');
        if (orderTypeElement) {
            orderTypeElement.innerHTML = `
                <span class="resumed-order-indicator">
                    <i class="fas fa-play me-2"></i>
                    RESUMED ORDER - Table ${this.resumedOrderTableName}
                </span>
            `;
        }
    }

    // Override holdOrder to handle running orders
    holdOrder() {
        if (this.cart.length === 0) {
            alert('Cart is empty!');
            return;
        }

        // Calculate total amount properly
        const totalAmount = this.cart.reduce((sum, item) => {
            const itemPrice = parseFloat(item.price) || 0;
            const itemQuantity = parseInt(item.quantity) || 0;
            return sum + (itemPrice * itemQuantity);
        }, 0);

        // Prepare order data with resumed order flag and unhold order ID for updates (like POS system)
        const orderData = {
            customer_name: 'Walk-in Customer',
            table_id: this.selectedTable ? this.selectedTable.id : null,
            order_mode: this.currentOrderType,
            total_amount: totalAmount,
            order_taker_id: window.orderTakerId,
            cart: this.cart,
            is_resumed_order: this.isResumedOrder || false,
            unhold_order_id: this.currentHoldOrderId || null // Use unhold_order_id like POS system
        };

        console.log('Sending running order data:', orderData);

        // Send to hold order endpoint
        fetch('ajax/tablet_hold_order.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(orderData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                let message;
                if (this.currentHoldOrderId) {
                    message = 'Order updated successfully!';
                } else if (this.isRunningOrder) {
                    message = 'Running order added successfully!';
                } else {
                    message = 'Order held successfully!';
                }
                alert(message);
                this.cart = [];
                this.updateCart();
                this.resetRunningOrderState();
                // Auto-logout after successful hold/update to prevent stale data
                window.location.href = 'tablet_logout.php';
            } else {
                alert('Error holding order: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error holding order:', error);
            alert('Error holding order. Please try again.');
        });
    }

    resetRunningOrderState() {
        this.isRunningOrder = false;
        this.runningOrderTableId = null;
        this.runningOrderTableName = null;
        this.currentHoldOrderId = null;
    }

    // Take-Away Order Actions
    createNewTakeAwayOrder() {
        // Clear any existing order context
        this.resetRunningOrderState();
        
        // Set up for new take-away order
        this.currentOrderType = 'take_away';
        this.selectedTable = null; // No table for take-away
        
        // Clear cart
        this.cart = [];
        this.updateCart();
        
        // Go to item selection screen
        this.showItemCartScreen();
    }

    async resumeTakeAwayOrder(orderId) {
        try {
            // Hide context menu
            this.hideTakeAwayContextMenu();

            // Fetch order data
            const response = await fetch(`load_held_order.php?id=${orderId}`);
            const data = await response.json();

            if (!data.success) {
                alert('Error loading order: ' + (data.error || 'Unknown error'));
                return;
            }

            // Clear current cart
            this.cart = [];

            // Set up order context for take-away
            this.isRunningOrder = true;
            this.runningOrderTableId = null; // No table for take-away
            this.runningOrderTableName = 'Take Away';
            this.currentHoldOrderId = orderId;

            // Set order type to take_away
            this.currentOrderType = 'take_away';

            // Load items into cart
            data.items.forEach(item => {
                // Parse modifiers if they exist
                let modifiers = [];
                if (item.modifiers && typeof item.modifiers === 'string') {
                    try {
                        modifiers = JSON.parse(item.modifiers);
                    } catch (e) {
                        console.error('Error parsing modifiers:', e);
                        modifiers = [];
                    }
                } else if (Array.isArray(item.modifiers)) {
                    modifiers = item.modifiers;
                }

                // Create unique identifier for cart items with modifiers
                const modifierCode = modifiers.map(m => m.id).sort().join('-');
                const uniqueId = modifierCode ? `${item.item_id}-mod-${modifierCode}` : item.item_id.toString();

                // Create modifier display text
                const modifierText = modifiers.map(m => m.name).join(', ');

                this.cart.push({
                    id: item.item_id,
                    uniqueId: uniqueId,
                    name: item.item_name,
                    modifierText: modifierText,
                    modifiers: modifiers,
                    price: parseFloat(item.unit_price) || 0,
                    basePrice: parseFloat(item.unit_price) || 0,
                    quantity: parseInt(item.quantity) || 1,
                    tax_rate: parseFloat(item.tax_rate) || 0.00,
                    remarks: item.remarks || ''
                });
            });

            // Show resumed order indicator
            this.showResumedTakeAwayIndicator();

            // Update cart display
            this.updateCart();

            // Go to item selection screen
            this.showItemCartScreen();

        } catch (error) {
            console.error('Error resuming take-away order:', error);
            alert('Error resuming order. Please try again.');
        }
    }

    showResumedTakeAwayIndicator() {
        const orderTypeElement = document.getElementById('current-order-type');
        if (orderTypeElement) {
            orderTypeElement.innerHTML = `
                <span class="resumed-order-indicator">
                    <i class="fas fa-play-circle me-2"></i>
                    RESUMED TAKE-AWAY ORDER
                </span>
            `;
        }
    }

    viewTakeAwayOrderDetails(orderId) {
        // Fetch order details and show modal
        fetch(`load_held_order.php?id=${orderId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showTakeAwayOrderDetailsModal(data.order, data.items);
                } else {
                    alert('Error loading order details: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error loading order details:', error);
                alert('Error loading order details. Please try again.');
            });
    }

    showTakeAwayOrderDetailsModal(order, items) {
        const modal = document.createElement('div');
        modal.className = 'takeaway-order-details-modal';
        
        // Generate items HTML with cash card design
        let itemsHtml = '';
        let totalItems = 0;
        
        items.forEach(item => {
            totalItems += parseInt(item.quantity);
            const modifiers = item.modifiers && item.modifiers.length > 0 ? 
                item.modifiers.map(m => m.name).join(', ') : '';
            
            itemsHtml += `
                <div class="card mb-2">
                    <div class="card-body p-3">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">${item.item_name}</h6>
                                <div class="text-muted small">
                                    <span class="badge bg-secondary me-2">Qty: ${item.quantity}</span>
                                    <span class="badge bg-info">Rs ${parseFloat(item.unit_price).toFixed(2)}</span>
                                </div>
                                ${modifiers ? `<div class="text-success small mt-1"><i class="fas fa-plus me-1"></i>${modifiers}</div>` : ''}
                                ${item.remarks ? `<div class="text-warning small mt-1"><i class="fas fa-comment me-1"></i>${item.remarks}</div>` : ''}
                            </div>
                            <div class="text-end">
                                <strong>Rs ${(parseFloat(item.unit_price) * parseInt(item.quantity)).toFixed(2)}</strong>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
        
        const orderTime = this.formatTime(order.created_at);
        const orderMode = order.order_mode ? order.order_mode.replace(/_/g, ' ').toUpperCase() : 'TAKE-AWAY';
        
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>Order Details</h3>
                        <button class="close-btn" onclick="this.closest('.takeaway-order-details-modal').remove()">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="card">
                            <div class="card-header bg-light">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-0">Order Summary</h6>
                                    <span class="badge bg-primary">${orderMode}</span>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <small class="text-muted">Customer</small>
                                        <div><strong>${order.customer_name || 'Walk-in'}</strong></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Order ID</small>
                                        <div><strong>HOLD-${String(order.id).padStart(6, '0')}</strong></div>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-6">
                                        <small class="text-muted">Created</small>
                                        <div><strong>${orderTime}</strong></div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Items</small>
                                        <div><strong>${totalItems} items</strong></div>
                                    </div>
                                </div>
                                
                                <hr>
                                
                                <h6 class="mb-3">Order Items (${items.length})</h6>
                                <div class="order-items-list" style="max-height: 300px; overflow-y: auto;">
                                    ${itemsHtml}
                                </div>
                                
                                <hr>
                                
                                ${this.generatePaymentBreakdown(order)}
                                
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">Total Amount</h5>
                                    <h5 class="mb-0 text-primary">Rs ${parseFloat(order.total_amount).toFixed(2)}</h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    // Generate payment breakdown for order details
    generatePaymentBreakdown(order) {
        // Check if payment method tax is enabled and we have tax settings
        if (!this.taxSettings || this.taxSettings.tax_method !== 'payment_method') {
            return '';
        }

        const paymentRates = this.taxSettings.payment_tax_rates || {};
        if (Object.keys(paymentRates).length === 0) {
            return '';
        }

        // Calculate subtotal from order items
        let subtotal = 0;
        if (order.items && order.items.length > 0) {
            order.items.forEach(item => {
                subtotal += parseFloat(item.unit_price) * parseInt(item.quantity);
            });
        } else {
            // Fallback to total amount if items not available
            subtotal = parseFloat(order.total_amount);
        }

        // Generate payment options (only Cash and Card)
        const paymentOptions = Object.entries(paymentRates)
            .filter(([method]) => method === 'cash' || method === 'card')
            .map(([method, rate]) => {
                const taxAmount = subtotal * (rate / 100);
                const total = subtotal + taxAmount;
                
                return `
                    <div class="payment-option d-flex justify-content-between align-items-center mb-2 p-2 border rounded bg-light">
                        <div>
                            <span class="fw-bold text-capitalize">${method}</span>
                            <small class="text-muted d-block">(${rate.toFixed(1)}% tax)</small>
                        </div>
                        <div class="text-end">
                            <div class="fw-bold text-primary">Rs ${total.toFixed(2)}</div>
                            <small class="text-muted">Rs ${subtotal.toFixed(2)} + Rs ${taxAmount.toFixed(2)}</small>
                        </div>
                    </div>
                `;
            }).join('');

        return `
            <div class="payment-breakdown mb-3">
                <h6 class="text-primary mb-2">
                    <i class="fas fa-credit-card me-1"></i>Payment Options
                </h6>
                <div class="payment-options">
                    ${paymentOptions}
                </div>
            </div>
        `;
    }

    // Format time helper (same as POS system)
    formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);
        
        if (diffMins < 1) {
            return 'Just now';
        } else if (diffMins < 60) {
            return `${diffMins}m ago`;
        } else if (diffHours < 24) {
            return `${diffHours}h ago`;
        } else if (diffDays < 7) {
            return `${diffDays}d ago`;
        } else {
            return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
        }
    }


    printTakeAwayProforma(orderId) {
        try {
            // Print proforma invoice for take-away order
            const printWindow = window.open(`print_proforma_invoice.php?id=${orderId}`, '_blank', 'width=400,height=600');
            
            if (printWindow) {
                // Focus the print window
                printWindow.focus();
            } else {
                alert('Please allow popups to print proforma invoice.');
            }
        } catch (error) {
            console.error('Proforma invoice print error:', error);
            alert('Error printing proforma invoice. Please try again.');
        }
    }

    // Resume Order Function - Load existing order into cart
    async resumeOrder(orderId, tableData) {
        try {
            // Hide context menu
            this.hideContextMenu();

            // Fetch order data
            const response = await fetch(`load_held_order.php?id=${orderId}`);
            const data = await response.json();

            if (!data.success) {
                alert('Error loading order: ' + (data.error || 'Unknown error'));
                return;
            }

            // Clear current cart
            this.cart = [];

            // Set up order context
            this.isResumedOrder = true;
            this.resumedOrderTableId = tableData.id;
            this.resumedOrderTableName = tableData.table_name;
            this.currentHoldOrderId = orderId; // Store the hold order ID for updates

            // Create table object for resumed order
            this.selectedTable = {
                id: tableData.id,
                table_name: tableData.table_name,
                status: 'occupied'
            };

            // Set order type to dine_in for resumed orders
            this.currentOrderType = 'dine_in';

            // Load items into cart
            data.items.forEach(item => {
                // Parse modifiers if they exist
                let modifiers = [];
                if (item.modifiers && typeof item.modifiers === 'string') {
                    try {
                        modifiers = JSON.parse(item.modifiers);
                    } catch (e) {
                        console.error('Error parsing modifiers:', e);
                        modifiers = [];
                    }
                } else if (Array.isArray(item.modifiers)) {
                    modifiers = item.modifiers;
                }

                // Create unique identifier for cart items with modifiers
                const modifierCode = modifiers.map(m => m.id).sort().join('-');
                const uniqueId = modifierCode ? `${item.item_id}-mod-${modifierCode}` : item.item_id.toString();

                // Create modifier display text
                const modifierText = modifiers.map(m => m.name).join(', ');

                this.cart.push({
                    id: item.item_id,
                    uniqueId: uniqueId,
                    name: item.item_name,
                    modifierText: modifierText,
                    modifiers: modifiers,
                    price: parseFloat(item.unit_price) || 0,
                    basePrice: parseFloat(item.unit_price) || 0,
                    quantity: parseInt(item.quantity) || 1,
                    tax_rate: parseFloat(item.tax_rate) || 0.00, // Add tax_rate field
                    remarks: item.remarks || ''
                });
            });

            // Show resumed order indicator
            this.showResumedOrderIndicator();

            // Update cart display
            this.updateCart();

            // Go to item selection screen
            this.showItemCartScreen();

            // Order loaded successfully - no popup needed

        } catch (error) {
            console.error('Error resuming order:', error);
            alert('Error resuming order. Please try again.');
        }
    }

    showResumedOrderIndicator() {
        // Add resumed order indicator to the order info
        const orderTypeElement = document.getElementById('current-order-type');
        if (orderTypeElement) {
            orderTypeElement.innerHTML = `
                <span class="resumed-order-indicator">
                    <i class="fas fa-play-circle me-2"></i>
                    RESUMED ORDER - Table ${this.runningOrderTableName}
                </span>
            `;
        }
    }

    // Print Order Function
    async printOrder(orderId) {
        try {
            // Print proforma invoice instead of KOT for tablet orders
            const printWindow = window.open(`print_proforma_invoice.php?id=${orderId}`, '_blank', 'width=400,height=600');
            
            if (printWindow) {
                // Focus the print window
                printWindow.focus();
            } else {
                alert('Please allow popups to print proforma invoice.');
            }
        } catch (error) {
            console.error('Proforma invoice print error:', error);
            alert('Error printing proforma invoice. Please try again.');
        }
    }

    // Context Menu Management
    initContextMenu() {
        // Create context menu element
        this.contextMenu = document.createElement('div');
        this.contextMenu.className = 'table-context-menu';
        this.contextMenu.style.display = 'none';
        document.body.appendChild(this.contextMenu);

        // Create take-away context menu element
        this.takeawayContextMenu = document.createElement('div');
        this.takeawayContextMenu.className = 'takeaway-context-menu';
        this.takeawayContextMenu.style.display = 'none';
        document.body.appendChild(this.takeawayContextMenu);

        // Add click event listener to hide context menu when clicking outside
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.takeaway-context-menu') && !e.target.closest('.takeaway-order-card')) {
                this.hideTakeAwayContextMenu();
            }
        });
    }

    showContextMenu(x, y, table, orders) {
        this.currentTableData = table;
        this.currentOrdersData = orders;
        
        // Position context menu
        this.contextMenu.style.left = x + 'px';
        this.contextMenu.style.top = y + 'px';
        
        // Generate context menu content
        this.contextMenu.innerHTML = this.generateContextMenuHTML(table, orders);
        
        // Show context menu
        this.contextMenu.style.display = 'block';
        
        // Adjust position if menu goes off screen
        this.adjustContextMenuPosition();
        
        // Add event listeners to context menu buttons
        this.bindContextMenuEvents();
    }

    hideContextMenu() {
        if (this.contextMenu) {
            this.contextMenu.style.display = 'none';
        }
        this.currentTableData = null;
        this.currentOrdersData = null;
    }

    // Take-Away Context Menu
    showTakeAwayContextMenu(event, orderId, orderReference, customerName) {
        event.preventDefault();
        event.stopPropagation();
        
        // Generate context menu content first
        this.takeawayContextMenu.innerHTML = this.generateTakeAwayContextMenuHTML(orderId, orderReference, customerName);
        
        // Show context menu (temporarily hidden for positioning)
        this.takeawayContextMenu.style.display = 'block';
        this.takeawayContextMenu.style.visibility = 'hidden';
        
        // Position context menu - try left side first to avoid hiding cart
        const cardRect = event.target.closest('.takeaway-order-card').getBoundingClientRect();
        const menuRect = this.takeawayContextMenu.getBoundingClientRect();
        
        // Try positioning to the left of the card first
        const leftPosition = cardRect.left - menuRect.width - 10;
        if (leftPosition > 10) {
            this.takeawayContextMenu.style.left = leftPosition + 'px';
            this.takeawayContextMenu.style.top = cardRect.top + 'px';
        } else {
            // Fallback to right side
            this.takeawayContextMenu.style.left = cardRect.right + 10 + 'px';
            this.takeawayContextMenu.style.top = cardRect.top + 'px';
        }
        
        // Make visible and adjust position if needed
        this.takeawayContextMenu.style.visibility = 'visible';
        this.adjustTakeAwayContextMenuPosition();
        
        // Add event listeners to context menu buttons
        this.bindTakeAwayContextMenuEvents();
    }

    generateTakeAwayContextMenuHTML(orderId, orderReference, customerName) {
        return `
            <div class="context-menu-header">
                <h4>${orderReference}</h4>
                <span class="context-menu-subtitle">${customerName}</span>
            </div>
            <div class="context-menu-actions">
                <button class="context-menu-btn resume-btn" data-action="resume-takeaway" data-order-id="${orderId}">
                    <i class="fas fa-play-circle"></i>
                    <span>Resume Order</span>
                </button>
                <button class="context-menu-btn view-btn" data-action="view-takeaway" data-order-id="${orderId}">
                    <i class="fas fa-eye"></i>
                    <span>View Details</span>
                </button>
                <button class="context-menu-btn print-btn" data-action="print-takeaway" data-order-id="${orderId}">
                    <i class="fas fa-print"></i>
                    <span>Print Proforma</span>
                </button>
            </div>
        `;
    }

    adjustTakeAwayContextMenuPosition() {
        const rect = this.takeawayContextMenu.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        
        // Try to position menu to the left of the card first (to avoid hiding cart)
        const cardRect = document.querySelector('.takeaway-order-card:hover, .takeaway-order-card:focus')?.getBoundingClientRect();
        if (cardRect) {
            // Position to the left of the card
            const leftPosition = cardRect.left - rect.width - 10;
            if (leftPosition > 10) {
                this.takeawayContextMenu.style.left = leftPosition + 'px';
                this.takeawayContextMenu.style.top = cardRect.top + 'px';
                return;
            }
        }
        
        // If left positioning doesn't work, use original logic but prefer left side
        if (rect.right > viewportWidth) {
            // Try to position to the left of the card
            const leftPosition = rect.left - rect.width - 20;
            if (leftPosition > 10) {
                this.takeawayContextMenu.style.left = leftPosition + 'px';
            } else {
                this.takeawayContextMenu.style.left = (viewportWidth - rect.width - 10) + 'px';
            }
        }
        
        // Ensure menu doesn't go off the left side
        if (rect.left < 10) {
            this.takeawayContextMenu.style.left = '10px';
        }
        
        // Adjust vertical position if menu goes off screen
        if (rect.bottom > viewportHeight) {
            this.takeawayContextMenu.style.top = (viewportHeight - rect.height - 10) + 'px';
        }
        
        // Ensure menu doesn't go off the top
        if (rect.top < 10) {
            this.takeawayContextMenu.style.top = '10px';
        }
    }

    bindTakeAwayContextMenuEvents() {
        // Bind events for context menu action buttons only
        const actionButtons = this.takeawayContextMenu.querySelectorAll('.context-menu-btn');
        actionButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                e.preventDefault();
                const action = btn.dataset.action;
                const orderId = btn.dataset.orderId;
                if (action) {
                    this.handleTakeAwayContextMenuAction(action, orderId);
                }
            });
        });
    }

    handleTakeAwayContextMenuAction(action, orderId) {
        // Hide context menu
        this.hideTakeAwayContextMenu();
        
        switch (action) {
            case 'resume-takeaway':
                this.resumeTakeAwayOrder(orderId);
                break;
            case 'view-takeaway':
                this.viewTakeAwayOrderDetails(orderId);
                break;
            case 'print-takeaway':
                this.printTakeAwayProforma(orderId);
                break;
            default:
                console.warn('Unknown take-away context menu action:', action);
        }
    }

    hideTakeAwayContextMenu() {
        if (this.takeawayContextMenu) {
            this.takeawayContextMenu.style.display = 'none';
        }
    }

    adjustContextMenuPosition() {
        const rect = this.contextMenu.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        
        // Adjust horizontal position if menu goes off screen
        if (rect.right > viewportWidth) {
            this.contextMenu.style.left = (viewportWidth - rect.width - 10) + 'px';
        }
        
        // Ensure menu doesn't go off the left side
        if (rect.left < 10) {
            this.contextMenu.style.left = '10px';
        }
        
        // Adjust vertical position if menu goes off screen
        if (rect.bottom > viewportHeight) {
            this.contextMenu.style.top = (viewportHeight - rect.height - 10) + 'px';
        }
        
        // Ensure menu doesn't go off the top
        if (rect.top < 10) {
            this.contextMenu.style.top = '10px';
        }
    }

    generateContextMenuHTML(table, orders) {
        const hasOrders = orders && orders.length > 0;
        const hasRunningOrders = hasOrders && orders.some(order => order.has_running_orders);
        
        let subtitle = 'No orders';
        if (hasOrders) {
            if (orders.length === 1) {
                subtitle = '1 order';
            } else {
                subtitle = `${orders.length} orders`;
            }
            if (hasRunningOrders) {
                subtitle += ' (with running orders)';
            }
        }
        
        return `
            <div class="context-menu-header">
                <h4>Table ${table.table_name}</h4>
                <span class="context-menu-subtitle">${subtitle}</span>
            </div>
            <div class="context-menu-actions">
                ${hasOrders ? `
                    <button class="context-menu-btn print-btn" data-action="print">
                        <i class="fas fa-print"></i>
                        <span>Print Order</span>
                    </button>
                ` : ''}
                                 <button class="context-menu-btn running-order-btn" data-action="resume-order">
                     <i class="fas fa-play-circle"></i>
                     <span>Resume Order</span>
                 </button>
                 ${hasOrders ? `
                     <button class="context-menu-btn transfer-btn" data-action="transfer-table">
                         <i class="fas fa-exchange-alt"></i>
                         <span>Transfer Table</span>
                     </button>
                     <button class="context-menu-btn view-details-btn" data-action="view-details">
                         <i class="fas fa-eye"></i>
                         <span>View Details</span>
                     </button>
                 ` : ''}
            </div>
        `;
    }

    bindContextMenuEvents() {
        const buttons = this.contextMenu.querySelectorAll('.context-menu-btn');
        
        buttons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                e.preventDefault();
                const action = btn.dataset.action;
                if (action) {
                    this.handleContextMenuAction(action);
                }
            });
        });
    }

    handleContextMenuAction(action) {
        // Store the data before hiding the context menu
        const tableData = this.currentTableData;
        const ordersData = this.currentOrdersData;
        
        console.log('Context menu action:', action, 'Table data:', tableData, 'Orders data:', ordersData);
        
        // Hide context menu after a small delay to ensure the click is processed
        setTimeout(() => {
            this.hideContextMenu();
        }, 100);
        
        switch (action) {
            case 'print':
                if (ordersData && ordersData.length > 0) {
                    if (ordersData.length === 1) {
                        // Print the single order
                        this.printOrder(ordersData[0].id);
                    } else {
                        // Show a simple alert for multiple orders (could be enhanced with a selection dialog)
                        alert(`Printing the most recent order (Order #${ordersData[0].id}).\n\nFor multiple orders, use "View Details" to see all orders.`);
                        this.printOrder(ordersData[0].id);
                    }
                } else {
                    alert('No orders available to print.');
                }
                break;
            case 'resume-order':
                if (tableData && ordersData && ordersData.length > 0) {
                    this.resumeOrder(ordersData[0].id, tableData);
                } else {
                    alert('No orders available to resume.');
                }
                break;
            case 'view-details':
                if (tableData) {
                    this.showOrderDetailsModal(tableData, ordersData);
                } else {
                    alert('Table data not available.');
                }
                break;
            case 'transfer-table':
                if (tableData && ordersData && ordersData.length > 0) {
                    this.showTransferModal(tableData, ordersData);
                } else {
                    alert('No orders available to transfer.');
                }
                break;
            default:
                console.warn('Unknown context menu action:', action);
        }
    }

    showOrderDetailsModal(table, orders) {
        const modal = document.createElement('div');
        modal.className = 'table-orders-modal';
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>Table ${table.table_name} - Order Details</h3>
                        <button class="close-btn" onclick="this.closest('.table-orders-modal').remove()">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="orders-list">
                            ${this.generateOrdersHTML(orders)}
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    // Table Transfer Management
    showTransferModal(table, orders) {
        // Store transfer data
        this.transferData = {
            source_table_id: table.id,
            source_table_name: table.table_name,
            source_orders: orders
        };

        const modal = document.createElement('div');
        modal.className = 'table-transfer-modal';
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-exchange-alt me-2"></i>Transfer Table</h3>
                        <button class="close-btn" onclick="this.closest('.table-transfer-modal').remove()">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="transfer-summary mb-3">
                            <div class="transfer-flow">
                                <div class="transfer-step">
                                    <div class="step-icon">
                                        <i class="fas fa-table"></i>
                                    </div>
                                    <div class="step-label">From</div>
                                    <div class="step-table">${table.table_name}</div>
                                </div>
                                <div class="transfer-arrow">
                                    <i class="fas fa-arrow-right"></i>
                                </div>
                                <div class="transfer-step">
                                    <div class="step-icon">
                                        <i class="fas fa-table"></i>
                                    </div>
                                    <div class="step-label">To</div>
                                    <div class="step-table" id="target-table-display">Select Table</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-5">
                                <div class="transfer-section">
                                    <div class="section-header">
                                        <h6><i class="fas fa-info-circle me-2"></i>Source Table</h6>
                                    </div>
                                    <div class="source-table-info">
                                        <div class="table-info">
                                            <strong>Table:</strong> ${table.table_name}<br>
                                            <strong>Orders:</strong> ${orders.length}<br>
                                            <strong>Total Amount:</strong> ${this.calculateTotalAmount(orders)}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-7">
                                <div class="transfer-section">
                                    <div class="section-header">
                                        <h6><i class="fas fa-list me-2"></i>Available Tables</h6>
                                        <button class="btn btn-sm btn-outline-primary" onclick="tabletOrderSystem.refreshAvailableTables()">
                                            <i class="fas fa-sync-alt"></i> Refresh
                                        </button>
                                    </div>
                                    <div class="target-tables-container" id="target-tables-container">
                                        <div class="loading-spinner">
                                            <i class="fas fa-spinner fa-spin"></i> Loading available tables...
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <div class="transfer-status" id="transfer-status"></div>
                        <div class="modal-actions">
                            <button class="btn btn-secondary" onclick="this.closest('.table-transfer-modal').remove()">Cancel</button>
                            <button class="btn btn-primary" id="confirm-transfer" disabled onclick="tabletOrderSystem.confirmTransfer()">
                                <i class="fas fa-exchange-alt me-2"></i>Transfer Order
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        // Load available tables
        this.loadAvailableTables();
    }

    calculateTotalAmount(orders) {
        let total = 0;
        orders.forEach(order => {
            if (order.items) {
                order.items.forEach(item => {
                    total += parseFloat(item.price) * parseInt(item.quantity);
                });
            }
        });
        return total.toFixed(2);
    }

    async loadAvailableTables() {
        try {
            console.log('Loading available tables...');
            const response = await fetch('ajax/tablet_table_transfer.php?action=get_available_tables');
            console.log('Response status:', response.status);
            
            const data = await response.json();
            console.log('Available tables response:', data);
            
            if (data.success) {
                this.renderTargetTableOptions(data.data);
            } else {
                console.error('Failed to load available tables:', data.message);
                document.getElementById('target-tables-container').innerHTML = 
                    `<div class="error-message">Error loading available tables: ${data.message}</div>`;
            }
        } catch (error) {
            console.error('Error loading available tables:', error);
            document.getElementById('target-tables-container').innerHTML = 
                '<div class="error-message">Failed to load available tables</div>';
        }
    }

    renderTargetTableOptions(tables) {
        const container = document.getElementById('target-tables-container');
        
        if (!tables || tables.length === 0) {
            container.innerHTML = '<div class="no-tables">No available tables found</div>';
            return;
        }

        let html = '<div class="target-tables-grid">';
        tables.forEach(table => {
            html += `
                <div class="target-table-card" data-table-id="${table.id}" data-table-name="${table.table_name}">
                    <div class="table-card-header">
                        <i class="fas fa-table"></i>
                        <span class="table-name">${table.table_name}</span>
                    </div>
                    <div class="table-card-body">
                        <div class="table-seats">${table.seats} Seats</div>
                        <div class="table-floor">${table.floor_name || 'Main Floor'}</div>
                    </div>
                    <button class="select-table-btn" onclick="tabletOrderSystem.selectTargetTable(${table.id}, '${table.table_name}')">
                        <i class="fas fa-check"></i> Select
                    </button>
                </div>
            `;
        });
        html += '</div>';
        
        container.innerHTML = html;
    }

    selectTargetTable(tableId, tableName) {
        // Remove selection from all cards
        document.querySelectorAll('.target-table-card').forEach(card => {
            card.classList.remove('selected');
            card.querySelector('.select-table-btn').innerHTML = '<i class="fas fa-check"></i> Select';
        });

        // Select this card
        const selectedCard = document.querySelector(`[data-table-id="${tableId}"]`);
        if (selectedCard) {
            selectedCard.classList.add('selected');
            selectedCard.querySelector('.select-table-btn').innerHTML = '<i class="fas fa-check"></i> Selected';
        }

        // Update transfer data
        this.transferData.target_table_id = tableId;
        this.transferData.target_table_name = tableName;

        // Update transfer flow display
        document.getElementById('target-table-display').textContent = tableName;

        // Enable transfer button
        document.getElementById('confirm-transfer').disabled = false;

        // Update transfer status
        this.updateTransferStatus();
    }

    updateTransferStatus() {
        const statusElement = document.getElementById('transfer-status');
        if (this.transferData.target_table_id) {
            statusElement.innerHTML = `
                <div class="status-ready">
                    <i class="fas fa-check-circle"></i>
                    Ready to transfer from ${this.transferData.source_table_name} to ${this.transferData.target_table_name}
                </div>
            `;
        } else {
            statusElement.innerHTML = `
                <div class="status-waiting">
                    <i class="fas fa-info-circle"></i>
                    Please select a target table
                </div>
            `;
        }
    }

    async refreshAvailableTables() {
        const refreshBtn = document.querySelector('.btn-outline-primary');
        const originalText = refreshBtn.innerHTML;
        
        refreshBtn.disabled = true;
        refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Refreshing...';
        
        await this.loadAvailableTables();
        
        refreshBtn.disabled = false;
        refreshBtn.innerHTML = originalText;
    }

    async confirmTransfer() {
        if (!this.transferData.target_table_id) {
            alert('Please select a target table.');
            return;
        }

        // Show confirmation dialog
        if (!confirm(`Transfer order from ${this.transferData.source_table_name} to ${this.transferData.target_table_name}?`)) {
            return;
        }

        const confirmBtn = document.getElementById('confirm-transfer');
        const originalText = confirmBtn.innerHTML;
        
        try {
            // Show loading state
            confirmBtn.disabled = true;
            confirmBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Transferring...';
            
            const response = await fetch('ajax/tablet_table_transfer.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'transfer_order',
                    source_table_id: this.transferData.source_table_id,
                    target_table_id: this.transferData.target_table_id,
                    hold_order_id: this.transferData.source_orders[0].id
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                // Show success message
                alert(`Order transferred successfully from ${this.transferData.source_table_name} to ${this.transferData.target_table_name}`);
                
                // Close modal
                document.querySelector('.table-transfer-modal').remove();
                
                // Refresh table status
                this.loadTables();
            } else {
                alert('Transfer failed: ' + (data.message || 'Unknown error'));
            }
        } catch (error) {
            console.error('Transfer error:', error);
            alert('Failed to transfer order. Please try again.');
        } finally {
            // Reset button state
            confirmBtn.disabled = false;
            confirmBtn.innerHTML = originalText;
        }
    }

    // ===== TEMPLATE FUNCTIONS =====
    
    // Show template selection modal for tablet
    showTemplateSelectionModal(uniqueId, event) {
        event.stopPropagation(); // Prevent cart item click
        
        fetch('ajax/get_modifier_templates.php')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.templates.length > 0) {
                    // Get cart item details
                    const item = this.cart.find(cartItem => cartItem.uniqueId === uniqueId);
                    if (item) {
                        this.createTemplateSelectionModal(uniqueId, item.name, item.price, data.templates);
                    }
                }
            });
    }

    // Create template selection modal for tablet
    createTemplateSelectionModal(uniqueId, itemName, itemPrice, templates) {
        const modalHtml = `
            <div class="modal fade" id="tabletTemplateSelectionModal" tabindex="-1" data-bs-backdrop="static">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Customize: ${itemName}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="text-center mb-3">
                                <h6>Base Price: Rs ${itemPrice.toFixed(2)}</h6>
                                <h5 id="tabletTemplateSelectionTotalPrice">Total: Rs ${itemPrice.toFixed(2)}</h5>
                            </div>
                            <div class="template-selection">
                                <h6 class="mb-3">Select Template:</h6>
                                <div class="row">
                                    ${templates.map(template => `
                                        <div class="col-md-6 mb-3">
                                            <div class="template-card" onclick="tabletOrderSystem.selectTemplate(${template.id}, '${uniqueId}', '${itemName}', ${itemPrice})">
                                                <div class="template-icon-large">
                                                    <i class="fas fa-${template.icon}"></i>
                                                </div>
                                                <div class="template-name">${template.name}</div>
                                            </div>
                                        </div>
                                    `).join('')}
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal
        const existingModal = document.getElementById('tabletTemplateSelectionModal');
        if (existingModal) existingModal.remove();
        
        // Add modal to body
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('tabletTemplateSelectionModal'));
        modal.show();
    }

    // Select template and show options for tablet
    selectTemplate(templateId, uniqueId, itemName, itemPrice) {
        // Close template selection modal
        const selectionModal = document.getElementById('tabletTemplateSelectionModal');
        if (selectionModal) {
            bootstrap.Modal.getInstance(selectionModal).hide();
        }
        
        // Now show template options modal
        fetch(`ajax/get_template_options.php?template_id=${templateId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.createTemplateModal(templateId, uniqueId, itemName, itemPrice, data.options);
                }
            });
    }

    // Create template options modal for tablet
    createTemplateModal(templateId, uniqueId, itemName, itemPrice, options) {
        const modalHtml = `
            <div class="modal fade" id="tabletTemplateModal" tabindex="-1" data-bs-backdrop="static">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Customize: ${itemName}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="text-center mb-4">
                                <div class="alert alert-info">
                                    <h6 class="mb-1">Base Price: Rs ${itemPrice.toFixed(2)}</h6>
                                    <h5 class="mb-0" id="tabletTemplateTotalPrice">Total: Rs ${itemPrice.toFixed(2)}</h5>
                                </div>
                            </div>
                            <div class="mb-3">
                                <h6 class="text-center">Select Option:</h6>
                            </div>
                            <div class="template-options">
                                ${options.map(option => `
                                    <div class="template-option" onclick="tabletOrderSystem.selectTemplateOption('option_${option.id}')">
                                        <input class="form-check-input" type="radio" name="template_option" 
                                               value="${option.id}" id="option_${option.id}" 
                                               data-price="${option.price_adjustment}">
                                        <label class="form-check-label" for="option_${option.id}">
                                            <strong>${option.name}</strong>
                                            ${option.price_adjustment > 0 ? `<span class="text-success">(+Rs ${option.price_adjustment})</span>` : ''}
                                        </label>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="tabletConfirmTemplateBtn">Add to Cart</button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Remove existing modal
        const existingModal = document.getElementById('tabletTemplateModal');
        if (existingModal) existingModal.remove();
        
        // Add modal to body
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // Show modal
        const modal = new bootstrap.Modal(document.getElementById('tabletTemplateModal'));
        modal.show();
        
        // Bind events
        this.bindTabletTemplateModalEvents(templateId, uniqueId, itemName, itemPrice);
    }

    // Bind tablet template modal events
    bindTabletTemplateModalEvents(templateId, uniqueId, itemName, itemPrice) {
        const modal = document.getElementById('tabletTemplateModal');
        const totalPriceEl = document.getElementById('tabletTemplateTotalPrice');
        const confirmBtn = document.getElementById('tabletConfirmTemplateBtn');
        
        // Update total price when option changes
        modal.querySelectorAll('input[name="template_option"]').forEach(input => {
            input.addEventListener('change', function() {
                const selectedOption = modal.querySelector('input[name="template_option"]:checked');
                if (selectedOption) {
                    const priceAdjustment = parseFloat(selectedOption.dataset.price);
                    const newTotal = itemPrice + priceAdjustment;
                    totalPriceEl.textContent = `Total: Rs ${newTotal.toFixed(2)}`;
                }
            });
        });
        
        // Confirm button
        confirmBtn.addEventListener('click', function() {
            const selectedOption = modal.querySelector('input[name="template_option"]:checked');
            if (selectedOption) {
                const priceAdjustment = parseFloat(selectedOption.dataset.price);
                const finalPrice = itemPrice + priceAdjustment;
                const optionName = selectedOption.nextElementSibling.textContent.trim();
                
                // Add template modifier to cart item
                tabletOrderSystem.addTemplateToCartItem(uniqueId, optionName, templateId, selectedOption.value, priceAdjustment);
                
                // Close modal
                bootstrap.Modal.getInstance(modal).hide();
            }
        });
    }

    // Select template option by clicking on the card
    selectTemplateOption(optionId) {
        const radioInput = document.getElementById(optionId);
        if (radioInput) {
            radioInput.checked = true;
            
            // Trigger change event to update price
            const changeEvent = new Event('change');
            radioInput.dispatchEvent(changeEvent);
        }
    }

    // Add template modifier to cart item
    addTemplateToCartItem(uniqueId, modifierText, templateId, optionId, priceAdjustment) {
        const item = this.cart.find(cartItem => cartItem.uniqueId === uniqueId);
        if (item) {
            // Update item price
            item.price = item.price + priceAdjustment;
            
            // Add template modifier to modifiers array
            if (!item.modifiers) {
                item.modifiers = [];
            }
            
            const templateModifier = {
                template_id: templateId,
                option_id: optionId,
                name: modifierText,
                price_adjustment: priceAdjustment
            };
            
            item.modifiers.push(templateModifier);
            
            // Update modifier text display
            const allModifiers = item.modifiers.map(mod => mod.name).join(', ');
            item.modifierText = allModifiers;
            
            // Update cart display
            this.updateCart();
        }
    }
}

// Global instance
let tabletOrderSystem;

// Initialize function called from PHP
function initializeTabletOrder(itemsData, categoriesData, tablesData) {
    tabletOrderSystem = new TabletOrderSystem(itemsData, categoriesData, tablesData);
}

// Global functions for onclick handlers
function refreshTablet() {
    location.reload();
}

function showSettings() {
    alert('Settings functionality will be implemented here');
}

function logout() {
    if (confirm('Are you sure you want to logout?')) {
        window.location.href = 'tablet_logout.php';
    }
}

// Prevent zoom on input focus
document.addEventListener('DOMContentLoaded', function() {
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.style.fontSize = '16px';
        });
    });
});

// Prevent context menu on long press
document.addEventListener('contextmenu', function(e) {
    e.preventDefault();
});

// Prevent double tap zoom
let lastTouchEnd = 0;
document.addEventListener('touchend', function(event) {
    const now = (new Date()).getTime();
    if (now - lastTouchEnd <= 300) {
        event.preventDefault();
    }
    lastTouchEnd = now;
}, false);
