<?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">
    
    <style>
                 body {
             background-color: #f5f5f5;
             color: #333333;
             font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
             overflow-x: hidden;
             margin: 0;
             padding: 0;
             height: 100vh;
         }
        
                 .kds-header {
             background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
             padding: 12px 20px;
             box-shadow: 0 2px 10px rgba(0,0,0,0.1);
             margin: 0;
             border: none;
         }
         
         /* Responsive Header Layout */
         .header-container {
             display: flex;
             align-items: center;
             justify-content: space-between;
             flex-wrap: wrap;
             gap: 15px;
             max-width: 100%;
         }
         
         .header-left {
             display: flex;
             align-items: center;
             gap: 20px;
             flex: 1;
             min-width: 0;
         }
         
         .header-center {
             display: flex;
             align-items: center;
             gap: 15px;
             flex-shrink: 0;
         }
         
         .header-right {
             display: flex;
             align-items: center;
             gap: 10px;
             flex-shrink: 0;
         }
         
         .header-logo {
             font-size: 1.25rem;
             font-weight: 600;
             color: white;
             white-space: nowrap;
             flex-shrink: 0;
         }
         
         .header-logo i {
             margin-right: 8px;
         }
         
         .current-time-display {
             background: rgba(255,255,255,0.1);
             padding: 6px 12px;
             border-radius: 6px;
             color: white;
             font-weight: 500;
             white-space: nowrap;
             flex-shrink: 0;
         }
         
         .header-buttons {
             display: flex;
             align-items: center;
             gap: 8px;
             flex-shrink: 0;
         }
         
         .header-buttons .btn {
             padding: 6px 12px;
             font-size: 0.875rem;
             white-space: nowrap;
         }
         
         .refresh-indicator {
             background: rgba(255,255,255,0.9);
             padding: 4px 8px;
             border-radius: 12px;
             font-size: 0.75rem;
             color: #333;
             white-space: nowrap;
             flex-shrink: 0;
         }
         
         /* Responsive Header Breakpoints */
         @media (max-width: 1200px) {
             .header-container {
                 gap: 12px;
             }
             
             .header-left {
                 gap: 15px;
             }
             
             .header-center {
                 gap: 12px;
             }
             
             .header-right {
                 gap: 8px;
             }
             
             .header-logo {
                 font-size: 1.1rem;
             }
             
             .header-buttons .btn {
                 padding: 5px 10px;
                 font-size: 0.8rem;
             }
         }
         
         @media (max-width: 992px) {
             .header-container {
                 flex-direction: column;
                 align-items: stretch;
                 gap: 10px;
             }
             
             .header-left {
                 justify-content: space-between;
                 gap: 10px;
             }
             
             .header-center {
                 justify-content: center;
                 gap: 15px;
             }
             
             .header-right {
                 justify-content: center;
                 gap: 10px;
             }
             
             .station-selector-header {
                 min-width: 200px;
             }
             
             .station-dropdown-header {
                 min-width: 180px;
             }
         }
         
         @media (max-width: 768px) {
             .kds-header {
                 padding: 10px 15px;
             }
             
             .header-left {
                 flex-direction: column;
                 align-items: center;
                 gap: 8px;
             }
             
             .header-center {
                 flex-direction: column;
                 gap: 8px;
             }
             
             .header-right {
                 flex-direction: column;
                 gap: 8px;
             }
             
             .header-buttons {
                 flex-direction: column;
                 width: 100%;
                 gap: 5px;
             }
             
             .header-buttons .btn {
                 width: 100%;
                 padding: 8px 12px;
             }
             
             .refresh-indicator {
                 order: -1;
                 align-self: center;
             }
             
             .station-selector-header {
                 width: 100%;
                 min-width: auto;
             }
             
             .station-dropdown-header {
                 width: 100%;
                 min-width: auto;
             }
         }
         
         @media (max-width: 576px) {
             .kds-header {
                 padding: 8px 10px;
             }
             
             .header-logo {
                 font-size: 1rem;
             }
             
             .current-time-display {
                 font-size: 0.875rem;
                 padding: 4px 8px;
             }
             
             .refresh-indicator {
                 font-size: 0.7rem;
                 padding: 3px 6px;
             }
         }
        
        .station-tab {
            background: rgba(255,255,255,0.1);
            border: none;
            color: #ffffff;
            padding: 15px 25px;
            margin: 0 5px;
            border-radius: 10px 10px 0 0;
            transition: all 0.3s ease;
            font-weight: 600;
            font-size: 16px;
        }
        
        .station-tab.active {
            background: rgba(255,255,255,0.2);
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        
        .order-card {
            background: rgba(255,255,255,0.05);
            border: 2px solid rgba(255,255,255,0.1);
            border-radius: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            position: relative;
        }
        
        .order-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
            border-color: #007bff;
        }
        
        /* Ready button styling */
        .ready-button {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
        }
        
        .ready-button:hover {
            background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(40, 167, 69, 0.4);
        }
        
        .ready-button:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
        }
        
        .ready-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .order-card.new {
            border-left: 5px solid #28a745;
        }
        
        .order-card.preparing {
            border-left: 5px solid #17a2b8;
        }
        
        .order-card.ready {
            border-left: 5px solid #ffc107;
        }
        
        .order-card.served {
            border-left: 5px solid #6c757d;
        }
        
        .order-card.urgent {
            border-left: 5px solid #dc3545;
            animation: pulse 2s infinite;
        }
        
        .order-card.rush {
            border-left: 5px solid #dc3545;
            animation: blink 1s infinite;
        }
        
        .order-card.order-ready {
            background: rgba(40, 167, 69, 0.3) !important;
            border-color: #28a745 !important;
            transform: scale(1.02);
            transition: all 0.3s ease;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(220, 53, 69, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(220, 53, 69, 0); }
            100% { box-shadow: 0 0 0 0 rgba(220, 53, 69, 0); }
        }
        
        @keyframes blink {
            0%, 50% { opacity: 1; }
            51%, 100% { opacity: 0.5; }
        }
        
        .order-header {
            background: rgba(0,0,0,0.3);
            padding: 10px 15px;
            border-radius: 13px 13px 0 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .order-number {
            font-size: 24px;
            font-weight: bold;
            color: #ffffff;
        }
        
        .order-time {
            font-size: 14px;
            font-weight: bold;
            padding: 4px 8px;
            border-radius: 6px;
            text-align: center;
            min-width: 80px;
            transition: all 0.3s ease;
        }
        
        .order-time.normal {
            background: #e8f5e8;
            color: #388e3c;
        }
        
        .order-time.warning {
            background: #fff3e0;
            color: #f57c00;
            animation: pulse 1s infinite;
        }
        
        .order-time.danger {
            background: #ffebee;
            color: #d32f2f;
            animation: pulse 0.5s infinite;
        }
        
        .order-time.critical {
            background: #d32f2f;
            color: white;
            animation: pulse 0.3s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        .order-body {
            padding: 15px;
        }
        
        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .item-row:last-child {
            border-bottom: none;
        }
        
        .item-quantity {
            background: #007bff;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-weight: bold;
            font-size: 12px;
        }
        
        .item-name {
            font-size: 16px;
            font-weight: 500;
        }
        
        .item-status {
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .item-status.pending {
            background: #6c757d;
            color: white;
        }
        
        .item-status.preparing {
            background: #17a2b8;
            color: white;
        }
        
        .item-status.ready {
            background: #28a745;
            color: white;
        }
        
        .item-status.served {
            background: #6c757d;
            color: white;
        }
        
        .order-actions {
            padding: 10px 15px;
            background: rgba(0,0,0,0.2);
            border-radius: 0 0 13px 13px;
        }
        
        .btn-kds {
            border: none;
            border-radius: 8px;
            padding: 8px 16px;
            margin: 0 5px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-kds:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        
        .btn-start {
            background: #17a2b8;
            color: white;
        }
        
        .btn-ready {
            background: #28a745;
            color: white;
        }
        
        .btn-complete {
            background: #6c757d;
            color: white;
        }
        
        .btn-urgent {
            background: #dc3545;
            color: white;
        }
        
        .priority-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .priority-indicator.normal { background: #28a745; }
        .priority-indicator.urgent { background: #ffc107; }
        .priority-indicator.rush { 
            background: #dc3545; 
            animation: blink 1s infinite;
        }
        
        .order-timer {
            background: rgba(0,0,0,0.3);
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: bold;
            margin-left: 10px;
        }
        
        .timer-warning { color: #ffc107; }
        .timer-danger { color: #dc3545; }
        
        .no-orders {
            text-align: center;
            padding: 100px 20px;
            color: #666666;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e0e0e0;
        }
        
        .no-orders i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
            color: #999999;
        }
        
        .connection-status {
            position: fixed;
            top: 60px;
            right: 20px;
            background: #ffffff;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 11px;
            z-index: 1000;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e0e0e0;
            color: #333;
        }
        
        
        

        
        .table-info {
            background: rgba(255,255,255,0.1);
            padding: 8px 12px;
            border-radius: 15px;
            font-size: 12px;
            margin-left: 10px;
        }
        
        .order-type-badge {
            background: rgba(255,255,255,0.2);
            padding: 4px 8px;
            border-radius: 10px;
            font-size: 10px;
            text-transform: uppercase;
            margin-left: 10px;
        }
        
                 /* Professional Multi-Column Layout with Order Splitting - NO SCROLLING */
         .orders-grid {
             display: flex;
             flex-direction: row;
             flex-wrap: wrap;
             gap: 15px;
             padding: 15px;
             max-width: 100%;
             height: calc(100vh - 140px);
             overflow: hidden;
             align-content: flex-start;
         }
         
                   .orders-column {
              display: flex;
              flex-direction: column;
              gap: 10px;
              min-width: 360px;
              max-width: 360px;
              flex: 1;
              height: calc(100vh - 170px);
              overflow: hidden;
          }
        
                 /* Responsive multi-column layout - NO SCROLLING */
         @media (min-width: 1200px) {
             .orders-grid {
                 max-width: 95%;
                 margin: 0 auto;
             }
             .orders-column {
                 min-width: 360px;
                 max-width: 360px;
             }
         }
         
         @media (min-width: 992px) and (max-width: 1199px) {
             .orders-grid {
                 max-width: 100%;
                 margin: 0 auto;
             }
             .orders-column {
                 min-width: 340px;
                 max-width: 340px;
             }
         }
         
         @media (min-width: 768px) and (max-width: 991px) {
             .orders-grid {
                 max-width: 100%;
                 margin: 0 auto;
             }
             .orders-column {
                 min-width: 300px;
                 max-width: 300px;
             }
         }
        
                 @media (max-width: 767px) {
             .orders-grid {
                 flex-direction: column;
                 flex-wrap: nowrap;
                 height: calc(100vh - 140px);
                 gap: 10px;
                 padding: 10px;
                 overflow: hidden;
             }
             
             .orders-column {
                 min-width: 100%;
                 max-width: 100%;
                 height: auto;
             }
            
            .order-card {
                width: 100%;
                max-width: 100%;
            }
            
            .item-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }
            
            .item-row .d-flex {
                width: 100%;
                justify-content: flex-start;
            }
            
            .item-name {
                max-width: 100%;
                white-space: normal;
            }
            
            .ready-button {
                padding: 10px 16px;
                font-size: 14px;
            }
            
            .order-actions-container {
                padding: 12px;
            }
        }
        
        @media (max-width: 576px) {
            .ready-button {
                padding: 8px 12px;
                font-size: 13px;
            }
            
            .order-actions-container {
                padding: 10px;
            }
        }
        
                 /* Professional Order Card Styling - COMPACT FOR NO SCROLLING */
         .order-card {
             background: #ffffff;
             border: 2px solid #e0e0e0;
             border-radius: 10px;
             margin-bottom: 0;
             transition: all 0.3s ease;
             backdrop-filter: none;
             position: relative;
             box-shadow: 0 3px 5px rgba(0, 0, 0, 0.1);
             min-height: auto;
             width: 100%;
             max-width: 360px;
             margin: 0 auto 10px 0;
             display: flex;
             flex-direction: column;
             cursor: default;
             break-inside: avoid;
             page-break-inside: avoid;
         }
         
         /* Visual indicators for multi-line orders */
         .order-card::before {
             content: '';
             position: absolute;
             left: -2px;
             top: 0;
             bottom: 0;
             width: 4px;
             background: linear-gradient(180deg, #007bff 0%, #0056b3 100%);
             border-radius: 2px;
             z-index: 1;
         }
         
         .order-card.urgent::before {
             background: linear-gradient(180deg, #dc3545 0%, #c82333 100%);
         }
         
         .order-card.rush::before {
             background: linear-gradient(180deg, #ffc107 0%, #e0a800 100%);
             animation: pulse-border 1s infinite;
         }
         
         .order-card.new::before {
             background: linear-gradient(180deg, #28a745 0%, #1e7e34 100%);
         }
         
         .order-card.preparing::before {
             background: linear-gradient(180deg, #17a2b8 0%, #138496 100%);
         }
         
         .order-card.ready::before {
             background: linear-gradient(180deg, #ffc107 0%, #e0a800 100%);
         }
         
         /* Continuation indicator for orders that might span */
         .order-card::after {
             content: '↴';
             position: absolute;
             bottom: 5px;
             right: 10px;
             font-size: 16px;
             color: #6c757d;
             opacity: 0.6;
             z-index: 2;
             transition: all 0.3s ease;
         }
         
         .order-card:hover::after {
             opacity: 1;
             color: #007bff;
             transform: translateY(2px);
         }
         
         @keyframes pulse-border {
             0% { opacity: 1; }
             50% { opacity: 0.7; }
             100% { opacity: 1; }
         }
        
        .order-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
            border-color: #007bff;
        }
        
        .order-card.new {
            border-left: 5px solid #28a745;
        }
        
        .order-card.preparing {
            border-left: 5px solid #17a2b8;
        }
        
        .order-card.ready {
            border-left: 5px solid #ffc107;
        }
        
        .order-card.served {
            border-left: 5px solid #6c757d;
        }
        
        .order-card.urgent {
            border-left: 5px solid #dc3545;
            animation: pulse 2s infinite;
        }
        
        .order-card.rush {
            border-left: 5px solid #dc3545;
            animation: blink 1s infinite;
        }
        
                 .order-card.order-ready {
             background: rgba(40, 167, 69, 0.1) !important;
             border-color: #28a745 !important;
             transform: scale(1.02);
             transition: all 0.3s ease;
         }
         
                   /* Professional curved continuation indicators for split orders */
          .order-continuation {
              position: relative;
              margin: 8px 0;
              height: 20px;
              display: flex;
              align-items: center;
              justify-content: center;
          }
          
          .order-continuation.continued {
              background: none;
              border: none;
              box-shadow: none;
          }
          
          .order-continuation.continued::before {
              content: "";
              position: absolute;
              bottom: -10px;
              right: 15px;
              width: 30px;
              height: 30px;
              border: 3px solid #28a745;
              border-top: none;
              border-left: none;
              border-radius: 0 0 30px 0;
              transform: rotate(45deg);
          }
          
          .order-continuation.continued::after {
              content: "";
              position: absolute;
              bottom: -5px;
              right: 25px;
              width: 8px;
              height: 8px;
              background: #28a745;
              border-radius: 50%;
          }
          
          .order-continuation.continuing {
              background: none;
              border: none;
              box-shadow: none;
          }
          
          .order-continuation.continuing::before {
              content: "";
              position: absolute;
              top: -10px;
              left: 15px;
              width: 30px;
              height: 30px;
              border: 3px solid #ffc107;
              border-bottom: none;
              border-right: none;
              border-radius: 30px 0 0 30px;
              transform: rotate(45deg);
          }
          
          .order-continuation.continuing::after {
              content: "";
              position: absolute;
              top: -5px;
              left: 25px;
              width: 8px;
              height: 8px;
              background: #ffc107;
              border-radius: 50%;
          }
         
         /* Split order styling */
         .order-card.split-order {
             border-left: 4px solid #007bff;
         }
         
         .order-card.split-order.continued {
             border-left: 4px solid #28a745;
         }
         
         .order-card.split-order.continuing {
             border-left: 4px solid #ffc107;
         }
        
                 /* Professional Header Styling - COMPACT */
         .order-header {
             background: #f8f9fa;
             padding: 8px 12px;
             border-radius: 8px 8px 0 0;
             border-bottom: 1px solid #dee2e6;
             color: #333;
             transition: all 0.3s ease;
         }
        
        /* Timer-based header colors - Professional three-color system */
        .order-header.timer-normal {
            background: #28a745; /* Professional green for new orders */
            color: #ffffff; /* White text for prominence */
            border-bottom-color: #1e7e34;
        }
        
        .order-header.timer-warning {
            background: #ffc107; /* Professional yellow for last minutes */
            color: #212529; /* Dark text for prominence */
            border-bottom-color: #e0a800;
        }
        
        .order-header.timer-danger {
            background: #dc3545; /* Professional red for time over */
            color: #ffffff; /* White text for prominence */
            border-bottom-color: #c82333;
        }
        
        .order-header.timer-critical {
            background: #dc3545; /* Professional red for time over */
            color: #ffffff; /* White text for prominence */
            border-bottom-color: #c82333;
        }
        
        .order-number {
            font-size: 16px;
            font-weight: 600;
            color: #666;
            margin-top: 5px;
        }
        
                 .table-floor-info {
             font-size: 18px;
             font-weight: bold;
             color: inherit;
             margin-bottom: 3px;
         }
        
        .table-floor-info .table-name {
            color: inherit; /* Inherits from parent timer color for prominence */
            font-weight: 800;
        }
        
        .table-floor-info .floor-name {
            color: inherit; /* Inherits from parent timer color for prominence */
            font-weight: 600;
        }
        
        .order-time {
            font-size: 12px;
            font-weight: bold;
            padding: 3px 6px;
            border-radius: 4px;
            text-align: center;
            min-width: 60px;
            transition: all 0.3s ease;
            margin-top: 5px;
        }
        
        .order-time.normal {
            background: #28a745; /* Professional green for new orders */
            color: #ffffff; /* White text for prominence */
        }
        
        .order-time.warning {
            background: #ffc107; /* Professional yellow for last minutes */
            color: #212529; /* Dark text for prominence */
        }
        
        .order-time.danger {
            background: #dc3545; /* Professional red for time over */
            color: #ffffff; /* White text for prominence */
        }
        
        .order-time.critical {
            background: #dc3545; /* Professional red for time over */
            color: #ffffff; /* White text for prominence */
        }
        
                 /* Professional Body Styling - COMPACT */
         .order-body {
             padding: 8px 12px;
             flex-grow: 1;
             color: #333;
         }
        
                 .item-row {
             display: flex;
             justify-content: space-between;
             align-items: center;
             padding: 5px 0;
             border-bottom: 1px solid #f0f0f0;
             flex-wrap: nowrap;
             gap: 8px;
         }
        
        .item-row:last-child {
            border-bottom: none;
        }
        
        .item-row .d-flex {
            flex: 1;
            min-width: 0;
            flex-wrap: nowrap;
        }
        
                 .item-quantity {
             background: #007bff;
             color: white;
             padding: 1px 4px;
             border-radius: 6px;
             font-weight: bold;
             font-size: 14px;
             flex-shrink: 0;
         }
        
                 .item-name {
             font-size: 16px;
             font-weight: 500;
             color: #333;
             white-space: nowrap;
             overflow: hidden;
             text-overflow: ellipsis;
             max-width: 200px;
             flex: 1;
         }
        
        .item-status {
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .item-status.pending {
            background: #6c757d;
            color: white;
        }
        
        .item-status.preparing {
            background: #17a2b8;
            color: white;
        }
        
        .item-status.ready {
            background: #28a745;
            color: white;
        }
        
        .item-status.served {
            background: #6c757d;
            color: white;
        }
        
        /* Professional Info Styling */
        .table-info {
            background: #e9ecef;
            padding: 3px 6px;
            border-radius: 6px;
            font-size: 10px;
            margin-left: 8px;
            color: #495057;
        }
        
        .order-type-badge {
            background: #007bff;
            padding: 3px 6px;
            border-radius: 8px;
            font-size: 9px;
            text-transform: uppercase;
            margin-left: 8px;
            color: white;
        }
        
        .order-type-badge.dine-in {
            background: #28a745;
        }
        
        .order-type-badge.take_away {
            background: #17a2b8;
        }
        
        .order-type-badge.delivery {
            background: #6f42c1;
        }
        
        /* Professional Priority Indicators */
        .priority-indicator {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 6px;
        }
        
        .priority-indicator.normal { background: #28a745; }
        .priority-indicator.urgent { background: #ffc107; }
        .priority-indicator.rush { 
            background: #dc3545; 
            animation: blink 1s infinite;
        }
        
        /* Professional Customer Info */
        .customer-name {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .priority-info {
            font-size: 10px;
            color: #666;
            margin-top: 2px;
        }
        
                 /* Professional Ready Button Container - COMPACT */
         .order-actions-container {
             padding: 10px 12px;
             background: #f8f9fa;
             border-radius: 0 0 8px 8px;
             border-top: 1px solid #dee2e6;
         }
        
        /* Professional Running Order Badge */
        .running-order-badge {
            position: absolute;
            top: -8px;
            left: 50%;
            transform: translateX(-50%);
            background: linear-gradient(45deg, #dc3545, #ff6b6b);
            color: white;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 10px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            box-shadow: 0 2px 4px rgba(220, 53, 69, 0.3);
            z-index: 10;
            animation: pulse-running 2s infinite;
        }
        
        .running-order-item-label {
            background: linear-gradient(135deg, #ffc107 0%, #ff8c00 100%);
            color: #000;
            padding: 1px 6px;
            border-radius: 8px;
            font-size: 9px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.3px;
            margin-left: 6px;
            box-shadow: 0 1px 2px rgba(255, 193, 7, 0.3);
            animation: pulse-running 2s infinite;
            white-space: nowrap;
            flex-shrink: 0;
        }
        
                 /* Professional Station Selector */
         .station-selector {
             background: #ffffff;
             border-radius: 12px;
             padding: 15px;
             margin-bottom: 20px;
             box-shadow: 0 2px 8px rgba(0,0,0,0.1);
             border: 1px solid #e0e0e0;
         }
         
         .station-selector label {
             color: #333 !important;
             font-weight: 600;
         }
         
         .station-dropdown {
             background: #ffffff;
             border: 2px solid #e0e0e0;
             border-radius: 8px;
             color: #333;
             font-weight: 500;
             padding: 8px 12px;
             transition: all 0.3s ease;
         }
         
         .station-dropdown:focus {
             background: white;
             border-color: #007bff;
             box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
             outline: none;
         }
         
         /* Header Station Selector */
         .station-selector-header {
             display: inline-block;
         }
         
         .station-selector-header label {
             color: #ffffff !important;
             font-weight: 600;
             font-size: 14px;
             margin-bottom: 0;
         }
         
         .station-dropdown-header {
             background: rgba(255,255,255,0.9);
             border: 1px solid rgba(255,255,255,0.3);
             border-radius: 6px;
             color: #333;
             font-weight: 500;
             padding: 4px 8px;
             font-size: 13px;
             min-width: 150px;
             transition: all 0.3s ease;
         }
         
         .station-dropdown-header:focus {
             background: white;
             border-color: rgba(255,255,255,0.8);
             box-shadow: 0 0 0 2px rgba(255,255,255,0.2);
             outline: none;
         }
         
         .station-dropdown-header:hover {
             background: white;
             border-color: rgba(255,255,255,0.5);
         }
        
        #refresh-orders {
            background: #007bff;
            border: 2px solid #007bff;
            border-radius: 8px;
            color: white;
            padding: 8px 12px;
            transition: all 0.3s ease;
        }
        
        #refresh-orders:hover {
            background: #0056b3;
            border-color: #0056b3;
            transform: translateY(-1px);
        }
        
                 #refresh-orders:disabled {
             opacity: 0.6;
             cursor: not-allowed;
             transform: none;
         }
         
                   /* NO SCROLLING - Removed scrollbar styles */
    </style>
</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
        };

        // Initialize KDS
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Feather icons
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
            
            // Load initial orders
            loadOrders();
            
            // Set up auto refresh
            if (KDS_CONFIG.autoRefreshInterval > 0) {
                setInterval(loadOrders, KDS_CONFIG.autoRefreshInterval);
                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 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() {
                    loadOrders(); // 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 with column splitting
        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 orders
            const columns = createOrderColumns(orders);
            
            let html = '';
            columns.forEach((column, columnIndex) => {
                html += '<div class="orders-column">';
                column.forEach((orderData, orderIndex) => {
                    html += createOrderCard(orderData.order, orderData.isSplit, orderData.splitType, orderData.splitIndex);
                });
                html += '</div>';
            });
            
            container.innerHTML = html;
        }
        
                 // Create columns and split orders if needed - NO SCROLLING
         function createOrderColumns(orders) {
             const columns = [];
             const maxColumnHeight = window.innerHeight - 220; // Force multi-column layout
             let currentColumn = [];
             let currentHeight = 0;
            
            orders.forEach(order => {
                // Estimate order height (approximate)
                const estimatedHeight = estimateOrderHeight(order);
                
                // Check if order fits in current column
                if (currentHeight + estimatedHeight <= maxColumnHeight) {
                    // Order fits in current column
                    currentColumn.push({
                        order: order,
                        isSplit: false,
                        splitType: null,
                        splitIndex: null
                    });
                    currentHeight += estimatedHeight;
                } else {
                    // Order doesn't fit - check if we can split it
                    const splitResult = splitOrder(order, maxColumnHeight - currentHeight);
                    
                    if (splitResult.canSplit) {
                        // Add first part to current column
                        currentColumn.push({
                            order: splitResult.firstPart,
                            isSplit: true,
                            splitType: 'continued',
                            splitIndex: 0
                        });
                        
                        // Start new column with second part
                        columns.push(currentColumn);
                        currentColumn = [{
                            order: splitResult.secondPart,
                            isSplit: true,
                            splitType: 'continuing',
                            splitIndex: 1
                        }];
                        currentHeight = estimateOrderHeight(splitResult.secondPart);
                    } else {
                        // Can't split, start new column
                        columns.push(currentColumn);
                        currentColumn = [{
                            order: order,
                            isSplit: false,
                            splitType: null,
                            splitIndex: null
                        }];
                        currentHeight = estimatedHeight;
                    }
                }
            });
            
            // Add the last column
            if (currentColumn.length > 0) {
                columns.push(currentColumn);
            }
            
            return columns;
        }
        
                 // Estimate order height based on number of items - COMPACT FOR NO SCROLLING
         function estimateOrderHeight(order) {
             const baseHeight = 180; // More accurate base height
             const itemHeight = 40; // More accurate per item height
             const itemsCount = order.items ? order.items.length : 0;
             return baseHeight + (itemsCount * itemHeight);
         }
        
                 // Split order into two parts - COMPACT FOR NO SCROLLING
         function splitOrder(order, availableHeight) {
             const minHeight = 120; // Reduced minimum height for a split part
             const estimatedHeight = estimateOrderHeight(order);
            
            if (estimatedHeight < minHeight * 2) {
                return { canSplit: false };
            }
            
            // Split items roughly in half
            const items = order.items || [];
            const splitIndex = Math.ceil(items.length / 2);
            
            const firstPart = {
                ...order,
                items: items.slice(0, splitIndex)
            };
            
            const secondPart = {
                ...order,
                items: items.slice(splitIndex)
            };
            
            return {
                canSplit: true,
                firstPart: firstPart,
                secondPart: secondPart
            };
        }

        // Create order card HTML
        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 is a running order to show the label
                const isRunningOrder = order.is_running_order || (order.notes && order.notes.includes('RUNNING ORDER'));
                const runningOrderLabel = isRunningOrder ? '<span class="running-order-item-label">Running Order</span>' : '';
                
                // Parse special_instructions to separate modifiers and remarks
                const specialInstructions = item.special_instructions || '';
                const parts = specialInstructions.split(' | REMARKS: ');

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

                if (parts.length > 1) {
                    // Has both modifiers and remarks
                    const modifiers = parts[0];
                    const remarks = parts[1];
                    
                    modifierDisplay = modifiers ? 
                        `<div class="item-modifiers text-primary small mt-1">
                            <i class="fas fa-tags me-1"></i>${modifiers}
                        </div>` : '';
                    
                    remarksDisplay = remarks ? 
                        `<div class="item-remarks text-warning small mt-1">
                            <i class="fas fa-comment me-1"></i>${remarks}
                        </div>` : '';
                } else if (specialInstructions) {
                    // Only modifiers (existing behavior)
                    modifierDisplay = `<div class="item-modifiers text-primary small mt-1">
                        <i class="fas fa-tags me-1"></i>${specialInstructions}
                    </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">${item.quantity}x</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>
                                ${modifierDisplay}
                                ${remarksDisplay}
                            </div>
                        </div>
                        <div class="d-flex align-items-center flex-shrink-0 ms-2">
                            ${item.station_name ? `<span class="badge me-2" style="background-color: ${item.station_color || '#6c757d'}; color: white; font-size: 9px;">${item.station_name}</span>` : ''}
                            ${(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 tag
            let runningOrderBadge = '';
            if (order.is_running_order || (order.notes && order.notes.includes('RUNNING ORDER'))) {
                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 split order classes
            const splitClasses = isSplit ? `split-order ${splitType}` : '';
            
            // Add cancelled class if order is cancelled
            const cancelledClass = (order.order_status === 'cancelled' || (order.notes && order.notes.includes('CANCELLED'))) ? 'cancelled' : '';
            
                         // Create continuation indicator if needed
             let continuationIndicator = '';
             if (isSplit) {
                 if (splitType === 'continued') {
                     continuationIndicator = `
                         <div class="order-continuation continued"></div>
                     `;
                 } else if (splitType === 'continuing') {
                     continuationIndicator = `
                         <div class="order-continuation continuing"></div>
                     `;
                 }
             }
            
                         // For continuing orders, show minimal header with just order number
             if (splitType === 'continuing') {
                 return `
                     ${continuationIndicator}
                     <div class="order-card ${order.calculated_status} ${order.priority === 'urgent' || order.priority === 'rush' ? 'urgent' : ''} ${order.is_running_order || (order.notes && order.notes.includes('RUNNING ORDER')) ? 'running-order' : ''} ${cancelledClass} ${splitClasses}" data-order-id="${order.id}">
                         ${cancelledOrderBadge}
                         <div class="order-header" id="order-header-${order.id}">
                             <div class="d-flex justify-content-between align-items-center">
                                 <div>
                                     <div class="order-number">Order #${order.order_number}</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>
                                Ready
                             </button>
                         </div>
                     </div>
                 `;
             }
             
             // For regular orders and continued orders, show full header
             return `
                 ${splitType === 'continuing' ? continuationIndicator : ''}
                 <div class="order-card ${order.calculated_status} ${order.priority === 'urgent' || order.priority === 'rush' ? 'urgent' : ''} ${order.is_running_order || (order.notes && order.notes.includes('RUNNING ORDER')) ? 'running-order' : ''} ${cancelledClass} ${splitClasses}" 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>
                                 </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>
                            Ready
                         </button>
                     </div>
                 </div>
                 ${splitType === 'continued' ? continuationIndicator : ''}
             `;
        }

                 // Mark order as served when clicked
         function markOrderServed(orderId) {
             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');
            });
        }

        // 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;
            
            setInterval(() => {
                countdown--;
                document.getElementById('refresh-countdown').textContent = countdown;
                
                if (countdown <= 0) {
                    loadOrders();
                    countdown = KDS_CONFIG.autoRefreshInterval / 1000;
                }
            }, 1000);
        }

        // Manual refresh
        function manualRefresh() {
            loadOrders();
        }

        // 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;
                    const elapsedMinutes = Math.floor(elapsedMs / 60000);
                    const elapsedSeconds = Math.floor((elapsedMs % 60000) / 1000);
                    
                    // Calculate time display (reverse countdown from 5 minutes)
                    const targetTime = 5 * 60 * 1000; // 5 minutes in 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 5 minutes
                        timeDisplay = `${remainingMinutes}:${remainingSeconds.toString().padStart(2, '0')}`;
                        
                        if (remainingMs > targetTime * 0.6) { // More than 3 minutes left - Green for new orders
                            timeClass = 'normal';
                        } else if (remainingMs > targetTime * 0.2) { // More than 1 minute left - Yellow for last minutes
                            timeClass = 'warning';
                        } else { // Less than 1 minute left - Red for time over
                            timeClass = 'danger';
                        }
                    } else {
                        // Beyond 5 minutes - 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')}`;
                        
                        if (overdueMs < 2 * 60 * 1000) { // Less than 2 minutes overdue - Red for time over
                            timeClass = 'danger';
                        } else { // More than 2 minutes overdue - Red for time over
                            timeClass = 'critical';
                        }
                    }
                    
                    // Update timer display
                    timer.textContent = timeDisplay;
                    
                    // Update CSS classes for both timer and header
                    orderTimeElement.className = `order-time ${timeClass}`;
                    
                    // Remove existing timer classes from header
                    orderHeaderElement.classList.remove('timer-normal', 'timer-warning', 'timer-danger', 'timer-critical');
                    
                    // Add new timer class to header
                    orderHeaderElement.classList.add(`timer-${timeClass}`);
                }
            });
        }

        // 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
        };
    </script>
</body>
</html>
