<!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="zytheme">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Menu Management - 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">

    <!-- Bootstrap CSS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

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

    <title>Menu Management - Granny Restaurant</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 0;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .admin-name {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
        }

        .sidebar-menu li {
            margin: 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: white;
            text-decoration: none;
            transition: all 0.3s ease;
            position: relative;
        }

        .sidebar-menu a:hover {
            background: rgba(212, 165, 116, 0.1);
            padding-left: 35px;
        }

        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.15);
            color: #ffffff;
            font-weight: 600;
        }

        .sidebar-menu a i {
            width: 20px;
            text-align: center;
        }

        .notification-badge {
            background: #e74c3c;
            color: white;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            margin-left: auto;
        }

        .notification-badge.hidden {
            display: none;
        }

        .sidebar-footer {
            padding: 20px 25px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            margin-top: auto;
        }

        .logout-btn {
            width: 100%;
            padding: 12px;
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .logout-btn:hover {
            background: #c0392b;
        }

        /* Topbar */
        .topbar {
            position: fixed;
            left: 280px;
            top: 0;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e0e0e0;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 999;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .topbar-title {
            font-size: 22px;
            font-weight: 700;
            color: #2c3e50;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 25px;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 18px;
        }

        .user-info p {
            margin: 0;
            font-size: 12px;
            color: #999;
        }

        .user-info strong {
            display: block;
            color: #2c3e50;
            font-size: 14px;
        }

        .menu-toggle {
            display: none;
            background: none;
            border: none;
            color: #2c3e50;
            font-size: 24px;
            cursor: pointer;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }

        .content-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
        }

        .section-title {
            font-size: 28px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .section-title i {
            color: #d4a574;
            font-size: 32px;
        }

        .btn-group {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .btn-action {
            background: linear-gradient(135deg, #d4a574 0%, #c99560 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-action:hover {
            background: linear-gradient(135deg, #c99560 0%, #b8854f 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        .btn-action:active {
            transform: translateY(0);
        }

        .btn-action-secondary {
            background: #f0f0f0;
            color: #333;
            border: 1px solid #e0e0e0;
        }

        .btn-action-secondary:hover {
            background: #e0e0e0;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
            border-radius: 4px;
        }

        .btn-small.edit {
            background: #3498db;
            color: white;
        }

        .btn-small.edit:hover {
            background: #2980b9;
        }

        .btn-small.delete {
            background: #e74c3c;
            color: white;
        }

        .btn-small.delete:hover {
            background: #c0392b;
        }

        /* Tabs */
        .tabs-container {
            display: flex;
            gap: 10px;
            border-bottom: 2px solid #e0e0e0;
            margin-bottom: 30px;
        }

        .tab-btn {
            padding: 12px 25px;
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            position: relative;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
            margin-bottom: -2px;
        }

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

        .tab-btn.active {
            color: #d4a574;
            border-bottom-color: #d4a574;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* Filter Accordion */
        .filter-item {
            background: #f9f9f9;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            margin-bottom: 15px;
            overflow: hidden;
        }

        .filter-header {
            padding: 20px;
            background: #f5f5f5;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }

        .filter-header:hover {
            background: #efefef;
        }

        .filter-header.active {
            background: linear-gradient(135deg, #d4a574 0%, #c99560 100%);
            color: white;
        }

        .filter-header-content {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .filter-header-title {
            font-weight: 600;
            font-size: 16px;
        }

        .filter-header-actions {
            display: flex;
            gap: 10px;
        }

        .filter-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .filter-content.active {
            max-height: none;
            overflow: visible;
        }

        .filter-body {
            padding: 20px;
            background: white;
            max-height: 70vh;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: #d4a574 #f5f5f5;
        }

        .filter-body::-webkit-scrollbar {
            width: 8px;
        }

        .filter-body::-webkit-scrollbar-track {
            background: #f5f5f5;
            border-radius: 4px;
        }

        .filter-body::-webkit-scrollbar-thumb {
            background: #d4a574;
            border-radius: 4px;
        }

        .filter-body::-webkit-scrollbar-thumb:hover {
            background: #c99560;
        }

        /* Subcategories Grid */
        .subcategories-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 25px;
        }

        .subcategory-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            transition: all 0.3s ease;
        }

        .subcategory-card:hover {
            border-color: #d4a574;
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.1);
        }

        .subcategory-name {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .subcategory-actions {
            display: flex;
            gap: 8px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            overflow-y: auto;
            padding: 20px;
        }

        .modal-content {
            background: white;
            padding: 40px;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            position: relative;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            margin: 0 auto;
        }

        .modal-content h2 {
            font-size: 24px;
            color: #2c3e50;
            margin-bottom: 25px;
        }

        .close-modal {
            position: absolute;
            right: 20px;
            top: 20px;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
        }

        .close-modal:hover {
            color: #333;
        }

        /* Forms */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
            transition: border-color 0.3s ease;
            width: 100%;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .image-upload-wrapper {
            position: relative;
            border: 2px dashed #d4a574;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fafafa;
        }

        .image-upload-wrapper:hover {
            border-color: #8b6f47;
            background: #f5f5f5;
        }

        .image-upload-wrapper input[type="file"] {
            display: none;
        }

        .image-preview-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;
            padding: 15px 0 0 0;
        }

        .btn-remove-image {
            padding: 8px 16px;
            background: #c0392b;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-remove-image:hover {
            background: #a93226;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            margin-top: 25px;
            padding-top: 25px;
            border-top: 1px solid #e0e0e0;
        }

        .form-actions button {
            flex: 1;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-actions .btn-action {
            margin: 0;
        }

        .form-actions .btn-action-secondary {
            margin: 0;
            flex: 1;
        }

        /* Menu Items Grid */
        .menu-items-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .menu-item-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .menu-item-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        .menu-item-image {
            width: 100%;
            height: 200px;
            background: #f5f5f5;
            overflow: hidden;
        }

        .menu-item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .menu-item-no-image {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 14px;
        }

        .menu-item-body {
            padding: 15px;
        }

        .menu-item-name {
            font-weight: 600;
            font-size: 16px;
            color: #2c3e50;
            margin-bottom: 8px;
        }

        .menu-item-description {
            font-size: 13px;
            color: #666;
            margin-bottom: 12px;
            line-height: 1.4;
            max-height: 50px;
            overflow: hidden;
        }

        .menu-item-price {
            font-size: 18px;
            font-weight: 700;
            color: #d4a574;
            margin-bottom: 12px;
        }

        .menu-item-actions {
            display: flex;
            gap: 8px;
        }

        .overlay {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.3);
            z-index: 900;
        }

        .overlay.active {
            display: block;
        }

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

        /* Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                width: 250px;
            }

            .topbar {
                left: 250px;
            }

            .main-content {
                margin-left: 250px;
            }

            .menu-items-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            }
        }

        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                width: 280px;
                height: 100vh;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 1000;
            }

            .topbar {
                left: 0;
            }

            .main-content {
                margin-left: 0;
            }

            .menu-toggle {
                display: block;
            }

            .menu-items-grid {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            }

            .modal-content {
                padding: 30px;
            }

            .form-actions {
                flex-direction: column;
            }

            .form-actions button {
                width: 100%;
            }
        }

        @media (max-width: 576px) {
            .topbar-title {
                font-size: 18px;
            }

            .main-content {
                padding: 15px;
            }

            .content-section {
                padding: 20px;
            }

            .btn-group {
                flex-direction: column;
            }

            .btn-action {
                width: 100%;
                justify-content: center;
            }

            .menu-items-grid {
                grid-template-columns: 1fr;
            }

            .modal-content {
                padding: 20px;
                width: 95%;
            }

            .tabs-container {
                flex-wrap: wrap;
            }

            .tab-btn {
                padding: 10px 15px;
                font-size: 12px;
            }
        }
    </style>
</head>

<body>
    <!-- Overlay for mobile menu -->
    <div id="menuOverlay" class="overlay"></div>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-crown sidebar-logo"></i>
            <h2>Admin Portal</h2>
            <p>Granny Restaurant</p>
            <div class="admin-name" id="sidebarAdminName">Admin</div>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span><span class="notification-badge hidden" data-type="bookings">0</span></a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> <span>Orders</span><span class="notification-badge hidden" data-type="orders">0</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span><span class="notification-badge hidden" data-type="contacts">0</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span><span class="notification-badge hidden" data-type="feedback">0</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-image"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php" class="active"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </div>

    <!-- Top Header -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 20px;">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Menu Management</div>
        </div>

        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div class="user-info">
                    <p>Welcome back</p>
                    <strong id="topbarUserName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="content-section">
            <div class="section-title">
                <i class="fas fa-utensils"></i>
                Menu Management
            </div>
            <p style="color: #999; margin-bottom: 20px;">Manage menu filters, categories, and items</p>

            <!-- Tabs -->
            <div class="tabs-container">
                <button class="tab-btn active" data-tab="filters-tab">
                    <i class="fas fa-list"></i> Filters & Items
                </button>
                <button class="tab-btn" data-tab="items-tab">
                    <i class="fas fa-pizza-slice"></i> All Menu Items
                </button>
            </div>

            <!-- Filters & Items Tab -->
            <div id="filters-tab" class="tab-content active">
                <div class="btn-group">
                    <button class="btn-action" id="addFilterBtn">
                        <i class="fas fa-plus"></i> Add Filter
                    </button>
                </div>

                <div id="filtersContainer" style="margin-bottom: 30px;">
                    <p style="text-align: center; color: #999; padding: 40px;">Loading filters...</p>
                </div>
            </div>

            <!-- All Menu Items Tab -->
            <div id="items-tab" class="tab-content">
                <div class="btn-group">
                    <button class="btn-action" id="addItemBtn">
                        <i class="fas fa-plus"></i> Add Menu Item
                    </button>
                </div>

                <div id="allItemsContainer" class="menu-items-grid">
                    <p style="text-align: center; color: #999; padding: 40px; grid-column: 1/-1;">Loading menu items...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Filter Modal -->
    <div id="filterModal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="close-modal" id="closeFilterModal">&times;</span>
            <h2 id="filterModalTitle">Add New Filter</h2>

            <form id="filterForm">
                <input type="hidden" id="filterId">

                <div class="form-group">
                    <label for="filterName">Filter Name *</label>
                    <input type="text" id="filterName" placeholder="e.g., Breakfast, Lunch, Dinner" required>
                </div>

                <div class="form-group">
                    <label for="filterDescription">Description</label>
                    <textarea id="filterDescription" placeholder="Filter description" rows="3"></textarea>
                </div>

                <h4 style="margin-top: 30px; margin-bottom: 15px; color: #2c3e50;">Default Subcategories</h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin-bottom: 20px;">
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 0;">
                        <input type="checkbox" class="subcategory-check" value="Vegetarian"> Vegetarian
                    </label>
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 0;">
                        <input type="checkbox" class="subcategory-check" value="Non-Vegetarian"> Non-Vegetarian
                    </label>
                    <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 0;">
                        <input type="checkbox" class="subcategory-check" value="Egg"> Egg
                    </label>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitFilterBtn">Add Filter</button>
                    <button type="button" class="btn-action-secondary" id="cancelFilterBtn">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Menu Item Modal -->
    <div id="itemModal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="close-modal" id="closeItemModal">&times;</span>
            <h2 id="itemModalTitle">Add New Menu Item</h2>

            <form id="itemForm">
                <input type="hidden" id="itemId">

                <div class="form-group">
                    <label for="itemFilter">Filter *</label>
                    <select id="itemFilter" required>
                        <option value="">Select a filter</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="itemSubcategory">Subcategory *</label>
                    <select id="itemSubcategory" required>
                        <option value="">Select a subcategory</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="itemName">Item Name *</label>
                    <input type="text" id="itemName" placeholder="e.g., Paneer Tikka" required>
                </div>

                <div class="form-group">
                    <label for="itemDescription">Description</label>
                    <textarea id="itemDescription" placeholder="Item description" rows="3"></textarea>
                </div>

                <div class="form-group">
                    <label for="itemPrice">Price *</label>
                    <input type="number" id="itemPrice" placeholder="e.g., 299.99" step="0.01" min="0" required>
                </div>

                <div class="form-group">
                    <label for="itemImage">Item Image</label>
                    <div class="image-upload-wrapper" id="imageUploadWrapper">
                        <i class="fas fa-cloud-upload-alt" style="font-size: 32px; color: #d4a574; margin-bottom: 10px;"></i>
                        <p>Click to upload image</p>
                        <input type="file" id="itemImage" accept="image/*">
                        <div class="image-preview-container" id="imagePreviewContainer" style="display: none;">
                            <img id="imagePreview" src="" alt="Preview" style="max-width: 300px; max-height: 200px; border-radius: 8px;">
                            <button type="button" class="btn-remove-image" id="removeImageBtn">Remove Image</button>
                        </div>
                        <input type="hidden" id="itemImagePath">
                    </div>
                </div>

                <div class="form-group">
                    <label for="itemAvailable">
                        <input type="checkbox" id="itemAvailable" checked> Available
                    </label>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitItemBtn">Add Item</button>
                    <button type="button" class="btn-action-secondary" id="cancelItemBtn">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

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

    <!-- Menu Management Script -->
    <script>
        let allFilters = [];
        let allItems = [];
        let allMenuData = [];

        document.addEventListener('DOMContentLoaded', function() {
            // Check admin authentication
            const adminUser = localStorage.getItem('admin_user');
            if (!adminUser) {
                window.location.href = 'login.php';
                return;
            }

            const admin = JSON.parse(adminUser);
            document.getElementById('sidebarAdminName').textContent = admin.name;
            document.getElementById('topbarUserName').textContent = admin.name;
            document.getElementById('userInitial').textContent = admin.name.charAt(0).toUpperCase();

            // Load initial data
            loadFilters();
            loadAllItems();
            loadMenuData();

            // Mobile menu toggle
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('menuOverlay');

            if (menuToggle && sidebar && overlay) {
                menuToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    sidebar.classList.toggle('active');
                    overlay.classList.toggle('active');
                });

                overlay.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    sidebar.classList.remove('active');
                    overlay.classList.remove('active');
                });

                document.addEventListener('click', function(e) {
                    if (sidebar.classList.contains('active') && 
                        !sidebar.contains(e.target) && 
                        !menuToggle.contains(e.target)) {
                        sidebar.classList.remove('active');
                        overlay.classList.remove('active');
                    }
                });
            }

            // Tab switching
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const tabId = this.getAttribute('data-tab');
                    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    document.getElementById(tabId).classList.add('active');
                });
            });

            // Logout
            document.getElementById('logoutBtn').addEventListener('click', function() {
                Swal.fire({
                    icon: 'warning',
                    title: 'Confirm Logout',
                    text: 'Are you sure you want to logout?',
                    showCancelButton: true,
                    confirmButtonColor: '#d4a574',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Yes, Logout',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        localStorage.removeItem('admin_user');
                        localStorage.removeItem('admin_token');
                        
                        fetch('../backend/admin_logout.php', {
                            method: 'POST'
                        }).then(() => {
                            window.location.href = 'login.php';
                        });
                    }
                });
            });

            setupFilterModal();
            setupItemModal();
        });

        // ===== FILTERS =====
        async function loadFilters() {
            try {
                const response = await fetch('../backend/menu_api.php?action=get_filters');
                const result = await response.json();

                if (result.success) {
                    allFilters = result.data;
                    renderFilters();
                    populateFilterSelect();
                }
            } catch (error) {
                console.error('Error loading filters:', error);
            }
        }

        function renderFilters() {
            const container = document.getElementById('filtersContainer');
            
            if (allFilters.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #999; padding: 40px;">No filters created yet</p>';
                return;
            }

            container.innerHTML = allFilters.map(filter => `
                <div class="filter-item">
                    <div class="filter-header" onclick="toggleFilterContent(this)">
                        <div class="filter-header-content">
                            <i class="fas fa-chevron-right"></i>
                            <div class="filter-header-title">${filter.filter_name}</div>
                        </div>
                        <div class="filter-header-actions">
                            <button class="btn-small edit" onclick="editFilter(${filter.id}, event)"><i class="fas fa-edit"></i> Edit</button>
                            <button class="btn-small delete" onclick="deleteFilter(${filter.id}, event)"><i class="fas fa-trash"></i> Delete</button>
                        </div>
                    </div>
                    <div class="filter-content">
                        <div class="filter-body">
                            <div style="margin-bottom: 25px;">
                                <h5 style="margin-bottom: 15px; color: #2c3e50;">Subcategories</h5>
                                <div id="subcategories-${filter.id}" class="subcategories-grid"></div>
                                <button class="btn-action" onclick="showAddSubcategoryForm(${filter.id})" style="margin-top: 15px;">
                                    <i class="fas fa-plus"></i> Add Subcategory
                                </button>
                            </div>
                            <div>
                                <h5 style="margin-bottom: 15px; color: #2c3e50;">Menu Items</h5>
                                <div id="items-${filter.id}" class="menu-items-grid"></div>
                                <button class="btn-action" onclick="showAddItemForm(${filter.id})" style="margin-top: 15px;">
                                    <i class="fas fa-plus"></i> Add Item
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            // Load subcategories and items for each filter
            allFilters.forEach(filter => {
                loadSubcategoriesForFilter(filter.id);
            });
        }

        function toggleFilterContent(header) {
            header.classList.toggle('active');
            header.nextElementSibling.classList.toggle('active');
        }

        async function loadSubcategoriesForFilter(filterId) {
            try {
                const response = await fetch(`../backend/menu_api.php?action=get_subcategories&filter_id=${filterId}`);
                const result = await response.json();

                if (result.success) {
                    renderSubcategories(filterId, result.data);
                    loadItemsForSubcategories(filterId, result.data);
                }
            } catch (error) {
                console.error('Error loading subcategories:', error);
            }
        }

        function renderSubcategories(filterId, subcategories) {
            const container = document.getElementById(`subcategories-${filterId}`);
            
            if (subcategories.length === 0) {
                container.innerHTML = '<p style="color: #999; font-size: 13px;">No subcategories yet</p>';
                return;
            }

            container.innerHTML = subcategories.map(sub => `
                <div class="subcategory-card">
                    <div class="subcategory-name">${sub.subcategory_name}</div>
                    <div class="subcategory-actions">
                        <button class="btn-small edit" onclick="editSubcategory(${sub.id}, event)"><i class="fas fa-edit"></i></button>
                        <button class="btn-small delete" onclick="deleteSubcategory(${sub.id}, event)"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
            `).join('');
        }

        function loadItemsForSubcategories(filterId, subcategories) {
            subcategories.forEach(sub => {
                loadItemsForSubcategory(filterId, sub.id);
            });
        }

        async function loadItemsForSubcategory(filterId, subcategoryId) {
            try {
                const response = await fetch(`../backend/menu_api.php?action=get_items&subcategory_id=${subcategoryId}`);
                const result = await response.json();

                if (result.success) {
                    renderItemsForSubcategory(filterId, subcategoryId, result.data);
                }
            } catch (error) {
                console.error('Error loading items:', error);
            }
        }

        function renderItemsForSubcategory(filterId, subcategoryId, items) {
            const container = document.getElementById(`items-${filterId}`);
            
            if (!container) return;

            let existingHTML = container.innerHTML;
            
            items.forEach(item => {
                existingHTML += `
                    <div class="menu-item-card">
                        <div class="menu-item-image">
                            ${item.image_path && item.image_path !== '0' ? `<img src="../${item.image_path}" alt="${item.item_name}">` : '<div class="menu-item-no-image"><i class="fas fa-image"></i> No Image</div>'}
                        </div>
                        <div class="menu-item-body">
                            <div class="menu-item-name">${item.item_name}</div>
                            <div class="menu-item-description">${item.description || 'No description'}</div>
                            <div class="menu-item-price">₹${item.price}</div>
                            <div class="menu-item-actions">
                                <button class="btn-small edit" onclick="editItem(${item.id}, event)"><i class="fas fa-edit"></i> Edit</button>
                                <button class="btn-small delete" onclick="deleteItem(${item.id}, event)"><i class="fas fa-trash"></i> Delete</button>
                            </div>
                        </div>
                    </div>
                `;
            });

            container.innerHTML = existingHTML;
        }

        async function loadAllItems() {
            try {
                const filters = await fetch('../backend/menu_api.php?action=get_filters').then(r => r.json());
                
                if (!filters.success) return;

                let allItems = [];
                
                for (let filter of filters.data) {
                    const subResponse = await fetch(`../backend/menu_api.php?action=get_subcategories&filter_id=${filter.id}`).then(r => r.json());
                    
                    if (subResponse.success) {
                        for (let sub of subResponse.data) {
                            const itemsResponse = await fetch(`../backend/menu_api.php?action=get_items&subcategory_id=${sub.id}`).then(r => r.json());
                            if (itemsResponse.success) {
                                allItems = allItems.concat(itemsResponse.data);
                            }
                        }
                    }
                }

                renderAllItems(allItems);
            } catch (error) {
                console.error('Error loading all items:', error);
            }
        }

        function renderAllItems(items) {
            const container = document.getElementById('allItemsContainer');
            
            if (items.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #999; padding: 40px; grid-column: 1/-1;">No menu items created yet</p>';
                return;
            }

            container.innerHTML = items.map(item => `
                <div class="menu-item-card">
                    <div class="menu-item-image">
                        ${item.image_path && item.image_path !== '0' ? `<img src="../${item.image_path}" alt="${item.item_name}">` : '<div class="menu-item-no-image"><i class="fas fa-image"></i> No Image</div>'}
                    </div>
                    <div class="menu-item-body">
                        <div class="menu-item-name">${item.item_name}</div>
                        <div class="menu-item-description">${item.description || 'No description'}</div>
                        <div class="menu-item-price">₹${item.price}</div>
                        <div class="menu-item-actions">
                            <button class="btn-small edit" onclick="editItem(${item.id}, event)"><i class="fas fa-edit"></i> Edit</button>
                            <button class="btn-small delete" onclick="deleteItem(${item.id}, event)"><i class="fas fa-trash"></i> Delete</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function populateFilterSelect() {
            const select = document.getElementById('itemFilter');
            select.innerHTML = '<option value="">Select a filter</option>' + 
                allFilters.map(f => `<option value="${f.id}">${f.filter_name}</option>`).join('');
        }

        async function loadMenuData() {
            try {
                // Build hierarchical menu data including ALL items (not just available ones)
                allMenuData = [];
                const filters = await fetch('../backend/menu_api.php?action=get_filters').then(r => r.json());
                
                if (!filters.success) {
                    console.error('Failed to load filters for menu data');
                    return;
                }

                for (let filter of filters.data) {
                    let filterObj = {
                        filter_id: filter.id,
                        filter_name: filter.filter_name,
                        subcategories: []
                    };

                    const subResponse = await fetch(`../backend/menu_api.php?action=get_subcategories&filter_id=${filter.id}`).then(r => r.json());
                    
                    if (subResponse.success) {
                        for (let sub of subResponse.data) {
                            let subcategoryObj = {
                                subcategory_id: sub.id,
                                subcategory_name: sub.subcategory_name,
                                items: []
                            };

                            const itemsResponse = await fetch(`../backend/menu_api.php?action=get_items&subcategory_id=${sub.id}`).then(r => r.json());
                            if (itemsResponse.success) {
                                subcategoryObj.items = itemsResponse.data.map(item => ({
                                    item_id: item.id,
                                    item_name: item.item_name,
                                    description: item.description,
                                    price: item.price,
                                    image_path: item.image_path,
                                    is_available: item.is_available
                                }));
                            }

                            filterObj.subcategories.push(subcategoryObj);
                        }
                    }

                    allMenuData.push(filterObj);
                }
                
                console.log('Hierarchical menu data loaded (all items):', allMenuData);
            } catch (error) {
                console.error('Error loading menu data:', error);
            }
        }

        function setupFilterModal() {
            const filterModal = document.getElementById('filterModal');
            const addFilterBtn = document.getElementById('addFilterBtn');
            const closeFilterModal = document.getElementById('closeFilterModal');
            const filterForm = document.getElementById('filterForm');
            const cancelFilterBtn = document.getElementById('cancelFilterBtn');

            addFilterBtn.addEventListener('click', () => {
                document.getElementById('filterId').value = '';
                filterForm.reset();
                document.querySelectorAll('.subcategory-check').forEach(c => c.checked = true);
                document.getElementById('filterModalTitle').textContent = 'Add New Filter';
                document.getElementById('submitFilterBtn').textContent = 'Add Filter';
                filterModal.style.display = 'block';
            });

            closeFilterModal.addEventListener('click', () => {
                filterModal.style.display = 'none';
            });

            cancelFilterBtn.addEventListener('click', () => {
                filterModal.style.display = 'none';
            });

            filterModal.addEventListener('click', (e) => {
                if (e.target === filterModal) {
                    filterModal.style.display = 'none';
                }
            });

            filterForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const filterId = document.getElementById('filterId').value;
                const filterName = document.getElementById('filterName').value.trim();
                const filterDescription = document.getElementById('filterDescription').value.trim();

                if (!filterName) {
                    Swal.fire('Error', 'Filter name is required', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('action', filterId ? 'update_filter' : 'create_filter');
                if (filterId) formData.append('id', filterId);
                formData.append('filter_name', filterName);
                formData.append('description', filterDescription);
                formData.append('display_order', 0);

                try {
                    const response = await fetch('../backend/menu_api.php', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();

                    if (result.success) {
                        const newFilterId = result.id || filterId;
                        
                        // Create subcategories
                        const selectedSubcategories = Array.from(document.querySelectorAll('.subcategory-check:checked')).map(c => c.value);
                        
                        for (let i = 0; i < selectedSubcategories.length; i++) {
                            const subData = new FormData();
                            subData.append('action', 'create_subcategory');
                            subData.append('filter_id', newFilterId);
                            subData.append('subcategory_name', selectedSubcategories[i]);
                            subData.append('display_order', i);

                            await fetch('../backend/menu_api.php', {
                                method: 'POST',
                                body: subData
                            });
                        }

                        Swal.fire('Success', filterId ? 'Filter updated' : 'Filter created', 'success');
                        filterModal.style.display = 'none';
                        filterForm.reset();
                        loadFilters();
                    } else {
                        Swal.fire('Error', result.message, 'error');
                    }
                } catch (error) {
                    Swal.fire('Error', 'Failed to save filter', 'error');
                    console.error(error);
                }
            });
        }

        function editFilter(id, event) {
            if (event) event.stopPropagation();
            const filter = allFilters.find(f => parseInt(f.id) === parseInt(id));
            if (!filter) {
                console.error('Filter not found with id:', id, 'Available filters:', allFilters);
                Swal.fire('Error', 'Filter not found', 'error');
                return;
            }

            document.getElementById('filterId').value = id;
            document.getElementById('filterName').value = filter.filter_name;
            document.getElementById('filterDescription').value = filter.description || '';
            document.getElementById('filterModalTitle').textContent = 'Edit Filter';
            document.getElementById('submitFilterBtn').textContent = 'Update Filter';
            
            // Ensure modal is visible
            const modal = document.getElementById('filterModal');
            modal.style.display = 'block';
            console.log('Edit filter modal opened');
        }

        async function deleteFilter(id, event) {
            event.stopPropagation();
            Swal.fire({
                icon: 'warning',
                title: 'Delete Filter',
                text: 'This will also delete all subcategories and items under this filter',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'delete_filter');
                        formData.append('id', id);

                        const response = await fetch('../backend/menu_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();

                        if (result.success) {
                            Swal.fire('Deleted', 'Filter deleted successfully', 'success');
                            loadFilters();
                        }
                    } catch (error) {
                        Swal.fire('Error', 'Failed to delete filter', 'error');
                    }
                }
            });
        }

        function showAddSubcategoryForm(filterId) {
            Swal.fire({
                title: 'Add Subcategory',
                input: 'text',
                inputPlaceholder: 'e.g., Vegetarian, Non-Vegetarian, Egg',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Add',
                cancelButtonText: 'Cancel'
            }).then(async (result) => {
                if (result.isConfirmed && result.value.trim()) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'create_subcategory');
                        formData.append('filter_id', filterId);
                        formData.append('subcategory_name', result.value.trim());
                        formData.append('display_order', 0);

                        const response = await fetch('../backend/menu_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const response_result = await response.json();

                        if (response_result.success) {
                            Swal.fire('Success', 'Subcategory added', 'success');
                            loadSubcategoriesForFilter(filterId);
                        }
                    } catch (error) {
                        Swal.fire('Error', 'Failed to add subcategory', 'error');
                    }
                }
            });
        }

        function editSubcategory(id, event) {
            event.stopPropagation();
            // Implement edit subcategory
        }

        async function deleteSubcategory(id, event) {
            event.stopPropagation();
            Swal.fire({
                icon: 'warning',
                title: 'Delete Subcategory',
                text: 'All items under this subcategory will be deleted',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                confirmButtonText: 'Yes, Delete'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'delete_subcategory');
                        formData.append('id', id);

                        const response = await fetch('../backend/menu_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();

                        if (result.success) {
                            Swal.fire('Deleted', 'Subcategory deleted', 'success');
                            loadFilters();
                        }
                    } catch (error) {
                        Swal.fire('Error', 'Failed to delete subcategory', 'error');
                    }
                }
            });
        }

        // ===== MENU ITEMS =====
        function setupItemModal() {
            const itemModal = document.getElementById('itemModal');
            const addItemBtn = document.getElementById('addItemBtn');
            const closeItemModal = document.getElementById('closeItemModal');
            const itemForm = document.getElementById('itemForm');
            const cancelItemBtn = document.getElementById('cancelItemBtn');
            const itemFilter = document.getElementById('itemFilter');
            const itemSubcategory = document.getElementById('itemSubcategory');
            const itemImage = document.getElementById('itemImage');
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewContainer = document.getElementById('imagePreviewContainer');
            const removeImageBtn = document.getElementById('removeImageBtn');
            const imageUploadWrapper = document.getElementById('imageUploadWrapper');

            addItemBtn.addEventListener('click', () => {
                document.getElementById('itemId').value = '';
                itemForm.reset();
                document.getElementById('itemModalTitle').textContent = 'Add New Menu Item';
                document.getElementById('submitItemBtn').textContent = 'Add Item';
                imagePreviewContainer.style.display = 'none';
                itemModal.style.display = 'block';
            });

            closeItemModal.addEventListener('click', () => {
                itemModal.style.display = 'none';
            });

            cancelItemBtn.addEventListener('click', () => {
                itemModal.style.display = 'none';
            });

            itemModal.addEventListener('click', (e) => {
                if (e.target === itemModal) {
                    itemModal.style.display = 'none';
                }
            });

            imageUploadWrapper.addEventListener('click', () => {
                itemImage.click();
            });

            itemImage.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        imagePreview.src = event.target.result;
                        imagePreviewContainer.style.display = 'flex';
                    };
                    reader.readAsDataURL(file);
                }
            });

            removeImageBtn.addEventListener('click', (e) => {
                e.preventDefault();
                itemImage.value = '';
                imagePreviewContainer.style.display = 'none';
            });

            itemFilter.addEventListener('change', async () => {
                const filterId = itemFilter.value;
                itemSubcategory.innerHTML = '<option value="">Select a subcategory</option>';

                if (!filterId) return;

                try {
                    const response = await fetch(`../backend/menu_api.php?action=get_subcategories&filter_id=${filterId}`);
                    const result = await response.json();

                    if (result.success) {
                        itemSubcategory.innerHTML += result.data.map(sub => 
                            `<option value="${sub.id}">${sub.subcategory_name}</option>`
                        ).join('');
                    }
                } catch (error) {
                    console.error('Error loading subcategories:', error);
                }
            });

            itemForm.addEventListener('submit', async (e) => {
                e.preventDefault();
                const itemId = document.getElementById('itemId').value;
                const subcategoryId = document.getElementById('itemSubcategory').value;
                const itemName = document.getElementById('itemName').value.trim();
                const itemDescription = document.getElementById('itemDescription').value.trim();
                const itemPrice = document.getElementById('itemPrice').value;
                const isAvailable = document.getElementById('itemAvailable').checked ? 1 : 0;

                if (!subcategoryId || !itemName || !itemPrice) {
                    Swal.fire('Error', 'Please fill all required fields', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('action', itemId ? 'update_item' : 'create_item');
                if (itemId) formData.append('id', itemId);
                formData.append('subcategory_id', subcategoryId);
                formData.append('item_name', itemName);
                formData.append('description', itemDescription);
                formData.append('price', itemPrice);
                formData.append('is_available', isAvailable);
                formData.append('display_order', 0);

                if (itemImage.files[0]) {
                    formData.append('image', itemImage.files[0]);
                }

                try {
                    const response = await fetch('../backend/menu_api.php', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();

                    if (result.success) {
                        Swal.fire('Success', itemId ? 'Item updated' : 'Item created', 'success');
                        itemModal.style.display = 'none';
                        itemForm.reset();
                        loadFilters();
                        loadAllItems();
                    } else {
                        Swal.fire('Error', result.message, 'error');
                    }
                } catch (error) {
                    Swal.fire('Error', 'Failed to save item', 'error');
                    console.error(error);
                }
            });
        }

        function showAddItemForm(filterId) {
            document.getElementById('itemFilter').value = filterId;
            document.getElementById('itemFilter').dispatchEvent(new Event('change'));
            document.getElementById('itemModal').style.display = 'block';
        }

        async function editItem(id, event) {
            event.stopPropagation();
            
            // Find the item from allMenuData
            let item = null;
            let itemSubcategory = null;
            let itemFilter = null;
            
            for (let filter of allMenuData) {
                for (let subcategory of filter.subcategories) {
                    const foundItem = subcategory.items.find(i => parseInt(i.item_id) === parseInt(id));
                    if (foundItem) {
                        item = foundItem;
                        itemSubcategory = subcategory;
                        itemFilter = filter;
                        break;
                    }
                }
                if (item) break;
            }
            
            if (!item || !itemSubcategory || !itemFilter) {
                console.error('Item not found with id:', id, 'Available data:', allMenuData);
                Swal.fire('Error', 'Item not found', 'error');
                return;
            }

            // Fill the form with existing data
            document.getElementById('itemId').value = id;
            document.getElementById('itemFilter').value = itemFilter.filter_id;
            document.getElementById('itemName').value = item.item_name;
            document.getElementById('itemDescription').value = item.description || '';
            document.getElementById('itemPrice').value = item.price;
            document.getElementById('itemAvailable').checked = item.is_available == 1;
            document.getElementById('itemImagePath').value = item.image_path || '';
            
            // Load subcategories for this filter
            try {
                const response = await fetch(`../backend/menu_api.php?action=get_subcategories&filter_id=${itemFilter.filter_id}`);
                const result = await response.json();

                if (result.success) {
                    const itemSubcategorySelect = document.getElementById('itemSubcategory');
                    itemSubcategorySelect.innerHTML = '<option value="">Select a subcategory</option>';
                    itemSubcategorySelect.innerHTML += result.data.map(sub => 
                        `<option value="${sub.id}">${sub.subcategory_name}</option>`
                    ).join('');
                    
                    // Now set the subcategory value
                    itemSubcategorySelect.value = itemSubcategory.subcategory_id;
                }
            } catch (error) {
                console.error('Error loading subcategories:', error);
            }
            
            // Show image preview if exists
            if (item.image_path && item.image_path !== '0') {
                const previewContainer = document.getElementById('imagePreviewContainer');
                const preview = document.getElementById('imagePreview');
                preview.src = '../' + item.image_path;
                previewContainer.style.display = 'block';
            } else {
                document.getElementById('imagePreviewContainer').style.display = 'none';
            }
            
            // Update modal title and button
            document.getElementById('itemModalTitle').textContent = 'Edit Menu Item';
            document.getElementById('submitItemBtn').textContent = 'Update Item';
            
            // Show modal
            const itemModal = document.getElementById('itemModal');
            itemModal.style.display = 'block';
            console.log('Edit item modal opened');
        }

        async function deleteItem(id, event) {
            event.stopPropagation();
            Swal.fire({
                icon: 'warning',
                title: 'Delete Item',
                text: 'Are you sure?',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                confirmButtonText: 'Yes, Delete'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'delete_item');
                        formData.append('id', id);

                        const response = await fetch('../backend/menu_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();

                        if (result.success) {
                            Swal.fire('Deleted', 'Item deleted successfully', 'success');
                            loadFilters();
                            loadAllItems();
                        }
                    } catch (error) {
                        Swal.fire('Error', 'Failed to delete item', 'error');
                    }
                }
            });
        }
    </script>
</body>

</html>
