<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
?>
<!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="Meal Types & Slots Management">
    <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>Meal Types & Slots Management</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-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

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

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

        .sidebar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            border-left-color: #d4a574;
        }

        .sidebar-menu a.active {
            background: rgba(212, 165, 116, 0.2);
            border-left-color: #d4a574;
            color: #d4a574;
        }

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

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

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

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
        }

        .btn-primary {
            background: #d4a574;
            color: white;
        }

        .btn-primary:hover {
            background: #c1944a;
        }

        .btn-secondary {
            background: #eceff1;
            color: #2c3e50;
        }

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

        .container-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            background: white;
            padding: 15px 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .tab-btn {
            padding: 10px 20px;
            border: none;
            background: #eceff1;
            color: #2c3e50;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .tab-btn.active {
            background: #d4a574;
            color: white;
        }

        .tab-content {
            display: none;
        }

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

        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }

        .meal-type-card {
            border-left: 4px solid #d4a574;
            padding: 15px;
            margin-bottom: 15px;
        }

        .meal-type-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .meal-type-info h3 {
            margin: 0;
            color: #2c3e50;
            font-size: 18px;
        }

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

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        .time-slots-container {
            background: #f9f9f9;
            border-radius: 4px;
            padding: 15px;
        }

        .slot-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e8e8e8;
        }

        .slot-item:last-child {
            border-bottom: none;
        }

        .slot-time {
            flex: 1;
        }

        .slot-time .time-range {
            font-weight: 600;
            color: #2c3e50;
        }

        .slot-time .time-name {
            font-size: 12px;
            color: #999;
        }

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

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .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 {
            font-size: 20px;
            margin: 0;
            color: #2c3e50;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #999;
        }

        .form-group {
            margin-bottom: 15px;
        }

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

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-family: 'Raleway', sans-serif;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .modal-footer {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 200px;
            }

            .topbar {
                left: 200px;
            }

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

            .header {
                flex-direction: column;
                align-items: flex-start;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h2>Granny Admin</h2>
            <p>Meal Management</p>
        </div>
        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
            <li><a href="tables.php"><i class="fas fa-table"></i> Restaurant Tables</a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> Online Booking Tables</a></li>
            <li><a href="meal_slots.php" class="active"><i class="fas fa-clock"></i> Meal Types & Slots</a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> Menu</a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar"></i> Bookings</a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> Orders</a></li>
            <li><a href="logout.html"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>

    <!-- Topbar -->
    <div class="topbar">
        <div class="topbar-title">Meal Types & Slots Management</div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="header">
            <h1><i class="fas fa-clock"></i> Meal Types & Slots</h1>
        </div>

        <!-- Tabs -->
        <div class="container-tabs">
            <button class="tab-btn active" onclick="switchTab('mealTypes')">Meal Types</button>
            <button class="tab-btn" onclick="switchTab('timeSlots')">Time Slots</button>
        </div>

        <!-- MEAL TYPES TAB -->
        <div id="mealTypes" class="tab-content active">
            <div class="card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0;">Manage Meal Types</h3>
                    <button class="btn btn-primary" onclick="openMealTypeModal()">
                        <i class="fas fa-plus"></i> Add Meal Type
                    </button>
                </div>
                <div id="mealTypesList"></div>
            </div>
        </div>

        <!-- TIME SLOTS TAB -->
        <div id="timeSlots" class="tab-content">
            <div class="card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0;">Manage Time Slots</h3>
                    <button class="btn btn-primary" onclick="openTimeSlotModal()">
                        <i class="fas fa-plus"></i> Add Time Slot
                    </button>
                </div>
                <div id="timeSlotsList"></div>
            </div>
        </div>
    </div>

    <!-- Meal Type Modal -->
    <div id="mealTypeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="mealTypeModalTitle">Add Meal Type</h2>
                <button class="modal-close" onclick="closeMealTypeModal()">&times;</button>
            </div>
            <form id="mealTypeForm">
                <input type="hidden" id="mealTypeId" value="">
                
                <div class="form-group">
                    <label for="mealTypeName">Meal Type Name *</label>
                    <input type="text" id="mealTypeName" required placeholder="e.g., Breakfast, Lunch, Dinner">
                </div>

                <div class="form-group">
                    <label for="mealTypeDescription">Description</label>
                    <textarea id="mealTypeDescription" placeholder="Brief description of this meal type"></textarea>
                </div>

                <div class="form-group">
                    <label for="mealTypeIcon">Icon Class (Font Awesome)</label>
                    <input type="text" id="mealTypeIcon" value="fas fa-utensils" placeholder="e.g., fas fa-sun">
                </div>

                <div class="form-group">
                    <label for="mealTypeColor">Color Code</label>
                    <input type="color" id="mealTypeColor" value="#d4a574">
                </div>

                <div class="form-group">
                    <label for="mealTypeStatus">Status</label>
                    <select id="mealTypeStatus">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="mealTypeOrder">Display Order</label>
                    <input type="number" id="mealTypeOrder" value="0" min="0">
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeMealTypeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Time Slot Modal -->
    <div id="timeSlotModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="timeSlotModalTitle">Add Time Slot</h2>
                <button class="modal-close" onclick="closeTimeSlotModal()">&times;</button>
            </div>
            <form id="timeSlotForm">
                <input type="hidden" id="timeSlotId" value="">
                
                <div class="form-group">
                    <label for="timeSlotMealType">Meal Type *</label>
                    <select id="timeSlotMealType" required></select>
                </div>

                <div class="form-group">
                    <label for="timeSlotName">Slot Name (Optional)</label>
                    <input type="text" id="timeSlotName" placeholder="e.g., Breakfast Special">
                </div>

                <div class="form-group">
                    <label for="timeSlotStart">Start Time *</label>
                    <input type="time" id="timeSlotStart" required>
                </div>

                <div class="form-group">
                    <label for="timeSlotEnd">End Time *</label>
                    <input type="time" id="timeSlotEnd" required>
                </div>

                <div class="form-group">
                    <label for="timeSlotDescription">Description</label>
                    <textarea id="timeSlotDescription" placeholder="Brief description of this time slot"></textarea>
                </div>

                <div class="form-group">
                    <label for="timeSlotCapacity">Max Capacity</label>
                    <input type="number" id="timeSlotCapacity" value="100" min="1">
                </div>

                <div class="form-group">
                    <label for="timeSlotStatus">Status</label>
                    <select id="timeSlotStatus">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="timeSlotOrder">Display Order</label>
                    <input type="number" id="timeSlotOrder" value="0" min="0">
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeTimeSlotModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>

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

    <script>
        // Switch tabs
        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.getElementById(tabName).classList.add('active');
            event.target.classList.add('active');

            if (tabName === 'mealTypes') {
                loadMealTypes();
            } else {
                loadTimeSlots();
            }
        }

        // Modal functions
        function openMealTypeModal() {
            document.getElementById('mealTypeId').value = '';
            document.getElementById('mealTypeForm').reset();
            document.getElementById('mealTypeModalTitle').textContent = 'Add Meal Type';
            document.getElementById('mealTypeModal').classList.add('show');
        }

        function closeMealTypeModal() {
            document.getElementById('mealTypeModal').classList.remove('show');
        }

        function openTimeSlotModal() {
            document.getElementById('timeSlotId').value = '';
            document.getElementById('timeSlotForm').reset();
            document.getElementById('timeSlotModalTitle').textContent = 'Add Time Slot';
            document.getElementById('timeSlotModal').classList.add('show');
            loadMealTypesForSelect();
        }

        function closeTimeSlotModal() {
            document.getElementById('timeSlotModal').classList.remove('show');
        }

        // Load meal types
        async function loadMealTypes() {
            try {
                const response = await fetch('../backend/meal_slots_api.php?action=get_meal_types');
                const data = await response.json();
                
                if (data.success) {
                    let html = '';
                    data.data.forEach(mealType => {
                        const statusClass = mealType.status === 'active' ? 'status-active' : 'status-inactive';
                        html += `
                            <div class="meal-type-card">
                                <div class="meal-type-header">
                                    <div class="meal-type-info">
                                        <h3><i class="${mealType.icon}"></i> ${mealType.name}</h3>
                                        <p style="margin: 5px 0 0 0; color: #999; font-size: 13px;">${mealType.description || 'No description'}</p>
                                    </div>
                                    <span class="status-badge ${statusClass}">${mealType.status.toUpperCase()}</span>
                                </div>
                                <div class="time-slots-container" id="slots-${mealType.id}">
                                    <div style="text-align: center; color: #999;">Loading slots...</div>
                                </div>
                                <div class="meal-type-actions" style="margin-top: 15px;">
                                    <button class="btn btn-secondary btn-sm" onclick="editMealType(${mealType.id})">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="btn btn-danger btn-sm" onclick="deleteMealType(${mealType.id})">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                    document.getElementById('mealTypesList').innerHTML = html;
                    
                    // Load slots for each meal type
                    data.data.forEach(mealType => {
                        loadSlotsForMealType(mealType.id);
                    });
                } else {
                    document.getElementById('mealTypesList').innerHTML = '<p style="text-align: center; color: #999;">No meal types found.</p>';
                }
            } catch (error) {
                console.error('Error loading meal types:', error);
            }
        }

        // Load slots for a specific meal type
        async function loadSlotsForMealType(mealTypeId) {
            try {
                const response = await fetch(`../backend/meal_slots_api.php?action=get_slots&meal_type_id=${mealTypeId}`);
                const data = await response.json();
                
                const container = document.getElementById(`slots-${mealTypeId}`);
                if (data.success && data.data.length > 0) {
                    let html = '';
                    data.data.forEach(slot => {
                        html += `
                            <div class="slot-item">
                                <div class="slot-time">
                                    <div class="time-range">${formatTime(slot.start_time)} - ${formatTime(slot.end_time)}</div>
                                    <div class="time-name">${slot.slot_name || 'No name'}</div>
                                </div>
                                <div class="slot-actions">
                                    <button class="btn btn-secondary btn-sm" onclick="editTimeSlot(${slot.id})">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm" onclick="deleteTimeSlot(${slot.id})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p style="text-align: center; color: #999; padding: 10px 0;">No time slots configured</p>';
                }
            } catch (error) {
                console.error('Error loading slots:', error);
            }
        }

        // Load time slots view
        async function loadTimeSlots() {
            try {
                const response = await fetch('../backend/meal_slots_api.php?action=get_all_slots');
                const data = await response.json();
                
                if (data.success && data.data.length > 0) {
                    let html = '';
                    data.data.forEach(slot => {
                        const statusClass = slot.status === 'active' ? 'status-active' : 'status-inactive';
                        html += `
                            <div class="card" style="margin-bottom: 15px;">
                                <div style="display: flex; justify-content: space-between; align-items: center;">
                                    <div>
                                        <h4 style="margin: 0 0 5px 0;">${slot.meal_type_name} - ${slot.slot_name || 'No name'}</h4>
                                        <p style="margin: 0; color: #999; font-size: 13px;">${formatTime(slot.start_time)} to ${formatTime(slot.end_time)}</p>
                                    </div>
                                    <div style="display: flex; gap: 10px; align-items: center;">
                                        <span class="status-badge ${statusClass}">${slot.status.toUpperCase()}</span>
                                        <button class="btn btn-secondary btn-sm" onclick="editTimeSlot(${slot.id})">
                                            <i class="fas fa-edit"></i> Edit
                                        </button>
                                        <button class="btn btn-danger btn-sm" onclick="deleteTimeSlot(${slot.id})">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    document.getElementById('timeSlotsList').innerHTML = html;
                } else {
                    document.getElementById('timeSlotsList').innerHTML = '<p style="text-align: center; color: #999;">No time slots found.</p>';
                }
            } catch (error) {
                console.error('Error loading time slots:', error);
            }
        }

        // Load meal types for select dropdown
        async function loadMealTypesForSelect() {
            try {
                const response = await fetch('../backend/meal_slots_api.php?action=get_meal_types');
                const data = await response.json();
                
                if (data.success) {
                    let html = '<option value="">-- Select Meal Type --</option>';
                    data.data.forEach(mealType => {
                        html += `<option value="${mealType.id}">${mealType.name}</option>`;
                    });
                    document.getElementById('timeSlotMealType').innerHTML = html;
                }
            } catch (error) {
                console.error('Error loading meal types:', error);
            }
        }

        // Meal Type Form Submit
        document.getElementById('mealTypeForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const id = document.getElementById('mealTypeId').value;
            const action = id ? 'update_meal_type' : 'create_meal_type';
            
            const formData = new FormData();
            formData.append('action', action);
            if (id) formData.append('id', id);
            formData.append('name', document.getElementById('mealTypeName').value);
            formData.append('description', document.getElementById('mealTypeDescription').value);
            formData.append('icon', document.getElementById('mealTypeIcon').value);
            formData.append('color_code', document.getElementById('mealTypeColor').value);
            formData.append('status', document.getElementById('mealTypeStatus').value);
            formData.append('display_order', document.getElementById('mealTypeOrder').value);
            
            try {
                const response = await fetch('../backend/meal_slots_api.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire('Success!', data.message, 'success');
                    closeMealTypeModal();
                    loadMealTypes();
                } else {
                    Swal.fire('Error!', data.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error!', 'Failed to save meal type', 'error');
            }
        });

        // Time Slot Form Submit
        document.getElementById('timeSlotForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const id = document.getElementById('timeSlotId').value;
            const action = id ? 'update_time_slot' : 'create_time_slot';
            
            const formData = new FormData();
            formData.append('action', action);
            if (id) formData.append('id', id);
            formData.append('meal_type_id', document.getElementById('timeSlotMealType').value);
            formData.append('slot_name', document.getElementById('timeSlotName').value);
            formData.append('start_time', document.getElementById('timeSlotStart').value);
            formData.append('end_time', document.getElementById('timeSlotEnd').value);
            formData.append('description', document.getElementById('timeSlotDescription').value);
            formData.append('max_capacity', document.getElementById('timeSlotCapacity').value);
            formData.append('status', document.getElementById('timeSlotStatus').value);
            formData.append('display_order', document.getElementById('timeSlotOrder').value);
            
            try {
                const response = await fetch('../backend/meal_slots_api.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire('Success!', data.message, 'success');
                    closeTimeSlotModal();
                    loadMealTypes();
                    loadTimeSlots();
                } else {
                    Swal.fire('Error!', data.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error!', 'Failed to save time slot', 'error');
            }
        });

        // Edit functions
        async function editMealType(id) {
            try {
                const response = await fetch(`../backend/meal_slots_api.php?action=get_meal_type&id=${id}`);
                const data = await response.json();
                
                if (data.success) {
                    const mealType = data.data;
                    document.getElementById('mealTypeId').value = mealType.id;
                    document.getElementById('mealTypeName').value = mealType.name;
                    document.getElementById('mealTypeDescription').value = mealType.description || '';
                    document.getElementById('mealTypeIcon').value = mealType.icon;
                    document.getElementById('mealTypeColor').value = mealType.color_code;
                    document.getElementById('mealTypeStatus').value = mealType.status;
                    document.getElementById('mealTypeOrder').value = mealType.display_order;
                    document.getElementById('mealTypeModalTitle').textContent = 'Edit Meal Type';
                    document.getElementById('mealTypeModal').classList.add('show');
                }
            } catch (error) {
                Swal.fire('Error!', 'Failed to load meal type', 'error');
            }
        }

        async function editTimeSlot(id) {
            try {
                const response = await fetch(`../backend/meal_slots_api.php?action=get_time_slot&id=${id}`);
                const data = await response.json();
                
                if (data.success) {
                    await loadMealTypesForSelect();
                    const slot = data.data;
                    document.getElementById('timeSlotId').value = slot.id;
                    document.getElementById('timeSlotMealType').value = slot.meal_type_id;
                    document.getElementById('timeSlotName').value = slot.slot_name || '';
                    document.getElementById('timeSlotStart').value = slot.start_time;
                    document.getElementById('timeSlotEnd').value = slot.end_time;
                    document.getElementById('timeSlotDescription').value = slot.description || '';
                    document.getElementById('timeSlotCapacity').value = slot.max_capacity;
                    document.getElementById('timeSlotStatus').value = slot.status;
                    document.getElementById('timeSlotOrder').value = slot.display_order;
                    document.getElementById('timeSlotModalTitle').textContent = 'Edit Time Slot';
                    document.getElementById('timeSlotModal').classList.add('show');
                }
            } catch (error) {
                Swal.fire('Error!', 'Failed to load time slot', 'error');
            }
        }

        // Delete functions
        function deleteMealType(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: 'This will delete the meal type and all associated time slots!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'delete_meal_type');
                        formData.append('id', id);
                        
                        const response = await fetch('../backend/meal_slots_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const data = await response.json();
                        
                        if (data.success) {
                            Swal.fire('Deleted!', 'Meal type has been deleted.', 'success');
                            loadMealTypes();
                        } else {
                            Swal.fire('Error!', data.message, 'error');
                        }
                    } catch (error) {
                        Swal.fire('Error!', 'Failed to delete meal type', 'error');
                    }
                }
            });
        }

        function deleteTimeSlot(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: 'This will delete the time slot!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const formData = new FormData();
                        formData.append('action', 'delete_time_slot');
                        formData.append('id', id);
                        
                        const response = await fetch('../backend/meal_slots_api.php', {
                            method: 'POST',
                            body: formData
                        });
                        const data = await response.json();
                        
                        if (data.success) {
                            Swal.fire('Deleted!', 'Time slot has been deleted.', 'success');
                            loadMealTypes();
                            loadTimeSlots();
                        } else {
                            Swal.fire('Error!', data.message, 'error');
                        }
                    } catch (error) {
                        Swal.fire('Error!', 'Failed to delete time slot', 'error');
                    }
                }
            });
        }

        // Utility function to format time
        function formatTime(time) {
            const [hours, minutes] = time.split(':');
            const hour = parseInt(hours);
            const period = hour >= 12 ? 'PM' : 'AM';
            const displayHour = hour % 12 || 12;
            return `${displayHour}:${minutes} ${period}`;
        }

        // Load meal types on page load
        window.addEventListener('DOMContentLoaded', () => {
            loadMealTypes();
        });
    </script>
</body>

</html>
