<?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: #f9fafb;
            color: #1f2937;
        }

        /* ===== NAVBAR ===== */
        .navbar {
            background: linear-gradient(135deg, #9333ea 0%, #7e22ce 100%);
            color: white;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .navbar-brand {
            font-size: 18px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px 0;
        }

        .navbar-brand i {
            font-size: 24px;
        }

        .navbar-menu {
            display: flex;
            gap: 5px;
            flex: 1;
            margin-left: 40px;
        }

        .navbar-menu a {
            color: white;
            text-decoration: none;
            padding: 15px 15px;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            position: relative;
            white-space: nowrap;
        }

        .navbar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        .navbar-menu a.active {
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 3px solid white;
        }

        .navbar-user {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
            color: white;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 14px;
        }

        .user-name {
            font-size: 14px;
            font-weight: 500;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .kitchen-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .sidebar {
            display: none;
        }

        .main-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 20px;
        }
        
        .header h1 {
            font-size: 28px;
            color: #1f2937;
            font-weight: 700;
            line-height: 1;
        }

        .page-header {
            margin-bottom: 30px;
        }

        .page-header h1 {
            font-size: 28px;
            color: #1f2937;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .page-header p {
            color: #6b7280;
            font-size: 14px;
        }

        .page-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .header-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-item {
            text-align: center;
            padding: 20px 15px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            background: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .stat-item:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            transform: translateY(-2px);
        }
        
        .stat-number {
            font-size: 22px;
            font-weight: 800;
            color: #1d2432;
        }
        
        .stat-label {
            font-size: 12px;
            color: #475063;
            text-transform: none;
            font-weight: 700;
        }
        
        .orders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            padding: 60px 20px;
            color: #9ca3af;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 10px;
            opacity: 0.5;
        }

        .empty-state p {
            font-size: 16px;
            color: #6b7280;
        }
        
        .order-card {
            background: white;
            border-radius: 10px;
            padding: 0;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .order-card:hover {
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
            transform: translateY(-2px);
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 16px;
            background: linear-gradient(135deg, #9333ea 0%, #7e22ce 100%);
            color: white;
        }

        .order-number {
            font-size: 16px;
            font-weight: 700;
            color: inherit;
        }

        .order-status-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: #ffffff;
        }
        
        .badge-preparing {
            background: rgba(255, 255, 255, 0.2);
            color: #ffffff;
        }
        
        .badge-ready {
            background: rgba(255, 255, 255, 0.2);
            color: #ffffff;
        }
        
        .order-info {
            margin: 0;
            font-size: 13px;
            color: #3e4758;
            padding: 12px 14px 8px;
        }
        
        .order-info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 6px;
            gap: 10px;
            font-weight: 600;
        }
        
        .items-list {
            background: #ffffff;
            border-radius: 0;
            padding: 0 14px 10px;
            margin-bottom: 8px;
            max-height: 150px;
            overflow-y: auto;
        }
        
        .item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px dashed #dde2ea;
            font-size: 12px;
            gap: 10px;
        }
        
        .item-row:last-child {
            border-bottom: 0;
        }
        
        .item-name {
            flex: 1;
            min-width: 0;
        }

        .item-name-with-photo {
            display: flex;
            align-items: center;
            gap: 10px;
            min-width: 0;
        }

        .item-name-copy {
            display: flex;
            flex-direction: column;
            gap: 4px;
            min-width: 0;
        }

        .item-inline-actions {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .item-mini-btn {
            border: 1px solid #d5dce8;
            border-radius: 7px;
            padding: 4px 8px;
            font-size: 11px;
            font-weight: 700;
            cursor: pointer;
            background: #ffffff;
            color: #243044;
        }

        .item-mini-btn:hover {
            background: #f6f8fb;
        }

        .item-mini-btn.recipe-btn {
            border-color: #8fc3ff;
            color: #1565c0;
            background: #edf5ff;
        }

        .item-mini-btn.stock-btn {
            border-color: #ffd08a;
            color: #d97706;
            background: #fff6e8;
        }

        .item-photo {
            width: 34px;
            height: 34px;
            border-radius: 10px;
            object-fit: cover;
            flex-shrink: 0;
            border: 1px solid #d8dfeb;
            background: #f3f6fb;
        }

        .item-photo-fallback {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #7a8597;
            font-size: 13px;
        }

        .item-name-text {
            min-width: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .item-qty {
            background: #f2f5fa;
            color: #1e2533;
            padding: 3px 7px;
            border-radius: 999px;
            border: 1px solid #d9e0ea;
            font-weight: 700;
        }
        
        .item-status {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
            text-transform: capitalize;
            width: fit-content;
        }
        
        .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;
            padding: 8px 14px 14px;
        }
        
        .btn {
            flex: 1;
            padding: 10px 12px;
            border: 1px solid #d5dce8;
            border-radius: 8px;
            cursor: pointer;
            font-size: 12px;
            font-weight: bold;
            transition: all 0.3s ease;
            background: #fff;
            color: #232b3a;
        }
        
        .btn-view {
            background: #ffffff;
            color: #1f2837;
        }
        
        .btn-view:hover {
            background: #f7f9fc;
        }
        
        .btn-ready {
            background: #f7fff8;
            color: white;
            border-color: #8fd79a;
            color: #1d6d2b;
        }
        
        .btn-ready:hover {
            background: #e8f9eb;
        }

        .btn-disabled,
        .btn:disabled {
            background: #eef2f0;
            border-color: #d8e0da;
            color: #98a39b;
            cursor: not-allowed;
            opacity: 0.8;
        }
        
        .status-new {
            background: #6e7f97;
        }

        .status-in-kitchen {
            background: #f0ab3d;
        }

        .status-delayed {
            background: #ff4343;
        }

        .status-completed {
            background: #43a047;
        }

        .order-card-body-footer {
            padding: 0 14px 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #4d576a;
            font-weight: 700;
            font-size: 13px;
        }

        .delay-text {
            color: #ff4343;
        }

        .good-time {
            color: #2f9e44;
        }

        .top-tools {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .queue-search {
            min-width: 260px;
            position: relative;
        }

        .queue-search input {
            width: 100%;
            padding: 10px 34px 10px 12px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            background: white;
            font-size: 13px;
            outline: none;
            transition: all 0.3s;
        }

        .queue-search input:focus {
            border-color: #9333ea;
            box-shadow: 0 0 0 3px rgba(147, 51, 234, 0.1);
        }

        .queue-search i {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            font-size: 12px;
        }

        .header-stock-btn,
        .header-new-ingredient-btn,
        .header-logout-btn {
            border: 1px solid #e5e7eb;
            background: white;
            color: #1f2937;
            border-radius: 6px;
            padding: 10px 14px;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .header-stock-btn:hover {
            background: #f0f9ff;
            border-color: #0ea5e9;
        }

        .header-new-ingredient-btn:hover {
            background: #fffbeb;
            border-color: #f59e0b;
        }

        .header-logout-btn:hover {
            background: #fee2e2;
            border-color: #ef4444;
        }

        .stock-alert-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 20px;
            height: 20px;
            padding: 0 6px;
            border-radius: 999px;
            background: #ef4444;
            color: white;
            font-size: 11px;
            font-weight: 700;
        }

        .kitchen-summary {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .status-chip-new {
            border-color: #cfd8e6;
            background: #f1f4fa;
        }

        .status-chip-in-kitchen {
            border-color: #ffe2b6;
            background: #fff6e9;
        }

        .status-chip-delayed {
            border-color: #ffd0d0;
            background: #fff1f1;
        }

        .status-chip-completed {
            border-color: #c8ebce;
            background: #effbf1;
        }

        .hide-sidebar .sidebar {
            display: none;
        }

        .hide-sidebar .main-content {
            width: 100%;
        }

        .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;
        }

        #orderDetailsModal .modal-content {
            max-width: 760px;
            padding: 0;
            border-radius: 18px;
            border: 1px solid #dce3ee;
            background:
                radial-gradient(circle at top right, rgba(255, 94, 94, 0.1), transparent 28%),
                linear-gradient(180deg, #ffffff 0%, #f7f9fc 100%);
            box-shadow: 0 22px 60px rgba(11, 23, 45, 0.22);
            overflow: hidden;
        }

        #orderDetailsModal .modal-header {
            margin-bottom: 0;
            padding: 22px 24px 18px;
            border-bottom: 1px solid #e7ecf3;
            background: linear-gradient(135deg, #ffffff 0%, #f6f8fb 100%);
        }

        #orderDetailsModal .modal-header h2 {
            font-size: 30px;
            font-weight: 800;
            color: #1b2433;
            margin: 0;
        }

        #orderDetailsModal .close-btn {
            width: 38px;
            height: 38px;
            border-radius: 999px;
            border: 1px solid #d6ddea;
            background: #ffffff;
            color: #7a8597;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }

        #orderDetailsModal .close-btn:hover {
            background: #f3f6fb;
            color: #334155;
        }

        #orderDetailsModal .detail-section {
            margin: 0;
            padding: 22px 24px 0;
        }

        #orderDetailsModal .detail-section h3 {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
            letter-spacing: 0.08em;
            color: #6a7281;
            margin-bottom: 14px;
            border-bottom: 0;
            padding-bottom: 0;
        }

        #orderDetailsModal .detail-section h3::before {
            content: "";
            width: 34px;
            height: 3px;
            border-radius: 999px;
            background: linear-gradient(90deg, #ff5a5f 0%, #ffb36b 100%);
        }

        #orderDetailsModal .items-detail-list {
            padding: 16px;
            border-radius: 16px;
            background: linear-gradient(180deg, #f8fafd 0%, #f2f5fa 100%);
            border: 1px solid #e4eaf2;
        }

        #orderDetailsModal .item-detail-row {
            margin-bottom: 12px;
            padding: 16px;
            border-radius: 14px;
            border: 1px solid #e6ebf2;
            border-left-width: 4px;
            background: #ffffff;
            box-shadow: 0 8px 18px rgba(15, 23, 42, 0.05);
            gap: 16px;
        }

        #orderDetailsModal .item-detail-row:last-child {
            margin-bottom: 0;
        }

        #orderDetailsModal .item-detail-name {
            flex: 1;
            min-width: 180px;
        }

        #orderDetailsModal .item-detail-qty {
            min-width: 42px;
            align-self: center;
        }

        #orderDetailsModal .item-detail-controls {
            display: flex;
            align-items: center;
            gap: 14px;
            margin-left: auto;
            flex-wrap: wrap;
            justify-content: flex-end;
        }

        #orderDetailsModal .detail-item {
            border: 0;
            padding: 14px 16px;
            border-radius: 14px;
            background: #fffaf4;
            color: #394253;
        }

        #orderDetailsModal .detail-value {
            width: 100%;
            color: #2a3342;
            line-height: 1.6;
        }

        #orderDetailsModal .item-detail-status-dropdown {
            min-width: 156px;
            height: 44px;
            padding: 0 46px 0 16px;
            border-radius: 14px;
            border: 1px solid #cfd9e8;
            background:
                linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
            color: #1f2d3f;
            font-size: 13px;
            font-weight: 800;
            letter-spacing: 0.01em;
            box-shadow: 0 8px 20px rgba(15, 23, 42, 0.06);
            cursor: pointer;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image:
                linear-gradient(45deg, transparent 50%, #4a678f 50%),
                linear-gradient(135deg, #4a678f 50%, transparent 50%),
                linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
            background-position:
                calc(100% - 20px) calc(50% - 3px),
                calc(100% - 14px) calc(50% - 3px),
                0 0;
            background-size:
                6px 6px,
                6px 6px,
                100% 100%;
            background-repeat: no-repeat;
            transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
        }

        #orderDetailsModal .item-detail-status-dropdown:hover {
            border-color: #9fbbdf;
            box-shadow: 0 12px 24px rgba(45, 139, 230, 0.12);
            transform: translateY(-1px);
        }

        #orderDetailsModal .item-detail-status-dropdown:focus {
            outline: none;
            border-color: #2d8be6;
            box-shadow: 0 0 0 4px rgba(45, 139, 230, 0.14), 0 14px 28px rgba(45, 139, 230, 0.12);
        }

        #orderDetailsModal .item-detail-status-dropdown:disabled {
            background-image: linear-gradient(180deg, #f3f5f8 0%, #eceff4 100%);
            color: #8a94a6;
            cursor: not-allowed;
            box-shadow: none;
        }

        #orderDetailsModal .item-detail-status-dropdown option {
            background: #ffffff;
            color: #1f2d3f;
            font-weight: 700;
        }

        #orderDetailsModal .item-detail-status-dropdown option[value="pending"] {
            background: #f6f7f9;
            color: #6b7280;
        }

        #orderDetailsModal .item-detail-status-dropdown option[value="preparing"] {
            background: #fff4e5;
            color: #d97706;
        }

        #orderDetailsModal .item-detail-status-dropdown option[value="ready"] {
            background: #eaf8ee;
            color: #2f9e44;
        }

        #orderDetailsModal .item-detail-row .item-status {
            margin-left: 6px;
            padding: 5px 9px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 800;
            letter-spacing: 0.02em;
        }

        #orderDetailsModal .modal-footer {
            margin-top: 22px;
            padding: 22px 24px 24px;
            border-top: 1px solid #e6ebf2;
            background: #ffffff;
        }

        #orderDetailsModal .btn-primary,
        #orderDetailsModal .btn-secondary {
            min-height: 52px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 800;
            border: 1px solid transparent;
            box-shadow: none;
        }

        #orderDetailsModal .btn-primary {
            background: linear-gradient(135deg, #2d9bf0 0%, #2d8be6 100%);
        }

        #orderDetailsModal #markReadyBtn {
            background: linear-gradient(135deg, #48b54a 0%, #37a53d 100%);
        }

        #orderDetailsModal .btn-secondary {
            background: #eef2f7;
            border-color: #d8e0eb;
            color: #4b5565;
        }

        #orderDetailsModal .btn-primary:hover,
        #orderDetailsModal .btn-secondary:hover {
            transform: translateY(-1px);
        }
        
        .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;
        }

        .stock-overview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 12px;
            margin-bottom: 18px;
        }

        .stock-overview-card {
            background: #f8fafc;
            border: 1px solid #dce4ee;
            border-radius: 12px;
            padding: 14px;
        }

        .stock-overview-card-label {
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            color: #6a7588;
            margin-bottom: 8px;
        }

        .stock-overview-card-value {
            font-size: 26px;
            font-weight: 800;
            color: #1c2332;
        }

        .stock-toolbar {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 14px;
        }

        .stock-toolbar input,
        .stock-toolbar select {
            border: 1px solid #d6dce7;
            border-radius: 10px;
            background: #f7f9fc;
            padding: 10px 12px;
            font-size: 13px;
            color: #1f2837;
            outline: none;
        }

        .stock-toolbar input {
            flex: 1 1 240px;
        }

        .stock-toolbar select {
            min-width: 180px;
        }

        .stock-list {
            display: grid;
            gap: 10px;
            max-height: 420px;
            overflow-y: auto;
            padding-right: 4px;
        }

        .stock-row {
            display: flex;
            justify-content: space-between;
            gap: 14px;
            padding: 14px;
            border-radius: 12px;
            border: 1px solid #dce4ee;
            background: #fff;
        }

        .stock-row-main {
            flex: 1;
            min-width: 0;
        }

        .stock-row-title {
            font-size: 15px;
            font-weight: 800;
            color: #172032;
            margin-bottom: 4px;
        }

        .stock-row-meta {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            font-size: 12px;
            color: #667085;
            margin-bottom: 10px;
        }

        .stock-progress {
            height: 8px;
            background: #ebf0f6;
            border-radius: 999px;
            overflow: hidden;
        }

        .stock-progress-bar {
            height: 100%;
            border-radius: 999px;
        }

        .stock-row-side {
            min-width: 120px;
            text-align: right;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 8px;
        }

        .stock-request-btn {
            border: 1px solid #ffc988;
            background: #fff5e7;
            color: #a95b00;
            border-radius: 999px;
            padding: 6px 10px;
            font-size: 11px;
            font-weight: 800;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .stock-request-btn:hover {
            background: #ffe9c7;
        }

        .stock-request-btn.is-hidden {
            display: none;
        }

        .stock-qty {
            font-size: 16px;
            font-weight: 800;
            color: #1c2332;
        }

        .stock-status-pill {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 5px 10px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.02em;
        }

        .stock-status-adequate {
            background: #e9f8ec;
            color: #1f7a35;
        }

        .stock-status-normal {
            background: #eef4ff;
            color: #295db2;
        }

        .stock-status-low {
            background: #fff1f1;
            color: #c62828;
        }

        .stock-empty-state {
            padding: 32px 16px;
            text-align: center;
            color: #7b8697;
            border: 1px dashed #d5dde8;
            border-radius: 12px;
            background: #fafbfd;
        }
        
        .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-main {
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .item-detail-photo {
            width: 56px;
            height: 56px;
            border-radius: 14px;
            object-fit: cover;
            border: 1px solid #d7dfeb;
            background: #f4f7fb;
            flex-shrink: 0;
        }

        .item-detail-photo-fallback {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: #7a8597;
            font-size: 18px;
        }
        
        .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) {
            .navbar {
                padding: 0 15px;
                flex-wrap: wrap;
                gap: 10px;
            }

            .navbar-brand {
                flex: 1;
                min-width: 160px;
            }

            .navbar-menu {
                flex: 0 100%;
                margin-left: 0;
                padding: 0;
                width: 100%;
                border-top: 1px solid rgba(255, 255, 255, 0.1);
                padding-top: 10px;
            }

            .navbar-user {
                flex: 0 100%;
                width: 100%;
                padding-top: 10px;
                border-top: 1px solid rgba(255, 255, 255, 0.1);
                gap: 10px;
            }

            .main-content {
                padding: 15px;
            }

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

            .header-stats {
                grid-template-columns: repeat(2, 1fr);
            }

            .queue-search {
                min-width: 100%;
            }

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

            .stat-item {
                padding: 15px 12px;
            }
        }

        @media (max-width: 480px) {
            .page-header h1 {
                font-size: 22px;
            }

            .header-stats {
                grid-template-columns: 1fr;
            }

            .navbar {
                flex-direction: column;
            }

            .navbar-brand {
                width: 100%;
            }

            .navbar-menu {
                width: 100%;
            }

            .navbar-user {
                width: 100%;
                justify-content: space-between;
            }

            .main-content {
                padding: 12px;
            }

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

            .order-card {
                padding: 0;
            }
        }
    </style>
</head>

<body>
    <!-- Navigation Bar -->
    <nav class="navbar">
        <div class="navbar-brand"><i class="fas fa-utensils"></i> Kitchen</div>
        <div class="navbar-menu">
            <a href="dashboard.php" class="active">Orders</a>
        </div>
        <div class="navbar-user">
            <!-- <div class="user-info">
                <div class="user-avatar">K</div>
                <div class="user-name" id="userName"><?php echo htmlspecialchars($chef_name ?? 'Chef'); ?></div>
            </div> -->
            <button class="logout-btn" onclick="logout()">Logout</button>
        </div>
    </nav>

    <div class="kitchen-container">
        <!-- Main Content -->
        <div class="main-content">
            <!-- Page Header -->
            <div class="page-header">
                <h1>Kitchen Orders</h1>
                <p>Manage and track orders in real-time</p>
            </div>

            <!-- Status Cards -->
            <div class="header-stats">
                <div class="stat-item">
                    <div class="stat-label">New Orders</div>
                    <div class="stat-number" id="confirmedCount">0</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">In Kitchen</div>
                    <div class="stat-number" id="preparingCount">0</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">Pending</div>
                    <div class="stat-number" id="delayedCount">0</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">Completed</div>
                    <div class="stat-number" id="completedCount">0</div>
                </div>
            </div>

            <!-- Tools Bar -->
            <div class="header" style="margin-bottom: 20px;">
                <div class="queue-search">
                    <input type="text" id="orderSearchInput" placeholder="Search order, table, item..." oninput="renderOrders(window.latestOrders || [])">
                    <i class="fas fa-search"></i>
                </div>
                <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                    <button class="header-stock-btn" onclick="openStockOverviewModal()">
                        <i class="fas fa-boxes-stacked"></i> Ingredients
                        <span class="stock-alert-badge" id="stockAlertBadge">0</span>
                    </button>
                    <button class="header-new-ingredient-btn" onclick="openNewIngredientRequestDialog()">
                        <i class="fas fa-seedling"></i> Request Ingredient
                    </button>
                </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 order-modal-content">
            <div class="modal-header">
                <h2>Order Details</h2>
                <button class="close-btn" onclick="closeOrderModal()">&times;</button>
            </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="printKotBtn" onclick="printKotTicket()" style="display: none; background: #2196f3;">
                    <i class="fas fa-print"></i> Print KOT
                </button>
                <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>

    <div id="stockOverviewModal" class="modal">
        <div class="modal-content" style="max-width: 920px;">
            <div class="modal-header">
                <h2><i class="fas fa-warehouse"></i> All Ingredient Availability</h2>
                <button class="close-btn" onclick="closeStockOverviewModal()">&times;</button>
            </div>

            <div class="stock-overview-grid">
                <div class="stock-overview-card">
                    <div class="stock-overview-card-label">Active Ingredients</div>
                    <div class="stock-overview-card-value" id="stockTotalIngredients">0</div>
                </div>
                <div class="stock-overview-card">
                    <div class="stock-overview-card-label">Low Stock</div>
                    <div class="stock-overview-card-value" id="stockLowCount">0</div>
                </div>
                <div class="stock-overview-card">
                    <div class="stock-overview-card-label">Normal</div>
                    <div class="stock-overview-card-value" id="stockNormalCount">0</div>
                </div>
                <div class="stock-overview-card">
                    <div class="stock-overview-card-label">Adequate</div>
                    <div class="stock-overview-card-value" id="stockAdequateCount">0</div>
                </div>
            </div>

            <div class="stock-toolbar">
                <input type="text" id="stockSearchInput" placeholder="Search ingredient name or supplier..." oninput="renderStockOverviewList()">
                <select id="stockStatusFilter" onchange="renderStockOverviewList()">
                    <option value="">All stock levels</option>
                    <option value="low">Low stock only</option>
                    <option value="normal">Normal stock</option>
                    <option value="adequate">Adequate stock</option>
                </select>
            </div>

            <div id="stockOverviewList" class="stock-list">
                <div class="stock-empty-state">Loading ingredient availability...</div>
            </div>

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

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

    <script>
        let currentOrderId = null;
        let kitchenStockIngredients = [];
        const DELAY_THRESHOLD_MINUTES = 20;

        function escapeHtml(value) {
            return String(value ?? '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function parseOrderDateTime(dateTimeValue) {
            if (!dateTimeValue) return null;
            if (dateTimeValue instanceof Date) return dateTimeValue;

            const normalized = String(dateTimeValue).trim().replace(' ', 'T');
            const sqlMatch = normalized.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/);

            if (sqlMatch) {
                const [, year, month, day, hours, minutes, seconds = '00'] = sqlMatch;
                return new Date(
                    Number(year),
                    Number(month) - 1,
                    Number(day),
                    Number(hours),
                    Number(minutes),
                    Number(seconds)
                );
            }

            const parsed = new Date(dateTimeValue);
            return Number.isNaN(parsed.getTime()) ? null : parsed;
        }

        function getMinutesSince(createdAt) {
            const created = parseOrderDateTime(createdAt);
            if (!created) return 0;
            const now = new Date();
            const diffMs = now - created;
            return Math.max(0, Math.floor(diffMs / 60000));
        }

        function formatOrderTime(createdAt) {
            const created = parseOrderDateTime(createdAt);
            if (!created) return '--';

            return created.toLocaleTimeString([], {
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
            });
        }

        function formatOrderDate(createdAt) {
            const created = parseOrderDateTime(createdAt);
            if (!created) return '--//--//--';

            const day = String(created.getDate()).padStart(2, '0');
            const month = String(created.getMonth() + 1).padStart(2, '0');
            const year = String(created.getFullYear()).slice(-2);

            return `${day}//${month}//${year}`;
        }

        function getOrderVisualState(order) {
            const elapsed = getMinutesSince(order.created_at);
            const isDelayed = order.status !== 'ready' && elapsed > DELAY_THRESHOLD_MINUTES;

            if (isDelayed) {
                return { cardClass: 'status-delayed', badgeLabel: 'Pending', footerClass: '', isDelayed: true };
            }
            if (order.status === 'confirmed') {
                return { cardClass: 'status-new', badgeLabel: 'New Order', footerClass: '', isDelayed: false };
            }
            if (order.status === 'preparing') {
                return { cardClass: 'status-in-kitchen', badgeLabel: 'In Kitchen', footerClass: '', isDelayed: false };
            }
            return { cardClass: 'status-completed', badgeLabel: 'Completed', footerClass: 'good-time', isDelayed: false };
        }

        function resolveImagePath(imagePath) {
            if (!imagePath) return '';
            if (/^(https?:)?\/\//i.test(imagePath)) return imagePath;

            const normalized = imagePath.replace(/^\.?\//, '');
            if (normalized.startsWith('assets/')) {
                return `../${normalized}`;
            }
            if (normalized.startsWith('uploads/')) {
                return `../assets/${normalized}`;
            }
            if (!normalized.includes('/')) {
                return `../assets/uploads/menu/${normalized}`;
            }
            return `../${normalized}`;
        }

        function renderItemThumb(imagePath, altText, className = 'item-photo') {
            const resolvedPath = resolveImagePath(imagePath);

            if (resolvedPath) {
                return `<img src="${escapeHtml(resolvedPath)}" alt="${escapeHtml(altText)}" class="${className}" loading="lazy" onerror="this.outerHTML='&lt;span class=&quot;${className} ${className}-fallback&quot;&gt;&lt;i class=&quot;fas fa-utensils&quot;&gt;&lt;/i&gt;&lt;/span&gt;'">`;
            }

            return `<span class="${className} ${className}-fallback"><i class="fas fa-utensils"></i></span>`;
        }

        function formatItemsSummary(items) {
            if (!items || !items.length) {
                return '<div class="item-row"><span class="item-name">No items</span></div>';
            }

            return items.map(item => `
                <div class="item-row">
                    <span class="item-name">
                        <span class="item-name-with-photo">
                            ${renderItemThumb(item.image_path, item.item_name)}
                            <span class="item-name-copy">
                                <span class="item-name-text">${escapeHtml(item.item_name)}</span>
                                <span class="item-status item-status-${escapeHtml(item.status || 'pending')}">
                                    ${escapeHtml((item.status || 'pending').charAt(0).toUpperCase() + (item.status || 'pending').slice(1))}
                                </span>
                                <span class="item-inline-actions">
                                    <button
                                        type="button"
                                        class="item-mini-btn recipe-btn"
                                        onclick='viewItemRecipe(${item.item_id}, ${JSON.stringify(String(item.item_name || 'Item'))})'
                                    >
                                        Recipe
                                    </button>
                                    <button
                                        type="button"
                                        class="item-mini-btn stock-btn"
                                        onclick='checkIngredientAvailability(${item.item_id}, ${JSON.stringify(String(item.item_name || 'Item'))})'
                                    >
                                        Stock
                                    </button>
                                </span>
                            </span>
                        </span>
                    </span>
                    <span class="item-qty">x${escapeHtml(item.quantity)}</span>
                </div>
            `).join('');
        }

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

        // 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 || [];
                window.latestOrders = orders;
                
                // Update counts
                const confirmedCount = orders.filter(o => o.status === 'confirmed').length;
                const preparingCount = orders.filter(o => o.status === 'preparing').length;
                const completedCount = Number.isFinite(Number(data.completed_count))
                    ? Number(data.completed_count)
                    : orders.filter(o => o.status === 'ready' || o.status === 'completed').length;
                const delayedCount = orders.filter(o => {
                    const elapsed = getMinutesSince(o.created_at);
                    return o.status !== 'ready' && elapsed > DELAY_THRESHOLD_MINUTES;
                }).length;
                
                document.getElementById('confirmedCount').textContent = confirmedCount;
                document.getElementById('preparingCount').textContent = preparingCount;
                document.getElementById('completedCount').textContent = completedCount;
                document.getElementById('delayedCount').textContent = delayedCount;

                // Render orders
                renderOrders(orders);

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

        // Render orders grid
        function renderOrders(orders) {
            const grid = document.getElementById('ordersGrid');
            const searchTerm = (document.getElementById('orderSearchInput')?.value || '').trim().toLowerCase();
            let filteredOrders = orders || [];

            if (searchTerm) {
                filteredOrders = filteredOrders.filter(order => {
                    const searchBlob = [
                        order.order_number,
                        order.table_number,
                        order.server_name,
                        order.items_summary,
                        ...(order.items || []).map(item => item.item_name),
                        order.status
                    ].join(' ').toLowerCase();
                    return searchBlob.includes(searchTerm);
                });
            }

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

            grid.innerHTML = filteredOrders.map(order => {
                const visualState = getOrderVisualState(order);
                const orderTimestamp = order.kot_generated_at || order.created_at;
                const orderDate = formatOrderDate(orderTimestamp);
                const orderTime = formatOrderTime(orderTimestamp);
                const statusLabel = visualState.badgeLabel;
                const kotTicket = order.kot_ticket_number || 'Not generated';

                return `
                <div class="order-card">
                    <div class="order-header ${visualState.cardClass}">
                        <div class="order-number">
                            <i class="fas fa-chair"></i> Table No : ${order.table_number ?? '--'}
                        </div>
                        <span class="order-status-badge badge-${order.status}">
                            ${statusLabel}
                        </span>
                    </div>

                    <div class="order-info">
                        <div class="order-info-row">
                            <span><i class="fas fa-user-circle"></i> Server : ${escapeHtml(order.server_name || 'Unknown')}</span>
                            <span>${escapeHtml(orderDate)}</span>
                        </div>
                        <div class="order-info-row">
                            <span><i class="fas fa-hashtag"></i> ${escapeHtml(order.order_number)}</span>
                            <span>${escapeHtml(orderTime)}</span>
                        </div>
                        <div class="order-info-row">
                            <span><i class="fas fa-receipt"></i> KOT : ${escapeHtml(kotTicket)}</span>
                            <span><i class="fas fa-boxes-stacked"></i> ${order.item_count} items</span>
                        </div>
                    </div>

                    <div class="items-list">
                        ${formatItemsSummary(order.items)}
                    </div>

                    <div class="order-actions">
                        ${order.status === 'confirmed' ? `
                            <button class="btn btn-ready" onclick="startPreparing(${order.id})">
                                <i class="fas fa-play"></i> Start
                            </button>
                            <button class="btn btn-disabled" disabled title="Start the order first to enable Mark Done">
                                <i class="fas fa-check"></i> Mark Done
                            </button>
                        ` : ''}
                        ${order.status === 'preparing' ? `
                            <button class="btn btn-ready" onclick="viewOrderDetails(${order.id})">
                                <i class="fas fa-pause"></i> Update
                            </button>
                            <button class="btn btn-ready" onclick="quickMarkDone(${order.id})">
                                <i class="fas fa-check"></i> Mark Done
                            </button>
                        ` : ''}
                        ${order.status === 'ready' ? `
                            <button class="btn btn-ready" onclick='notifyServerReady(${order.id}, ${JSON.stringify(String(order.table_number ?? "N/A"))})' style="background: #4caf50;">
                                <i class="fas fa-check"></i> Notify
                            </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
                const printKotBtn = document.getElementById('printKotBtn');
                if (order.kot && order.kot.id) {
                    printKotBtn.style.display = 'block';
                    printKotBtn.dataset.kotId = order.kot.id;
                } else {
                    printKotBtn.style.display = 'none';
                    printKotBtn.dataset.kotId = '';
                }

                // 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">
                            <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-controls">
                            <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>
                    </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 === 'preparing') {
                    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;
        }

        // Quick mark entire order as ready from card
        async function quickMarkDone(orderId) {
            const order = (window.latestOrders || []).find(o => Number(o.id) === Number(orderId));
            if (!order || order.status !== 'preparing') {
                Swal.fire('Info', 'Start the order before marking it done.', 'info');
                return;
            }

            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: 'mark_order_ready'
                    })
                });

                const data = await response.json();

                if (data.success) {
                    loadOrders();
                    Swal.fire({
                        title: 'Order Ready',
                        text: 'Order moved to completed kitchen status.',
                        icon: 'success',
                        timer: 1600,
                        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');
            }
        }

        async function refreshStockSummaryBadge() {
            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=get_stock_summary');
                const data = await response.json();

                if (!data.success || !data.data) {
                    return;
                }

                const lowStockCount = Number(data.data.low_stock_count || 0);
                document.getElementById('stockAlertBadge').textContent = lowStockCount;
            } catch (error) {
                console.error('Error loading stock summary:', error);
            }
        }

        function printKotTicket() {
            const printKotBtn = document.getElementById('printKotBtn');
            const kotId = printKotBtn ? printKotBtn.dataset.kotId : '';
            if (!kotId) {
                Swal.fire('Info', 'KOT is not available for this order', 'info');
                return;
            }
            window.open(`../backend/print_kot.php?kot_id=${encodeURIComponent(kotId)}`, '_blank');
        }

        // 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 requiredForComparison = Number(ing.quantity_required_in_stock_unit || ing.quantity_required || 0);
                    const stockPercentage = requiredForComparison > 0
                        ? (Number(ing.current_stock || 0) / requiredForComparison) * 100
                        : 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: ${(Number(s.shortage_amount || 0)).toFixed(3).replace(/\.?0+$/, '')} ${s.ingredient_unit} (Have: ${s.current_stock} ${s.ingredient_unit}, Need: ${s.quantity_required} ${s.required_unit})
                            </div>
                            <div style="margin-top: 8px;">
                                <button
                                    type="button"
                                    class="stock-request-btn"
                                    data-ingredient-id="${escapeHtml(s.ingredient_id || '')}"
                                    data-name="${escapeHtml(s.name || '')}"
                                    data-unit="${escapeHtml(s.ingredient_unit || '')}"
                                    data-shortage="${escapeHtml(s.shortage_amount || 0)}"
                                    data-item-name="${escapeHtml(itemName || '')}"
                                    data-have="${escapeHtml(s.current_stock || 0)}"
                                    data-need="${escapeHtml(s.quantity_required || 0)}"
                                    data-need-unit="${escapeHtml(s.required_unit || '')}"
                                    onclick="requestShortagePurchase(this)">
                                    Request Purchase
                                </button>
                            </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');
        }

        async function openStockOverviewModal() {
            document.getElementById('stockOverviewModal').classList.add('active');
            await loadStockOverview();
        }

        function closeStockOverviewModal() {
            document.getElementById('stockOverviewModal').classList.remove('active');
        }

        async function loadStockOverview() {
            const list = document.getElementById('stockOverviewList');
            list.innerHTML = '<div class="stock-empty-state">Loading ingredient availability...</div>';

            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients&status=active');
                const data = await response.json();

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

                kitchenStockIngredients = data.data || [];
                updateStockOverviewSummary();
                renderStockOverviewList();
                refreshStockSummaryBadge();
            } catch (error) {
                console.error('Error loading stock overview:', error);
                list.innerHTML = '<div class="stock-empty-state">Failed to load ingredient availability.</div>';
            }
        }

        function updateStockOverviewSummary() {
            const total = kitchenStockIngredients.length;
            const low = kitchenStockIngredients.filter(item => item.stock_status === 'low').length;
            const normal = kitchenStockIngredients.filter(item => item.stock_status === 'normal').length;
            const adequate = kitchenStockIngredients.filter(item => item.stock_status === 'adequate').length;

            document.getElementById('stockTotalIngredients').textContent = total;
            document.getElementById('stockLowCount').textContent = low;
            document.getElementById('stockNormalCount').textContent = normal;
            document.getElementById('stockAdequateCount').textContent = adequate;
        }

        function calculateSuggestedRequestQty(currentStock, minimumStock) {
            const current = Number(currentStock || 0);
            const minimum = Number(minimumStock || 0);

            if (minimum > current) {
                return Number((minimum - current).toFixed(3));
            }

            if (minimum > 0) {
                return Number((minimum * 0.5).toFixed(3));
            }

            return 1;
        }

        async function submitKitchenRequisition(payload) {
            const response = await fetch('../backend/kitchen_create_requisition.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Failed to send requisition');
            }

            return data;
        }

        async function submitNewIngredientRequest(payload) {
            const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=create_request', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error(data.message || 'Failed to submit new ingredient request');
            }

            return data;
        }

        async function openNewIngredientRequestDialog() {
            const result = await Swal.fire({
                title: 'Request New Ingredient',
                html: `
                    <style>
                        .new-ing-form {
                            text-align: left;
                            margin-top: 4px;
                        }
                        .new-ing-grid {
                            display: grid;
                            grid-template-columns: 1fr 1fr;
                            gap: 10px;
                            margin-bottom: 10px;
                        }
                        .new-ing-row {
                            display: flex;
                            flex-direction: column;
                            gap: 6px;
                        }
                        .new-ing-label {
                            font-size: 12px;
                            font-weight: 700;
                            color: #374151;
                        }
                        .new-ing-help {
                            font-size: 11px;
                            color: #6b7280;
                            margin-top: -2px;
                        }
                        .new-ing-field,
                        .new-ing-area {
                            width: 100%;
                            border: 1px solid #d1d5db;
                            border-radius: 8px;
                            padding: 10px 12px;
                            font-size: 14px;
                            outline: none;
                            box-sizing: border-box;
                        }
                        .new-ing-field:focus,
                        .new-ing-area:focus {
                            border-color: #7aaee1;
                            box-shadow: 0 0 0 2px rgba(122, 174, 225, 0.2);
                        }
                        .new-ing-area {
                            min-height: 84px;
                            resize: vertical;
                            font-family: inherit;
                        }
                        .new-ing-row.full {
                            grid-column: 1 / -1;
                        }
                        @media (max-width: 640px) {
                            .new-ing-grid {
                                grid-template-columns: 1fr;
                            }
                        }
                    </style>
                    <div class="new-ing-form">
                        <div class="new-ing-grid">
                            <div class="new-ing-row">
                                <label for="newIngName" class="new-ing-label">Ingredient Name *</label>
                                <input id="newIngName" class="new-ing-field" placeholder="e.g., Quinoa">
                            </div>
                            <div class="new-ing-row">
                                <label for="newIngUnit" class="new-ing-label">Unit *</label>
                                <input id="newIngUnit" class="new-ing-field" placeholder="e.g., kg, L, pcs">
                            </div>
                            <div class="new-ing-row">
                                <label for="newIngQty" class="new-ing-label">Requested Quantity *</label>
                                <input id="newIngQty" type="number" min="0.01" step="0.01" value="1" class="new-ing-field">
                                <div class="new-ing-help">Enter how much kitchen needs now.</div>
                            </div>
                            <div class="new-ing-row">
                                <label for="newIngPriority" class="new-ing-label">Priority</label>
                                <select id="newIngPriority" class="new-ing-field">
                                    <option value="high">High</option>
                                    <option value="medium" selected>Medium</option>
                                    <option value="low">Low</option>
                                </select>
                            </div>
                            <div class="new-ing-row full">
                                <label for="newIngSupplier" class="new-ing-label">Preferred Supplier</label>
                                <input id="newIngSupplier" class="new-ing-field" placeholder="Optional supplier name">
                            </div>
                            <div class="new-ing-row full">
                                <label for="newIngDesc" class="new-ing-label">Description</label>
                                <textarea id="newIngDesc" class="new-ing-area" placeholder="Short description of the ingredient"></textarea>
                            </div>
                            <div class="new-ing-row full">
                                <label for="newIngNotes" class="new-ing-label">Notes</label>
                                <textarea id="newIngNotes" class="new-ing-area" placeholder="Why kitchen needs this ingredient"></textarea>
                            </div>
                        </div>
                    </div>
                `,
                width: 680,
                showCancelButton: true,
                confirmButtonText: 'Send Request',
                cancelButtonText: 'Cancel',
                focusConfirm: false,
                preConfirm: () => {
                    const name = (document.getElementById('newIngName').value || '').trim();
                    const unit = (document.getElementById('newIngUnit').value || '').trim();
                    const quantity = Number(document.getElementById('newIngQty').value || 0);
                    const priority = (document.getElementById('newIngPriority').value || 'medium').trim();
                    const supplier = (document.getElementById('newIngSupplier').value || '').trim();
                    const description = (document.getElementById('newIngDesc').value || '').trim();
                    const notes = (document.getElementById('newIngNotes').value || '').trim();

                    if (!name) {
                        Swal.showValidationMessage('Ingredient name is required');
                        return false;
                    }
                    if (!unit) {
                        Swal.showValidationMessage('Unit is required');
                        return false;
                    }
                    if (!(quantity > 0)) {
                        Swal.showValidationMessage('Quantity must be greater than 0');
                        return false;
                    }

                    return { name, unit, quantity, priority, supplier, description, notes };
                }
            });

            if (!result.isConfirmed || !result.value) return;

            const payload = {
                name: result.value.name,
                unit: result.value.unit,
                quantity_requested: result.value.quantity,
                priority: result.value.priority,
                supplier: result.value.supplier,
                description: result.value.description,
                notes: result.value.notes,
                requested_by: <?php echo json_encode($chef_name ?: 'kitchen'); ?>
            };

            try {
                await submitNewIngredientRequest(payload);
                Swal.fire('Request Sent', 'New ingredient request sent to Purchase Manager.', 'success');
            } catch (error) {
                console.error('Error creating new ingredient request:', error);
                Swal.fire('Error', error.message || 'Failed to submit request', 'error');
            }
        }

        async function openPurchaseRequestDialog(prefill) {
            const ingredientName = prefill.item_description || 'Ingredient';
            const today = new Date();
            const neededBy = new Date(today.getTime() + 2 * 24 * 60 * 60 * 1000);
            const minDate = today.toISOString().slice(0, 10);
            const defaultDate = neededBy.toISOString().slice(0, 10);

            const result = await Swal.fire({
                title: `Request Purchase: ${escapeHtml(ingredientName)}`,
                html: `
                    <div style="text-align: left;">
                        <label style="font-size: 12px; font-weight: 700;">Quantity (${escapeHtml(prefill.unit || '-')})</label>
                        <input id="reqQtyInput" type="number" step="0.001" min="0.001" value="${escapeHtml(prefill.quantity || 1)}" class="swal2-input" style="margin: 6px 0 10px;">
                        <label style="font-size: 12px; font-weight: 700;">Priority</label>
                        <select id="reqPriorityInput" class="swal2-input" style="margin: 6px 0 10px;">
                            <option value="high" selected>High</option>
                            <option value="urgent">Urgent</option>
                            <option value="medium">Medium</option>
                            <option value="low">Low</option>
                        </select>
                        <label style="font-size: 12px; font-weight: 700;">Needed By</label>
                        <input id="reqDateInput" type="date" min="${minDate}" value="${defaultDate}" class="swal2-input" style="margin: 6px 0 10px;">
                        <label style="font-size: 12px; font-weight: 700;">Notes</label>
                        <textarea id="reqNotesInput" class="swal2-textarea" style="margin: 6px 0 0; min-height: 100px;" placeholder="Add request context">${escapeHtml(prefill.notes || '')}</textarea>
                    </div>
                `,
                focusConfirm: false,
                showCancelButton: true,
                confirmButtonText: 'Send Request',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    const qty = Number(document.getElementById('reqQtyInput').value || 0);
                    const priority = document.getElementById('reqPriorityInput').value || 'high';
                    const date = document.getElementById('reqDateInput').value || '';
                    const notes = (document.getElementById('reqNotesInput').value || '').trim();

                    if (qty <= 0) {
                        Swal.showValidationMessage('Quantity must be greater than zero');
                        return false;
                    }

                    return { qty, priority, date, notes };
                }
            });

            if (!result.isConfirmed || !result.value) {
                return;
            }

            const payload = {
                ingredient_id: prefill.ingredient_id || null,
                item_description: prefill.item_description || '',
                unit: prefill.unit || '',
                quantity: result.value.qty,
                priority: result.value.priority,
                needed_by_date: result.value.date,
                notes: result.value.notes
            };

            try {
                const apiResult = await submitKitchenRequisition(payload);

                Swal.fire({
                    title: apiResult.duplicate ? 'Already Requested' : 'Request Sent',
                    text: apiResult.message || 'Requisition submitted to Purchase Manager',
                    icon: apiResult.duplicate ? 'info' : 'success',
                    timer: 2200,
                    showConfirmButton: false
                });

                if (document.getElementById('stockOverviewModal').classList.contains('active')) {
                    await loadStockOverview();
                } else {
                    refreshStockSummaryBadge();
                }
            } catch (error) {
                console.error('Error creating requisition:', error);
                Swal.fire('Error', error.message || 'Failed to send requisition', 'error');
            }
        }

        function requestIngredientPurchase(button) {
            const ingredientId = Number(button.dataset.ingredientId || 0) || null;
            const ingredientName = button.dataset.name || 'Ingredient';
            const unit = button.dataset.unit || '';
            const currentStock = Number(button.dataset.currentStock || 0);
            const minimumStock = Number(button.dataset.minimumStock || 0);
            const quantity = calculateSuggestedRequestQty(currentStock, minimumStock);

            openPurchaseRequestDialog({
                ingredient_id: ingredientId,
                item_description: ingredientName,
                unit: unit,
                quantity: quantity,
                notes: `Low stock alert from kitchen dashboard. Current: ${currentStock} ${unit}, Minimum: ${minimumStock} ${unit}.`
            });
        }

        function requestShortagePurchase(button) {
            const ingredientId = Number(button.dataset.ingredientId || 0) || null;
            const ingredientName = button.dataset.name || 'Ingredient';
            const unit = button.dataset.unit || '';
            const shortageQty = Number(button.dataset.shortage || 0);
            const quantity = shortageQty > 0 ? Number(shortageQty.toFixed(3)) : 1;
            const itemName = button.dataset.itemName || 'Dish';
            const have = Number(button.dataset.have || 0);
            const need = Number(button.dataset.need || 0);
            const needUnit = button.dataset.needUnit || unit;

            openPurchaseRequestDialog({
                ingredient_id: ingredientId,
                item_description: ingredientName,
                unit: unit,
                quantity: quantity,
                notes: `Dish shortage from ${itemName}. Have: ${have} ${unit}, Need: ${need} ${needUnit}, Shortage: ${quantity} ${unit}.`
            });
        }

        function renderStockOverviewList() {
            const list = document.getElementById('stockOverviewList');
            const searchTerm = (document.getElementById('stockSearchInput')?.value || '').trim().toLowerCase();
            const statusFilter = document.getElementById('stockStatusFilter')?.value || '';

            const filtered = kitchenStockIngredients.filter(item => {
                const matchesSearch = !searchTerm || [
                    item.name,
                    item.supplier,
                    item.description
                ].join(' ').toLowerCase().includes(searchTerm);

                const matchesStatus = !statusFilter || item.stock_status === statusFilter;
                return matchesSearch && matchesStatus;
            });

            if (!filtered.length) {
                list.innerHTML = '<div class="stock-empty-state">No ingredients match the current filter.</div>';
                return;
            }

            list.innerHTML = filtered.map(item => {
                const currentStock = Number(item.current_stock || 0);
                const minimumStock = Number(item.minimum_stock || 0);
                const progressPercent = minimumStock > 0
                    ? Math.min((currentStock / minimumStock) * 100, 100)
                    : 100;
                const progressColor = item.stock_status === 'low'
                    ? '#d93025'
                    : item.stock_status === 'adequate'
                        ? '#2f9e44'
                        : '#2b6cb0';

                return `
                    <div class="stock-row">
                        <div class="stock-row-main">
                            <div class="stock-row-title">${escapeHtml(item.name)}</div>
                            <div class="stock-row-meta">
                                <span>Unit: ${escapeHtml(item.unit || '-')}</span>
                                <span>Minimum: ${escapeHtml(item.minimum_stock)} ${escapeHtml(item.unit || '')}</span>
                                <span>Supplier: ${escapeHtml(item.supplier || 'Not assigned')}</span>
                            </div>
                            <div class="stock-progress">
                                <div class="stock-progress-bar" style="width: ${progressPercent}%; background: ${progressColor};"></div>
                            </div>
                        </div>
                        <div class="stock-row-side">
                            <div class="stock-qty">${escapeHtml(item.current_stock)} ${escapeHtml(item.unit || '')}</div>
                            <span class="stock-status-pill stock-status-${escapeHtml(item.stock_status)}">${escapeHtml(item.stock_status)}</span>
                            <button
                                type="button"
                                class="stock-request-btn ${item.stock_status === 'low' ? '' : 'is-hidden'}"
                                data-ingredient-id="${escapeHtml(item.id)}"
                                data-name="${escapeHtml(item.name)}"
                                data-unit="${escapeHtml(item.unit || '')}"
                                data-current-stock="${escapeHtml(item.current_stock)}"
                                data-minimum-stock="${escapeHtml(item.minimum_stock)}"
                                onclick="requestIngredientPurchase(this)">
                                Request Purchase
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 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');
            const stockOverviewModal = document.getElementById('stockOverviewModal');
            
            if (event.target === orderModal) {
                closeOrderModal();
            }
            if (event.target === recipeModal) {
                closeRecipeModal();
            }
            if (event.target === ingredientModal) {
                closeIngredientModal();
            }
            if (event.target === stockOverviewModal) {
                closeStockOverviewModal();
            }
        });

        // 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>
