<?php
// Kitchen Staff Authentication Check
session_start();

// Verify kitchen staff is logged in
if (!isset($_SESSION['kitchen_staff_id'])) {
    header('Location: login.php');
    exit;
}

$chef_id = $_SESSION['kitchen_staff_id'];
$chef_name = $_SESSION['kitchen_staff_name'];
$chef_role = $_SESSION['kitchen_staff_role'];
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">

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

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

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

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

    <title>Kitchen Dashboard - Granny Restaurant</title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .kitchen-container {
            display: flex;
            min-height: 100vh;
        }
        
        .sidebar {
            width: 250px;
            background: linear-gradient(135deg, #d4a574 0%, #b8935f 100%);
            color: white;
            padding: 20px;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 30px;
            font-size: 18px;
            font-weight: bold;
        }
        
        .logo i {
            font-size: 24px;
        }
        
        .sidebar-nav {
            list-style: none;
        }
        
        .sidebar-nav li {
            margin-bottom: 15px;
        }
        
        .sidebar-nav a {
            color: white;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            border-radius: 5px;
            transition: all 0.3s ease;
        }
        
        .sidebar-nav a:hover,
        .sidebar-nav a.active {
            background: rgba(255, 255, 255, 0.2);
        }
        
        .sidebar-section {
            margin-top: 30px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
            padding-top: 15px;
        }
        
        .sidebar-section-title {
            font-size: 12px;
            text-transform: uppercase;
            opacity: 0.8;
            margin-bottom: 10px;
        }
        
        .logout-btn {
            width: 100%;
            padding: 10px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
        }
        
        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .main-content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }
        
        .header h1 {
            font-size: 24px;
            color: #333;
        }
        
        .header-stats {
            display: flex;
            gap: 20px;
            align-items: center;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #d4a574;
        }
        
        .stat-label {
            font-size: 12px;
            color: #999;
            text-transform: uppercase;
        }
        
        .orders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .order-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border-left: 4px solid #d4a574;
            transition: all 0.3s ease;
        }
        
        .order-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }
        
        .order-number {
            font-size: 16px;
            font-weight: bold;
            color: #333;
        }
        
        .order-status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .badge-confirmed {
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .badge-preparing {
            background: #fff3e0;
            color: #f57c00;
        }
        
        .badge-ready {
            background: #e8f5e9;
            color: #388e3c;
        }
        
        .order-info {
            margin-bottom: 15px;
            font-size: 13px;
            color: #666;
        }
        
        .order-info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
        }
        
        .items-list {
            background: #f9f9f9;
            border-radius: 5px;
            padding: 12px;
            margin-bottom: 15px;
            max-height: 150px;
            overflow-y: auto;
        }
        
        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 0;
            border-bottom: 1px solid #eee;
            font-size: 12px;
        }
        
        .item-row:last-child {
            border-bottom: none;
        }
        
        .item-name {
            flex: 1;
        }
        
        .item-qty {
            background: #d4a574;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            margin-right: 8px;
        }
        
        .item-status {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .item-status-pending {
            background: #f0f0f0;
            color: #999;
        }
        
        .item-status-preparing {
            background: #fff3e0;
            color: #f57c00;
        }
        
        .item-status-ready {
            background: #e8f5e9;
            color: #388e3c;
        }
        
        .order-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        
        .btn-view {
            background: #d4a574;
            color: white;
        }
        
        .btn-view:hover {
            background: #b8935f;
        }
        
        .btn-ready {
            background: #4caf50;
            color: white;
        }
        
        .btn-ready:hover {
            background: #45a049;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .empty-state p {
            font-size: 18px;
        }
        
        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-30px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-header h2 {
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
        }
        
        .close-btn:hover {
            color: #333;
        }
        
        .detail-section {
            margin-bottom: 20px;
        }
        
        .detail-section h3 {
            font-size: 14px;
            color: #333;
            margin-bottom: 10px;
            text-transform: uppercase;
            font-weight: bold;
            border-bottom: 2px solid #d4a574;
            padding-bottom: 8px;
        }
        
        .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        
        .detail-item:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #666;
            font-weight: bold;
        }
        
        .detail-value {
            color: #333;
        }
        
        .items-detail-list {
            background: #f9f9f9;
            border-radius: 5px;
            padding: 12px;
        }
        
        .item-detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            background: white;
            border-radius: 4px;
            margin-bottom: 8px;
            border-left: 3px solid #d4a574;
        }
        
        .item-detail-name {
            flex: 1;
        }
        
        .item-detail-qty {
            min-width: 50px;
            text-align: center;
        }
        
        .item-detail-status-dropdown {
            padding: 6px 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .modal-footer {
            display: flex;
            gap: 10px;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .btn-primary {
            background: #4caf50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            flex: 1;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background: #45a049;
        }
        
        .btn-secondary {
            background: #999;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            flex: 1;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        
        .btn-secondary:hover {
            background: #777;
        }

        /* Hamburger Button */
        .hamburger-btn {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            color: #333;
            cursor: pointer;
            padding: 8px 12px;
            transition: all 0.3s ease;
        }

        .hamburger-btn:hover {
            color: #d4a574;
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 800;
        }

        .sidebar-overlay.show {
            display: block;
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .hamburger-btn {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .kitchen-container {
                position: relative;
            }

            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                height: 100vh;
                width: 50%;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 900;
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .main-content {
                width: 100%;
            }

            .header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
                justify-content: flex-start;
                padding: 15px;
            }

            .header > div:first-child {
                width: 100%;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .header h1 {
                font-size: 18px;
                margin: 0;
            }

            .header-stats {
                width: 100%;
                gap: 15px;
                font-size: 12px;
                justify-content: space-around;
                padding: 10px 0;
                border-top: 1px solid #eee;
            }

            .stat-item {
                flex: 1;
                padding: 0 5px;
            }

            .stat-number {
                font-size: 18px;
            }

            .stat-label {
                font-size: 10px;
            }

            .main-content {
                padding: 15px;
            }

            .orders-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .order-card {
                padding: 15px;
            }
        }

        @media (max-width: 480px) {
            .sidebar {
                width: 70%;
            }

            .header {
                flex-direction: column;
                gap: 12px;
                padding: 10px;
            }

            .header > div:first-child {
                width: 100%;
                display: flex;
                align-items: center;
                gap: 8px;
            }

            .header h1 {
                font-size: 16px;
                margin: 0;
            }

            .header-stats {
                width: 100%;
                gap: 10px;
                justify-content: space-around;
                padding: 8px 0;
                border-top: 1px solid #eee;
            }

            .stat-item {
                flex: 1;
                padding: 0 3px;
            }

            .stat-number {
                font-size: 16px;
            }

            .stat-label {
                font-size: 9px;
            }

            .main-content {
                padding: 10px;
            }

            .order-card {
                padding: 10px;
            }

            .btn {
                font-size: 11px;
                padding: 8px;
            }
        }
    </style>
</head>

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

    <div class="kitchen-container">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <i class="fas fa-utensils"></i>
                <span>Granny Kitchen</span>
            </div>

            <ul class="sidebar-nav">
                <li><a href="dashboard.php" class="active"><i class="fas fa-fire"></i> Orders</a></li>
            </ul>

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

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <div class="header">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <button class="hamburger-btn" onclick="toggleSidebar()">
                        <i class="fas fa-bars"></i>
                    </button>
                    <h1><i class="fas fa-fire"></i> Kitchen Orders</h1>
                </div>
                <div class="header-stats">
                    <div class="stat-item">
                        <div class="stat-number" id="confirmedCount">0</div>
                        <div class="stat-label">New Orders</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="preparingCount">0</div>
                        <div class="stat-label">Preparing</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="readyCount">0</div>
                        <div class="stat-label">Ready</div>
                    </div>
                </div>
            </div>

            <!-- Orders Grid -->
            <div id="ordersGrid" class="orders-grid">
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>Loading orders...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Order Details Modal -->
    <div id="orderDetailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Order Details</h2>
                <button class="close-btn" onclick="closeOrderModal()">&times;</button>
            </div>

            <div class="detail-section">
                <h3>Order Information</h3>
                <div class="detail-item">
                    <span class="detail-label">Order Number:</span>
                    <span class="detail-value" id="modalOrderNumber">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Table:</span>
                    <span class="detail-value" id="modalTableInfo">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Server:</span>
                    <span class="detail-value" id="modalServerName">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Status:</span>
                    <span class="detail-value" id="modalOrderStatus">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Order Time:</span>
                    <span class="detail-value" id="modalOrderTime">-</span>
                </div>
            </div>

            <div class="detail-section">
                <h3>Items</h3>
                <div id="modalItemsList" class="items-detail-list">
                    <!-- Items will be rendered here -->
                </div>
            </div>

            <div class="detail-section" id="specialRequestsSection" style="display: none;">
                <h3>Special Requests</h3>
                <div class="detail-item">
                    <span class="detail-value" id="modalSpecialRequests">-</span>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn-primary" id="markReadyBtn" onclick="markOrderReady()" style="display: none;">
                    <i class="fas fa-check"></i> Mark Entire Order Ready
                </button>
                <button class="btn-secondary" onclick="closeOrderModal()">Close</button>
            </div>
        </div>
    </div>

    <!-- Recipe Viewer Modal -->
    <div id="recipeModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="modal-header">
                <h2><i class="fas fa-book"></i> Recipe Details</h2>
                <button class="close-btn" onclick="closeRecipeModal()">&times;</button>
            </div>

            <div class="detail-section">
                <h3>Dish Information</h3>
                <div class="detail-item">
                    <span class="detail-label">Dish Name:</span>
                    <span class="detail-value" id="recipeItemName">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Preparation Time:</span>
                    <span class="detail-value" id="recipeTime">-</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Difficulty:</span>
                    <span class="detail-value"><span id="recipeDifficulty" style="display: inline-block; padding: 3px 8px; border-radius: 3px; color: white; font-weight: bold; font-size: 11px;">-</span></span>
                </div>
            </div>

            <div class="detail-section">
                <h3>Ingredients Required</h3>
                <div id="recipeIngredientsList" class="items-detail-list">
                    <!-- Ingredients will load here -->
                </div>
            </div>

            <div class="detail-section" id="recipeNotesSection" style="display: none;">
                <h3>Chef Notes</h3>
                <div style="background: #fff9e6; padding: 10px; border-left: 3px solid #ff9800; border-radius: 3px;">
                    <p id="recipeNotes" style="margin: 0; color: #333;"></p>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeRecipeModal()">Close</button>
            </div>
        </div>
    </div>

    <!-- Ingredient Availability Modal -->
    <div id="ingredientModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="modal-header">
                <h2><i class="fas fa-boxes"></i> Ingredient Availability</h2>
                <button class="close-btn" onclick="closeIngredientModal()">&times;</button>
            </div>

            <div class="detail-section">
                <h3>Item: <span id="ingredientItemName">-</span></h3>
            </div>

            <div class="detail-section">
                <h3>Stock Status</h3>
                <div id="ingredientStatusList" style="background: #f9f9f9; padding: 10px; border-radius: 5px;">
                    <!-- Status will load here -->
                </div>
            </div>

            <div class="detail-section" id="ingredientShortageSection" style="display: none; background: #ffebee; padding: 15px; border-left: 4px solid #f44336; border-radius: 3px;">
                <h3 style="color: #c62828; margin-top: 0;">⚠️ Shortage Alert</h3>
                <div id="ingredientShortageList" style="margin-top: 10px;">
                    <!-- Shortage items will load here -->
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeIngredientModal()">Acknowledge</button>
            </div>
        </div>
    </div>

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

    <script>
        let currentOrderId = null;

        // Load orders on page load
        window.addEventListener('DOMContentLoaded', function() {
            loadOrders();
            // Auto-refresh every 3 seconds for faster updates
            setInterval(loadOrders, 3000);
        });

        // Load pending orders from kitchen
        async function loadOrders() {
            try {
                const response = await fetch('../backend/kitchen_get_pending_orders.php');
                const data = await response.json();

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

                const orders = data.data || [];
                
                // Update counts
                const confirmedCount = orders.filter(o => o.status === 'confirmed').length;
                const preparingCount = orders.filter(o => o.status === 'preparing').length;
                const readyCount = orders.filter(o => o.status === 'ready').length;
                
                document.getElementById('confirmedCount').textContent = confirmedCount;
                document.getElementById('preparingCount').textContent = preparingCount;
                document.getElementById('readyCount').textContent = readyCount;

                // Render orders
                renderOrders(orders);

            } catch (error) {
                console.error('Error loading orders:', error);
            }
        }

        // Render orders grid
        function renderOrders(orders) {
            const grid = document.getElementById('ordersGrid');

            if (!orders || orders.length === 0) {
                grid.innerHTML = `
                    <div class="empty-state" style="grid-column: 1/-1;">
                        <i class="fas fa-check-circle"></i>
                        <p>No pending orders. Kitchen is all caught up!</p>
                    </div>
                `;
                return;
            }

            grid.innerHTML = orders.map(order => `
                <div class="order-card">
                    <div class="order-header">
                        <div class="order-number">
                            <i class="fas fa-hash"></i> ${order.order_number}
                        </div>
                        <span class="order-status-badge badge-${order.status}">
                            ${order.status.toUpperCase()}
                        </span>
                    </div>

                    <div class="order-info">
                        <div class="order-info-row">
                            <span><i class="fas fa-table"></i> Table ${order.table_number}</span>
                            <span>${order.section} - Floor ${order.floor}</span>
                        </div>
                        <div class="order-info-row">
                            <span><i class="fas fa-user"></i> ${order.server_name || 'Unknown'}</span>
                            <span><i class="fas fa-boxes"></i> ${order.item_count} items</span>
                        </div>
                    </div>

                    <div class="items-list">
                        ${order.items_summary}
                    </div>

                    <div class="order-actions">
                        <button class="btn btn-view" onclick="viewOrderDetails(${order.id})">
                            <i class="fas fa-eye"></i> View Details
                        </button>
                        ${order.status === 'confirmed' ? `
                            <button class="btn btn-ready" onclick="startPreparing(${order.id})">
                                <i class="fas fa-fire"></i> Start
                            </button>
                        ` : ''}
                        ${order.status === 'ready' ? `
                            <button class="btn btn-ready" onclick="notifyServerReady(${order.id}, '${order.table_number}')" style="background: #4caf50;">
                                <i class="fas fa-bell"></i> Notify Server
                            </button>
                        ` : ''}
                    </div>
                </div>
            `).join('');
        }

        // View order details in modal
        async function viewOrderDetails(orderId) {
            currentOrderId = orderId;

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

                const data = await response.json();

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

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

                // Populate modal
                document.getElementById('modalOrderNumber').textContent = order.order_number;
                document.getElementById('modalTableInfo').textContent = `Table ${order.table_number} (${order.section} - Floor ${order.floor})`;
                document.getElementById('modalServerName').textContent = order.server_name || 'Unknown';
                document.getElementById('modalOrderStatus').textContent = order.status.toUpperCase();
                document.getElementById('modalOrderTime').textContent = new Date(order.created_at).toLocaleTimeString();

                // Render items
                const itemsHTML = items.map(item => `
                    <div class="item-detail-row" style="border-left: ${item.is_reorder ? '4px solid #ff6b35' : '4px solid #ccc'}; padding-left: 12px; flex-wrap: wrap;">
                        <div class="item-detail-name" style="flex: 1; min-width: 150px;">
                            <div style="font-weight: bold; display: flex; align-items: center; gap: 8px;">
                                ${item.item_name}
                                ${item.is_reorder ? '<span style="background: #ff6b35; color: white; padding: 2px 8px; border-radius: 3px; font-size: 10px; font-weight: bold;">REORDER</span>' : ''}
                            </div>
                            <div style="font-size: 11px; color: #999; margin-top: 4px;">₹${item.unit_price.toFixed(2)} each</div>
                            <div style="display: flex; gap: 6px; margin-top: 6px;">
                                <button onclick="viewItemRecipe(${item.item_id}, '${item.item_name}')" style="background: #2196f3; color: white; border: none; padding: 4px 8px; border-radius: 3px; cursor: pointer; font-size: 11px;">
                                    📖 Recipe
                                </button>
                                <button onclick="checkIngredientAvailability(${item.item_id}, '${item.item_name}')" style="background: #ff9800; color: white; border: none; padding: 4px 8px; border-radius: 3px; cursor: pointer; font-size: 11px;">
                                    📦 Stock
                                </button>
                            </div>
                        </div>
                        <div class="item-detail-qty">
                            <div style="font-weight: bold; font-size: 14px;">x${item.quantity}</div>
                        </div>
                        <select class="item-detail-status-dropdown" onchange="updateItemStatus(${item.id}, this.value)" ${order.status === 'ready' ? 'disabled' : ''}>
                            <option value="pending" ${item.status === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="preparing" ${item.status === 'preparing' ? 'selected' : ''}>Preparing</option>
                            <option value="ready" ${item.status === 'ready' ? 'selected' : ''}>Ready</option>
                        </select>
                        <span class="item-status item-status-${item.status}">${item.status.toUpperCase()}</span>
                    </div>
                `).join('');

                document.getElementById('modalItemsList').innerHTML = itemsHTML;

                // Show special requests if available
                const specialRequestsSection = document.getElementById('specialRequestsSection');
                if (order.special_requests) {
                    specialRequestsSection.style.display = 'block';
                    document.getElementById('modalSpecialRequests').textContent = order.special_requests;
                } else {
                    specialRequestsSection.style.display = 'none';
                }

                // Show/hide mark ready button
                const markReadyBtn = document.getElementById('markReadyBtn');
                if (order.status !== 'ready') {
                    markReadyBtn.style.display = 'block';
                } else {
                    markReadyBtn.style.display = 'none';
                }

                // Open modal
                document.getElementById('orderDetailsModal').classList.add('active');

            } catch (error) {
                console.error('Error loading order details:', error);
                Swal.fire('Error', 'Failed to load order details', 'error');
            }
        }

        // Start preparing order
        async function startPreparing(orderId) {
            try {
                const response = await fetch('../backend/kitchen_update_order_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        order_id: orderId,
                        action: 'start_preparation'
                    })
                });

                const data = await response.json();

                if (data.success) {
                    loadOrders();
                    Swal.fire('Success', 'Order preparation started', 'success');
                } else {
                    Swal.fire('Error', data.message || 'Failed to start preparation', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to start preparation', 'error');
            }
        }

        // Update individual item status
        async function updateItemStatus(itemId, newStatus) {
            try {
                const response = await fetch('../backend/kitchen_update_order_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        order_id: currentOrderId,
                        action: 'update_item_status',
                        item_id: itemId,
                        status: newStatus
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // Reload orders
                    loadOrders();
                    
                    // Show different messages based on status
                    let successMessage = `${data.item_name} marked as ${newStatus}`;
                    if (newStatus === 'ready') {
                        successMessage = `${data.item_name} is ready! Server has been notified.`;
                    }
                    
                    // Show success message
                    Swal.fire({
                        title: 'Success!',
                        text: successMessage,
                        icon: 'success',
                        timer: 1500,
                        showConfirmButton: false
                    });

                    // Refresh modal
                    if (currentOrderId) {
                        setTimeout(() => {
                            viewOrderDetails(currentOrderId);
                        }, 500);
                    }
                } else {
                    Swal.fire('Error', data.message || 'Failed to update status', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to update status', 'error');
            }
        }

        // Mark entire order as ready
        async function markOrderReady() {
            Swal.fire({
                title: 'Mark Order Ready?',
                text: 'Are you sure all items in this order are ready for serving?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4caf50',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Mark Ready'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/kitchen_update_order_status.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                order_id: currentOrderId,
                                action: 'mark_order_ready'
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            closeOrderModal();
                            loadOrders();

                            Swal.fire({
                                title: 'Success!',
                                text: 'Order marked as ready for serving',
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to mark order ready', 'error');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to mark order ready', 'error');
                    }
                }
            });
        }

        // Notify server that order is ready for pickup
        async function notifyServerReady(orderId, tableNumber) {
            Swal.fire({
                title: 'Notify Server?',
                text: `Send ready notification to server for Table ${tableNumber}?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4caf50',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Notify Server'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/server_order_ready_notification.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                order_id: orderId
                            })
                        });

                        const data = await response.json();

                        if (data.success) {
                            loadOrders();

                            Swal.fire({
                                title: 'Success!',
                                text: `Server notified for Table ${tableNumber}`,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            });
                        } else {
                            Swal.fire('Error', data.message || 'Failed to notify server', 'error');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to notify server', 'error');
                    }
                }
            });
        }

        // Close modal
        function closeOrderModal() {
            document.getElementById('orderDetailsModal').classList.remove('active');
            currentOrderId = null;
        }

        // Logout
        function logout() {
            Swal.fire({
                title: 'Logout?',
                text: 'Are you sure you want to logout?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Logout'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Call kitchen logout API
                    fetch('../backend/kitchen_logout.php')
                        .then(() => {
                            window.location.href = 'login.php';
                        })
                        .catch(() => {
                            window.location.href = 'login.php';
                        });
                }
            });
        }

        // View Item Recipe
        async function viewItemRecipe(menuItemId, itemName) {
            try {
                const response = await fetch('../backend/kitchen_get_recipe.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ menu_item_id: menuItemId })
                });

                const data = await response.json();

                if (!data.success) {
                    Swal.fire('Info', 'No recipe available for this item yet', 'info');
                    return;
                }

                const recipe = data.data.recipe;
                const ingredients = data.data.ingredients;

                // Populate recipe modal
                document.getElementById('recipeItemName').textContent = itemName;
                document.getElementById('recipeTime').textContent = recipe.preparation_time + ' minutes';
                
                const difficultyBadge = document.getElementById('recipeDifficulty');
                difficultyBadge.textContent = recipe.difficulty_level.toUpperCase();
                difficultyBadge.style.backgroundColor = recipe.difficulty_color;

                // Render ingredients
                const ingredientsHTML = ingredients.map(ing => `
                    <div class="item-detail-row" style="border-left: ${ing.in_stock ? '4px solid #4caf50' : '4px solid #f44336'};">
                        <div class="item-detail-name">
                            <div style="font-weight: bold;">${ing.name}</div>
                            <div style="font-size: 11px; color: #999;">Stock: ${ing.current_stock} ${ing.ingredient_unit}</div>
                        </div>
                        <div style="text-align: center; min-width: 80px;">
                            <div style="font-weight: bold;">${ing.quantity_required} ${ing.required_unit}</div>
                            <span style="display: inline-block; padding: 2px 6px; border-radius: 3px; font-size: 10px; font-weight: bold; color: white; background: ${ing.in_stock ? '#4caf50' : '#f44336'};">
                                ${ing.availability_status}
                            </span>
                        </div>
                    </div>
                `).join('');

                document.getElementById('recipeIngredientsList').innerHTML = ingredientsHTML;

                // Show chef notes if available
                const notesSection = document.getElementById('recipeNotesSection');
                if (recipe.chef_notes) {
                    document.getElementById('recipeNotes').textContent = recipe.chef_notes;
                    notesSection.style.display = 'block';
                } else {
                    notesSection.style.display = 'none';
                }

                // Open recipe modal
                document.getElementById('recipeModal').classList.add('active');

            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to load recipe', 'error');
            }
        }

        // Close recipe modal
        function closeRecipeModal() {
            document.getElementById('recipeModal').classList.remove('active');
        }

        // Check Ingredient Availability
        async function checkIngredientAvailability(menuItemId, itemName) {
            try {
                const response = await fetch('../backend/kitchen_get_recipe.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ menu_item_id: menuItemId })
                });

                const data = await response.json();

                if (!data.success) {
                    Swal.fire('Info', 'No recipe found for this item', 'info');
                    return;
                }

                const ingredients = data.data.ingredients;
                const summary = data.data.summary;

                document.getElementById('ingredientItemName').textContent = itemName;

                // Render ingredient status
                const statusHTML = ingredients.map(ing => {
                    const stockPercentage = (ing.current_stock / ing.quantity_required) * 100;
                    const barColor = ing.in_stock ? '#4caf50' : '#f44336';
                    
                    return `
                        <div style="margin-bottom: 15px; padding: 10px; background: white; border-radius: 3px;">
                            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                                <span style="font-weight: bold;">${ing.name}</span>
                                <span style="color: ${barColor}; font-weight: bold;">${ing.availability_status}</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666; margin-bottom: 5px;">
                                <span>Have: ${ing.current_stock} ${ing.ingredient_unit}</span>
                                <span>Need: ${ing.quantity_required} ${ing.required_unit}</span>
                            </div>
                            <div style="background: #e0e0e0; height: 6px; border-radius: 3px; overflow: hidden;">
                                <div style="background: ${barColor}; height: 100%; width: ${Math.min(stockPercentage, 100)}%;"></div>
                            </div>
                        </div>
                    `;
                }).join('');

                document.getElementById('ingredientStatusList').innerHTML = statusHTML;

                // Show shortage alert if needed
                const shortageSection = document.getElementById('ingredientShortageSection');
                const shortages = ingredients.filter(ing => !ing.in_stock);
                
                if (!summary.all_in_stock && shortages.length > 0) {
                    shortageSection.style.display = 'block';
                    const shortageHTML = shortages.map(s => `
                        <div style="background: white; padding: 8px; border-radius: 3px; margin-bottom: 8px;">
                            <div style="font-weight: bold;">${s.name}</div>
                            <div style="font-size: 12px; color: #666;">
                                Shortage: ${s.quantity_required - s.current_stock} ${s.required_unit} (Have: ${s.current_stock}, Need: ${s.quantity_required})
                            </div>
                        </div>
                    `).join('');
                    document.getElementById('ingredientShortageList').innerHTML = shortageHTML;
                } else {
                    shortageSection.style.display = 'none';
                }

                // Open ingredient modal
                document.getElementById('ingredientModal').classList.add('active');

            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to check ingredients', 'error');
            }
        }

        // Close ingredient modal
        function closeIngredientModal() {
            document.getElementById('ingredientModal').classList.remove('active');
        }

        // Close modal when clicking outside
        window.addEventListener('click', function(event) {
            const orderModal = document.getElementById('orderDetailsModal');
            const recipeModal = document.getElementById('recipeModal');
            const ingredientModal = document.getElementById('ingredientModal');
            
            if (event.target === orderModal) {
                closeOrderModal();
            }
            if (event.target === recipeModal) {
                closeRecipeModal();
            }
            if (event.target === ingredientModal) {
                closeIngredientModal();
            }
        });

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

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

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

</html>
