<?php
include 'db.php';


if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Get KDS settings
$enable_kds = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'enable_kds'")->fetch_assoc()['setting_value'] ?? '1';
$auto_refresh_interval = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'auto_refresh_interval'")->fetch_assoc()['setting_value'] ?? '30';
$sound_notifications = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'sound_enabled'")->fetch_assoc()['setting_value'] ?? '1';
$order_timeout = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'order_timeout_minutes'")->fetch_assoc()['setting_value'] ?? '45';

// Get active stations
$stations = $conn->query("SELECT * FROM kds_stations WHERE is_active = 1 ORDER BY sort_order, name");

// Get current user info
$user_id = $_SESSION['user_id'] ?? null;
$user_name = $_SESSION['user_name'] ?? 'Kitchen Staff';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kitchen Display System - ITRPOS</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- Feather Icons -->
    <script src="https://unpkg.com/feather-icons"></script>
    
    <!-- Custom KDS CSS -->
    <link rel="stylesheet" href="assets/css/kds.css">
    
</head>
<body>
    <!-- Connection Status -->
    <div class="connection-status">
        <i class="fas fa-wifi"></i>
        <span id="connection-status">Connected</span>
    </div>
    
    

         <!-- KDS Header -->
     <div class="kds-header">
         <div class="header-container">
             <div class="header-left">
                 <div class="header-logo">
                     <i class="fas fa-utensils"></i>
                     ITR POS KDS
                 </div>
                 <div class="station-selector-header">
                     <div class="d-flex align-items-center">
                         <label for="station-select" class="me-2 text-white fw-bold">
                             <i class="fas fa-fire me-1"></i>Station:
                         </label>
                         <select id="station-select" class="form-select station-dropdown-header">
                             <option value="0">All Stations</option>
                             <?php while ($station = $stations->fetch_assoc()): ?>
                                 <option value="<?= $station['id'] ?>" data-color="<?= htmlspecialchars($station['color']) ?>">
                                     <?= htmlspecialchars($station['name']) ?>
                                 </option>
                             <?php endwhile; ?>
                         </select>
                     </div>
                 </div>
             </div>
             
             <div class="header-center">
                 <div class="current-time-display">
                     <i class="fas fa-clock me-1"></i>
                     <span id="current-time"><?= date('H:i:s') ?></span>
                 </div>
             </div>
             
             <div class="header-right">
                 <div class="header-buttons">
                     <button class="btn btn-light btn-sm" onclick="manualRefresh()">
                         <i class="fas fa-sync-alt me-1"></i>
                         Refresh
                     </button>
                     <a href="order_history.php" class="btn btn-outline-light btn-sm">
                         <i class="fas fa-history me-1"></i>
                         Order History
                     </a>
                 </div>
                 <div class="refresh-indicator">
                     <i class="fas fa-sync-alt"></i>
                     <span id="refresh-countdown"><?= $auto_refresh_interval ?></span>s
                 </div>
             </div>
         </div>
     </div>



    <!-- Orders Container -->
    <div id="orders-container" class="orders-grid">
        <!-- Orders will be loaded here -->
    </div>

    <!-- Audio Elements -->
    <audio id="new-order-sound" preload="auto">
        <source src="assets/sounds/new-order.mp3" type="audio/mpeg">
    </audio>
    <audio id="order-ready-sound" preload="auto">
        <source src="assets/sounds/order-ready.mp3" type="audio/mpeg">
    </audio>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // KDS Configuration
        const KDS_CONFIG = {
            currentStation: 0,
            autoRefreshInterval: <?= intval($auto_refresh_interval) * 1000 ?>,
            soundEnabled: <?= $sound_notifications === '1' ? 'true' : 'false' ?>,
            orderTimeout: <?= intval($order_timeout) * 60 * 1000 ?>, // Convert to milliseconds
            lastOrderCount: 0
        };

        // Dynamic height calculation system
        function getAvailableHeight() {
            const header = document.querySelector('.kds-header');
            const headerHeight = header ? header.offsetHeight : 0;
            const padding = 30; // Account for padding/margins and potential browser UI
            return window.innerHeight - headerHeight - padding;
        }
        
        function updateLayoutHeights() {
            const availableHeight = getAvailableHeight();
            const ordersGrid = document.getElementById('orders-container');
            const ordersColumns = document.querySelectorAll('.orders-column');
            
            if (ordersGrid) {
                ordersGrid.style.height = availableHeight + 'px';
            }
            
            ordersColumns.forEach(column => {
                column.style.height = (availableHeight - 20) + 'px'; // 20px for grid padding
            });
        }

        // Initialize KDS
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Feather icons
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
            
            // Set initial layout heights
            updateLayoutHeights();
            
            // Load initial orders
            loadOrders();
            
            // Set up auto refresh
            if (KDS_CONFIG.autoRefreshInterval > 0) {
                startAutoRefresh();
            }
            
            // Set up station dropdown listener
            const stationSelect = document.getElementById('station-select');
            if (stationSelect) {
                stationSelect.addEventListener('change', function() {
                    // Update current station
                    KDS_CONFIG.currentStation = this.value;
                    
                    // Load orders for this station
                    loadOrders();
                    
                    // Update ready button texts
                    setTimeout(updateReadyButtonTexts, 200);
                });
            }
            
            // Update current time
            setInterval(updateCurrentTime, 1000);
            
            // Handle window resize for column recalculation
            window.addEventListener('resize', function() {
                // Debounce resize events
                clearTimeout(window.resizeTimeout);
                window.resizeTimeout = setTimeout(function() {
                    updateLayoutHeights(); // Update heights first
                    loadOrders(); // Then reload orders to recalculate columns
                }, 250);
            });
        });

        // Load orders from server
        function loadOrders() {
            const params = new URLSearchParams();
            if (KDS_CONFIG.currentStation > 0) {
                params.append('station', KDS_CONFIG.currentStation);
            }
            
            fetch(`ajax/kds_get_orders.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayOrders(data.orders);
                        checkForNewOrders(data.orders.length);
                        document.getElementById('connection-status').innerHTML = '<span class="text-success">Connected</span>';
                    } else {
                        console.error('Error loading orders:', data.message);
                        document.getElementById('connection-status').innerHTML = '<span class="text-warning">Error</span>';
                    }
                })
                .catch(error => {
                    console.error('Network error:', error);
                    document.getElementById('connection-status').innerHTML = '<span class="text-danger">Disconnected</span>';
                });
        }

        // Display orders in the container - PROFESSIONAL NO-SPLIT LAYOUT
        function displayOrders(orders) {
            const container = document.getElementById('orders-container');
            
            if (orders.length === 0) {
                container.innerHTML = `
                    <div class="no-orders">
                        <i class="fas fa-clipboard-list"></i>
                        <h3>No Orders Available</h3>
                        <p>Orders will appear here when they are placed</p>
                    </div>
                `;
                return;
            }

            // Create columns and distribute complete orders only
            const columns = createOrderColumns(orders);
            
            console.log(`KDS: Displaying ${orders.length} orders across ${columns.length} columns`);
            
            let html = '';
            columns.forEach((column, columnIndex) => {
                html += '<div class="orders-column">';
                column.forEach((orderData, orderIndex) => {
                    // Only render complete orders - no splitting
                    html += createOrderCard(orderData.order, false, null, null);
                });
                html += '</div>';
            });
            
            container.innerHTML = html;
            
            // Update heights after content is loaded
            setTimeout(() => {
                updateLayoutHeights();
            }, 50);
            
            // Debug: Log any potential issues
            const renderedOrders = container.querySelectorAll('.order-card');
            if (renderedOrders.length !== orders.length) {
                console.warn(`KDS Warning: Expected ${orders.length} orders, but rendered ${renderedOrders.length}`);
            }
        }
        
                 // Create columns with complete orders only - NO SPLITTING - PROFESSIONAL KDS
         function createOrderColumns(orders) {
             const columns = [];
             const maxColumnHeight = getAvailableHeight() - 60; // Extra margin for safety
             let currentColumn = [];
             let currentHeight = 0;
             
             // Calculate how many columns we can fit based on screen width
             const screenWidth = window.innerWidth;
             const columnWidth = 380; // Column width + gap
             const maxColumns = Math.max(1, Math.floor(screenWidth / columnWidth));
             
            orders.forEach(order => {
                const estimatedHeight = estimateOrderHeight(order);
                
                // Check if order fits in current column
                if (currentHeight + estimatedHeight <= maxColumnHeight) {
                    // Order fits - add to current column
                    currentColumn.push({
                        order: order,
                        isSplit: false,
                        splitType: null,
                        splitIndex: null
                    });
                    currentHeight += estimatedHeight;
                } else {
                    // Order doesn't fit - start new column with this order
                    // First, save the current column if it has orders
                    if (currentColumn.length > 0) {
                        columns.push(currentColumn);
                    }
                    
                    // Start new column with this order
                    currentColumn = [{
                        order: order,
                        isSplit: false,
                        splitType: null,
                        splitIndex: null
                    }];
                    currentHeight = estimatedHeight;
                }
            });
            
            // Add the last column if it has orders
            if (currentColumn.length > 0) {
                columns.push(currentColumn);
            }
            
            // If we have more columns than can fit on screen, redistribute orders
            if (columns.length > maxColumns) {
                return redistributeOrdersAcrossColumns(orders, maxColumns, maxColumnHeight);
            }
            
            return columns;
        }
        
                 // Estimate order height based on number of items - COMPACT FOR NO SCROLLING
         function estimateOrderHeight(order) {
             const baseHeight = 180; // Header + footer + padding
             const itemHeight = 45; // Slightly increased for better accuracy including modifiers
             const itemsCount = order.items ? order.items.length : 0;
             
             // Account for running orders and special badges
             let extraHeight = 0;
             if (order.is_running_order || (order.notes && order.notes.includes('RUNNING ORDER'))) {
                 extraHeight += 25; // Running order badge
             }
             if (order.order_status === 'cancelled' || (order.notes && order.notes.includes('CANCELLED'))) {
                 extraHeight += 25; // Cancelled badge
             }
             
             return baseHeight + (itemsCount * itemHeight) + extraHeight;
         }
        
                 // Redistribute orders across available columns - PROFESSIONAL DISTRIBUTION
         function redistributeOrdersAcrossColumns(orders, maxColumns, maxColumnHeight) {
             const columns = [];
             
             // Initialize empty columns
             for (let i = 0; i < maxColumns; i++) {
                 columns.push([]);
             }
             
             // Track height of each column
             const columnHeights = new Array(maxColumns).fill(0);
             
             // Distribute orders to columns with least height (balanced distribution)
             orders.forEach(order => {
                 const estimatedHeight = estimateOrderHeight(order);
                 
                 // Find column with minimum height that can fit this order
                 let bestColumnIndex = 0;
                 let minHeight = columnHeights[0];
                 
                 for (let i = 1; i < maxColumns; i++) {
                     if (columnHeights[i] < minHeight && 
                         columnHeights[i] + estimatedHeight <= maxColumnHeight) {
                         minHeight = columnHeights[i];
                         bestColumnIndex = i;
                     }
                 }
                 
                 // Add order to the best column
                 columns[bestColumnIndex].push({
                     order: order,
                     isSplit: false,
                     splitType: null,
                     splitIndex: null
                 });
                 
                 columnHeights[bestColumnIndex] += estimatedHeight;
             });
             
             // Remove empty columns
             return columns.filter(column => column.length > 0);
         }

        // Create order card HTML - SIMPLIFIED NO-SPLIT VERSION
        function createOrderCard(order, isSplit = false, splitType = null, splitIndex = null) {
            const orderTime = new Date(order.created_at).toLocaleTimeString();
            const elapsedTime = getElapsedTime(order.created_at);
            const isTimeout = order.time_elapsed > KDS_CONFIG.orderTimeout;
            
            let itemsHtml = '';
            order.items.forEach(item => {
                // Check if this specific item is newly added (not the entire order)
                const isNewItem = item.item_status_type === 'new';
                const isQuantityChanged = item.item_status_type === 'quantity_changed';
                
                let runningOrderLabel = '';
                if (isNewItem) {
                    runningOrderLabel = '<span class="running-order-item-label">New Item</span>';
                } else if (isQuantityChanged) {
                    runningOrderLabel = '<span class="running-order-item-label">Updated</span>';
                }
                
                // Parse special_instructions to separate template, modifiers and remarks
                const specialInstructions = item.special_instructions || '';
                const parts = specialInstructions.split(' | ');

                let templateDisplay = '';
                let modifierDisplay = '';
                let remarksDisplay = '';

                parts.forEach(part => {
                    if (part.startsWith('TEMPLATE: ')) {
                        const templateName = part.replace('TEMPLATE: ', '');
                        templateDisplay = `<div class="item-template">
                            <i class="fas fa-layer-group me-1"></i>Template: ${templateName}
                        </div>`;
                    } else if (part.startsWith('REMARKS: ')) {
                        const remarks = part.replace('REMARKS: ', '');
                        remarksDisplay = `<div class="item-remarks">
                            <i class="fas fa-comment me-1"></i>${remarks}
                        </div>`;
                    } else if (part && !part.startsWith('TEMPLATE: ') && !part.startsWith('REMARKS: ')) {
                        // This is a modifier
                        modifierDisplay = `<div class="item-modifiers">
                            <i class="fas fa-tags me-1"></i>${part}
                        </div>`;
                    }
                });
                
                itemsHtml += `
                    <div class="item-row" data-item-id="${item.id}">
                        <div class="d-flex align-items-start flex-grow-1">
                            <span class="item-quantity me-3" style="color:black;background-color:white;font-size:20px">${item.quantity}</span>
                            <div class="flex-grow-1">
                                <div class="d-flex align-items-center">
                                    <span class="item-name me-2">${item.item_name}</span>
                                    ${runningOrderLabel}
                                </div>
                                ${templateDisplay}
                                ${modifierDisplay}
                                ${remarksDisplay}
                            </div>
                        </div>
                        <div class="d-flex align-items-center flex-shrink-0 ms-2">
                            ${(item.item_status && item.item_status !== 'pending') ? `<span class="item-status ${item.item_status}">${item.item_status.replace('_', ' ')}</span>` : ''}
                        </div>
                    </div>
                `;
            });

            let tableFloorInfo = '';
            let orderTypeBadge = '';
            let orderNumberDisplay = '';
            
            // Display order type and table information
            if (order.order_type === 'dine_in') {
                if (order.table_name) {
                    const floorInfo = order.floor_name ? ` | Floor: <span class="floor-name">${order.floor_name}</span>` : '';
                    tableFloorInfo = `<div class="table-floor-info">Table: <span class="table-name">${order.table_name}</span>${floorInfo}</div>`;
                }
                orderTypeBadge = '<span class="order-type-badge dine-in">Dine In</span>';
                orderNumberDisplay = `<div class="order-number">Order #${order.order_number}</div>`;
            } else if (order.order_type === 'take_away') {
                orderTypeBadge = '<span class="order-type-badge take_away">Take Away</span>';
                orderNumberDisplay = `<div class="table-floor-info">Order #${order.order_number}</div>`;
            } else if (order.order_type === 'delivery') {
                orderTypeBadge = '<span class="order-type-badge delivery">Delivery</span>';
                orderNumberDisplay = `<div class="table-floor-info">Order #${order.order_number}</div>`;
            } else {
                orderTypeBadge = `<span class="order-type-badge">${order.order_type}</span>`;
                orderNumberDisplay = `<div class="table-floor-info">Order #${order.order_number}</div>`;
            }

            let priorityBadge = '';
            if (order.priority === 'urgent') {
                priorityBadge = '<span class="priority-indicator urgent"></span>URGENT';
            } else if (order.priority === 'rush') {
                priorityBadge = '<span class="priority-indicator rush"></span>RUSH';
            }

            // Check for RUNNING ORDER and POST-SERVICE ORDER tags - only show if there are actually new items
            let runningOrderBadge = '';
            const hasNewItems = order.items && order.items.some(item => item.item_status_type === 'new');
            
            if (order.notes && order.notes.includes('POST-SERVICE ORDER')) {
                runningOrderBadge = '<span class="post-service-order-badge">POST-SERVICE ORDER - ADDITIONAL ITEMS</span>';
            } else if (hasNewItems) {
                if (order.notes && order.notes.includes('ADDITIONAL ITEMS')) {
                    runningOrderBadge = '<span class="running-order-badge">RUNNING ORDER - ADDITIONAL ITEMS</span>';
                } else {
                    runningOrderBadge = '<span class="running-order-badge">RUNNING ORDER</span>';
                }
            }

            // Check for CANCELLED order
            let cancelledOrderBadge = '';
            if (order.order_status === 'cancelled' || (order.notes && order.notes.includes('CANCELLED'))) {
                cancelledOrderBadge = '<span class="cancelled-order-badge">CANCELLED</span>';
            }

            // Add cancelled class if order is cancelled
            const cancelledClass = (order.order_status === 'cancelled' || (order.notes && order.notes.includes('CANCELLED'))) ? 'cancelled' : '';
            
                         // REMOVED: Split order logic - always show complete orders
             
             // For regular orders and continued orders, show full header
             return `
                 <div class="order-card ${order.calculated_status} ${order.priority === 'urgent' || order.priority === 'rush' ? 'urgent' : ''} ${hasNewItems ? 'running-order' : ''} ${cancelledClass}" data-order-id="${order.id}">
                     ${runningOrderBadge}
                     ${cancelledOrderBadge}
                     <div class="order-header" id="order-header-${order.id}">
                         <div class="d-flex justify-content-between align-items-center">
                             <div>
                                 ${tableFloorInfo}
                                 ${orderNumberDisplay}
                                 ${orderTypeBadge}
                                 <div class="order-time" id="order-time-${order.id}">
                                     <i class="fas fa-clock me-1"></i>
                                     <span class="countdown-timer" data-order-id="${order.id}" data-created-time="${order.created_at}">
                                         Loading...
                                     </span>
                                     <small class="timing-source ms-2" style="font-size: 0.8em; opacity: 0.7;">
                                         (${order.station_timing || 22}min)
                                     </small>
                                 </div>
                             </div>
                             <div class="text-end">
                                 <div class="customer-name">${order.customer_name}</div>
                                 <div class="priority-info">${priorityBadge}</div>
                             </div>
                         </div>
                     </div>
                     
                     <div class="order-body">
                         <div class="items-list">
                             ${itemsHtml}
                         </div>
                     </div>
                     
                     <div class="order-actions-container">
                         <button class="ready-button" onclick="markOrderServed(${order.id})">
                             <i class="fas fa-check me-2"></i>
                            <span id="ready-button-text-${order.id}">Ready</span>
                         </button>
                     </div>
                 </div>
                 ${splitType === 'continued' ? continuationIndicator : ''}
             `;
        }

                 // Mark station-specific items as served when clicked
         function markOrderServed(orderId) {
             const currentStation = KDS_CONFIG.currentStation;
             
             // If viewing all stations, mark entire order as served (legacy behavior)
             if (currentStation == 0) {
                 fetch('ajax/kds_update_order.php', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         action: 'update_order_status',
                         order_id: orderId,
                         status: 'served'
                     })
                 })
                 .then(response => response.json())
                 .then(data => {
                     if (data.success) {
                         // Add visual feedback and hide the order
                         const orderCard = document.querySelector(`[data-order-id="${orderId}"]`);
                         if (orderCard) {
                             // Add served animation
                             orderCard.classList.add('order-ready');
                             orderCard.style.animation = 'fadeOut 1s ease-in-out';
                             
                             // Play sound if enabled
                             if (KDS_CONFIG.soundEnabled) {
                                 const sound = document.getElementById('order-ready-sound');
                                 if (sound) {
                                     sound.play().catch(error => {
                                         console.log('Sound file not available:', error);
                                     });
                                 }
                             }
                             
                             // Remove order card after 1 second
                             setTimeout(() => {
                                 orderCard.remove();
                             }, 1000);
                         }
                     } else {
                         alert('Error updating order: ' + data.message);
                     }
                 })
                 .catch(error => {
                     console.error('Error:', error);
                     alert('Network error occurred');
                 });
             } else {
                 // Mark only items from current station as served
                 fetch('ajax/kds_update_order.php', {
                     method: 'POST',
                     headers: {
                         'Content-Type': 'application/json',
                     },
                     body: JSON.stringify({
                         action: 'update_station_items',
                         order_id: orderId,
                         station_id: currentStation,
                         status: 'served'
                     })
                 })
                 .then(response => response.json())
                 .then(data => {
                     if (data.success) {
                         // Add visual feedback and hide the order
                         const orderCard = document.querySelector(`[data-order-id="${orderId}"]`);
                         if (orderCard) {
                             // Add served animation
                             orderCard.classList.add('order-ready');
                             orderCard.style.animation = 'fadeOut 1s ease-in-out';
                             
                             // Play sound if enabled
                             if (KDS_CONFIG.soundEnabled) {
                                 const sound = document.getElementById('order-ready-sound');
                                 if (sound) {
                                     sound.play().catch(error => {
                                         console.log('Sound file not available:', error);
                                     });
                                 }
                             }
                             
                             // Remove order card after 1 second
                             setTimeout(() => {
                                 orderCard.remove();
                             }, 1000);
                         }
                     } else {
                         alert('Error updating order: ' + data.message);
                     }
                 })
                 .catch(error => {
                     console.error('Error:', error);
                     alert('Network error occurred');
                 });
             }
        }

        // Get action buttons for order - REMOVED ALL BUTTONS
        function getOrderActionButtons(order) {
            // No buttons needed - orders are clicked to mark as ready
            return '';
        }





        // Check for new orders and play sound
        function checkForNewOrders(currentCount) {
            if (currentCount > KDS_CONFIG.lastOrderCount && KDS_CONFIG.soundEnabled) {
                const sound = document.getElementById('new-order-sound');
                if (sound) {
                    sound.play().catch(error => {
                        console.log('Sound file not available:', error);
                    });
                }
            }
            KDS_CONFIG.lastOrderCount = currentCount;
        }

        // Get elapsed time
        function getElapsedTime(createdAt) {
            const now = new Date();
            const created = new Date(createdAt);
            const diff = Math.floor((now - created) / 1000 / 60); // minutes
            
            if (diff < 1) return 'Just now';
            if (diff < 60) return `${diff}m ago`;
            
            const hours = Math.floor(diff / 60);
            const minutes = diff % 60;
            return `${hours}h ${minutes}m ago`;
        }

        // Update current time
        function updateCurrentTime() {
            const now = new Date();
            document.getElementById('current-time').textContent = now.toLocaleTimeString();
        }

        // Start auto refresh
        function startAutoRefresh() {
            let countdown = KDS_CONFIG.autoRefreshInterval / 1000;
            
            // Update countdown display immediately
            document.getElementById('refresh-countdown').textContent = countdown;
            
            const refreshInterval = setInterval(() => {
                countdown--;
                document.getElementById('refresh-countdown').textContent = countdown;
                
                if (countdown <= 0) {
                    // Refresh the orders
                    loadOrders();
                    // Reset countdown
                    countdown = KDS_CONFIG.autoRefreshInterval / 1000;
                }
            }, 1000);
            
            // Store interval ID for potential cleanup
            window.kdsRefreshInterval = refreshInterval;
        }

        // Manual refresh
        function manualRefresh() {
            loadOrders();
            // Reset the countdown timer after manual refresh
            if (window.kdsRefreshInterval) {
                clearInterval(window.kdsRefreshInterval);
                startAutoRefresh();
            }
        }

        // Update refresh interval (for future use when settings change dynamically)
        function updateRefreshInterval(newIntervalSeconds) {
            KDS_CONFIG.autoRefreshInterval = newIntervalSeconds * 1000;
            
            // Clear existing interval
            if (window.kdsRefreshInterval) {
                clearInterval(window.kdsRefreshInterval);
            }
            
            // Start new interval with updated setting
            if (KDS_CONFIG.autoRefreshInterval > 0) {
                startAutoRefresh();
            }
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'r') {
                e.preventDefault();
                manualRefresh();
            }
        });

        // Countdown timer functionality
        function updateCountdownTimers() {
            const timers = document.querySelectorAll('.countdown-timer');
            
            timers.forEach(timer => {
                const orderId = timer.getAttribute('data-order-id');
                const createdTime = timer.getAttribute('data-created-time');
                const orderTimeElement = document.getElementById(`order-time-${orderId}`);
                const orderHeaderElement = document.getElementById(`order-header-${orderId}`);
                
                if (createdTime && orderTimeElement && orderHeaderElement) {
                    const now = new Date();
                    const created = new Date(createdTime);
                    const elapsedMs = now - created;
                    
                    // Get station timing from the order data or use default
                    let stationTiming = 22; // Default timing
                    
                    // Try to get station timing from the order card or use default
                    const orderCard = document.querySelector(`[data-order-id="${orderId}"]`);
                    if (orderCard) {
                        const timingSource = orderCard.querySelector('.timing-source');
                        if (timingSource) {
                            const timingMatch = timingSource.textContent.match(/\((\d+)min\)/);
                            if (timingMatch) {
                                stationTiming = parseInt(timingMatch[1]);
                            }
                        }
                    }
                    
                    const targetTime = stationTiming * 60 * 1000; // Convert minutes to milliseconds
                    const remainingMs = targetTime - elapsedMs;
                    const remainingMinutes = Math.floor(remainingMs / 60000);
                    const remainingSeconds = Math.floor((remainingMs % 60000) / 1000);
                    
                    let timeDisplay, timeClass;
                    
                    if (remainingMs > 0) {
                        // Still within time limit - show countdown
                        timeDisplay = `${remainingMinutes}:${remainingSeconds.toString().padStart(2, '0')}`;
                        timeClass = 'normal'; // Always use normal class for countdown
                    } else {
                        // Time is over - show negative time
                        const overdueMs = Math.abs(remainingMs);
                        const overdueMinutes = Math.floor(overdueMs / 60000);
                        const overdueSeconds = Math.floor((overdueMs % 60000) / 1000);
                        
                        timeDisplay = `-${overdueMinutes}:${overdueSeconds.toString().padStart(2, '0')}`;
                        timeClass = 'danger'; // Use danger class only when time is over
                    }
                    
                    // Update timer display
                    timer.textContent = timeDisplay;
                    
                    // Update CSS classes for timer
                    orderTimeElement.className = `order-time ${timeClass}`;
                    
                    // Remove existing timer classes from header
                    orderHeaderElement.classList.remove('timer-normal', 'timer-warning', 'timer-danger', 'timer-critical');
                    
                    // Only add timer class to header when time is over (red)
                    if (timeClass === 'danger') {
                        orderHeaderElement.classList.add('timer-danger');
                    } else {
                        // Keep default header color (remove any timer classes)
                        orderHeaderElement.classList.remove('timer-normal', 'timer-warning', 'timer-danger', 'timer-critical');
                    }
                }
            });
        }

        // Start countdown timer updates
        function startCountdownTimers() {
            // Update timers immediately
            updateCountdownTimers();
            
            // Update timers every second
            setInterval(updateCountdownTimers, 1000);
        }

        // Initialize countdown timers when page loads
        document.addEventListener('DOMContentLoaded', function() {
            startCountdownTimers();
        });

        // Update countdown timers when orders are loaded
        const originalLoadOrders = loadOrders;
        loadOrders = function() {
            originalLoadOrders();
            setTimeout(updateCountdownTimers, 100); // Update timers after orders are loaded
            setTimeout(updateReadyButtonTexts, 150); // Update ready button texts after orders are loaded
        };
        
        // Update ready button texts based on current station
        function updateReadyButtonTexts() {
            const currentStation = KDS_CONFIG.currentStation;
            const readyButtons = document.querySelectorAll('[id^="ready-button-text-"]');
            
            readyButtons.forEach(button => {
                if (currentStation == 0) {
                    button.textContent = 'Ready (All)';
                } else {
                    // Get station name from dropdown
                    const stationSelect = document.getElementById('station-select');
                    const selectedOption = stationSelect.querySelector(`option[value="${currentStation}"]`);
                    const stationName = selectedOption ? selectedOption.textContent : 'Station';
                    button.textContent = `Ready (${stationName})`;
                }
            });
        }
    </script>
</body>
</html>
