<?php
/**
 * Admin Recipes Management Page
 * Manage recipes, ingredients mapping, and preparation details
 */
session_start();

// For now, allow access (in production, check admin authentication)
// 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="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Recipe Management - Granny Restaurant Admin">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <title>Recipe Management - Granny Restaurant</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        .overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.45);
            z-index: 998;
        }

        .overlay.active {
            display: block;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            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;
            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;
            flex: 1;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

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

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

        .sidebar-footer {
            width: 100%;
            margin-top: auto;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
        }

        .logout-btn {
            width: 100%;
            padding: 14px 12px;
            border: none;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

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

        .topbar-left,
        .topbar-right,
        .topbar-user {
            display: flex;
            align-items: center;
            gap: 18px;
        }

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

        .menu-toggle {
            width: 42px;
            height: 42px;
            display: none;
            border: none;
            border-radius: 8px;
            background: #f4efe8;
            color: #8b6f47;
            cursor: pointer;
            font-size: 16px;
        }

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

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

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

        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }
        
        .container {
            max-width: none;
            margin: 0;
            padding: 0;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 28px;
            color: #333;
        }
        
        .btn {
            display: inline-block;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
            text-decoration: none;
        }
        
        .btn-primary {
            background: #d4a574;
            color: white;
        }
        
        .btn-primary:hover {
            background: #b8935f;
        }
        
        .btn-success {
            background: #4caf50;
            color: white;
        }
        
        .btn-success:hover {
            background: #45a049;
        }
        
        .btn-error {
            background: #f44336;
            color: white;
        }
        
        .btn-error:hover {
            background: #da190b;
        }
        
        .btn-info {
            background: #2196f3;
            color: white;
        }
        
        .btn-info:hover {
            background: #0b7dda;
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        table thead {
            background: #f5f5f5;
            border-bottom: 2px solid #ddd;
        }
        
        table th {
            padding: 12px;
            text-align: left;
            font-weight: bold;
            color: #333;
        }
        
        table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
        }
        
        table tbody tr:hover {
            background: #f9f9f9;
        }
        
        .difficulty-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .difficulty-easy {
            background: #e8f5e9;
            color: #2e7d32;
        }
        
        .difficulty-medium {
            background: #fff3e0;
            color: #e65100;
        }
        
        .difficulty-hard {
            background: #ffebee;
            color: #c62828;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 700px;
            width: 90%;
            max-height: 85vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-30px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-header h2 {
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        
        .close-btn:hover {
            color: #333;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: 'Raleway', sans-serif;
            font-size: 14px;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 5px rgba(212, 165, 116, 0.3);
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .modal-footer {
            display: flex;
            gap: 10px;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .modal-footer button {
            flex: 1;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .search-box {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        
        .search-box input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        
        .ingredients-list {
            margin-top: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
        }
        
        .ingredients-list h4 {
            margin-bottom: 15px;
            color: #333;
        }
        
        .ingredient-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background: white;
            border: 1px solid #eee;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        
        .ingredient-info {
            flex: 1;
        }
        
        .ingredient-name {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .ingredient-qty {
            font-size: 12px;
            color: #666;
        }
        
        .add-ingredient-group {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .add-ingredient-group select,
        .add-ingredient-group input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 13px;
        }
        
        .add-ingredient-group button {
            padding: 8px 15px;
            flex: 0 1 auto;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }

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

            .topbar {
                left: 0;
                padding: 0 20px;
            }

            .menu-toggle {
                display: inline-flex;
                align-items: center;
                justify-content: center;
            }

            .main-content {
                margin-left: 0;
                padding: 20px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .header,
            .search-box,
            .add-ingredient-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            table {
                font-size: 12px;
            }
            
            table th,
            table td {
                padding: 8px;
            }
            
            .add-ingredient-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div id="menuOverlay" class="overlay"></div>

    <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="gallery.php"><i class="fas fa-th-large"></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"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="blog.php"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="ingredients.php"><i class="fas fa-leaf"></i> <span>Ingredients</span></a></li>
            <li><a href="recipes.php" class="active"><i class="fas fa-book-open"></i> <span>Recipes</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span></a></li>
            <li><a href="orders.php"><i class="fas fa-file-invoice"></i> <span>Orders</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span></a></li>
            <li><a href="servers.php"><i class="fas fa-user-secret"></i> <span>Servers</span></a></li>
            <li><a href="purchase_managers.php"><i class="fas fa-handshake"></i> <span>Purchase Managers</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</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>

    <div class="topbar">
        <div class="topbar-left">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Recipes</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>

    <div class="main-content">
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div>
                <h1><i class="fas fa-book"></i> Recipe Management</h1>
                <p style="color: #999; margin-top: 5px;">Create and manage recipes for your menu items</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()" style="font-size: 16px;">
                <i class="fas fa-plus"></i> Add Recipe
            </button>
        </div>

        <!-- Content -->
        <div class="content">
            <!-- Search -->
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search recipes by name..." onkeyup="filterTable()">
            </div>

            <!-- Recipes Table -->
            <div class="table-responsive">
                <table id="recipesTable">
                    <thead>
                        <tr>
                            <th>Recipe Name</th>
                            <th>Menu Item</th>
                            <th>Ingredients</th>
                            <th>Prep Time (min)</th>
                            <th>Difficulty</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="recipesTableBody">
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 40px 20px; color: #999;">
                                <i class="fas fa-spinner fa-spin"></i> Loading recipes...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Empty State -->
            <div id="emptyState" class="empty-state" style="display: none;">
                <i class="fas fa-book-open"></i>
                <p>No recipes found. Start by creating your first recipe!</p>
            </div>
        </div>
    </div>
    </div>

    <!-- Add/Edit Recipe Modal -->
    <div id="recipeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Add Recipe</h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>

            <form id="recipeForm" onsubmit="saveRecipe(event)">
                <div class="form-group">
                    <label for="recipeMenuItem">Menu Item *</label>
                    <select id="recipeMenuItem" required onchange="loadIngredientsForRecipe()">
                        <option value="">Select menu item...</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="recipeName">Recipe Name *</label>
                    <input type="text" id="recipeName" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="recipePrep">Preparation Time (minutes) *</label>
                        <input type="number" id="recipePrep" min="1" required>
                    </div>

                    <div class="form-group">
                        <label for="recipeDifficulty">Difficulty Level *</label>
                        <select id="recipeDifficulty" required>
                            <option value="easy">Easy</option>
                            <option value="medium">Medium</option>
                            <option value="hard">Hard</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label for="recipeYield">Yield Quantity (number of portions/servings) *</label>
                    <input type="number" id="recipeYield" min="1" step="0.5" required>
                </div>

                <div class="form-group">
                    <label for="recipeNotes">Chef Notes</label>
                    <textarea id="recipeNotes" placeholder="Special instructions, tips, or notes for the kitchen team..."></textarea>
                </div>

                <!-- Ingredients Section -->
                <div class="ingredients-list" id="ingredientsSection" style="display: none;">
                    <h4>Recipe Ingredients</h4>
                    <div id="ingredientsList"></div>

                    <div class="add-ingredient-group">
                        <select id="ingredientToAdd">
                            <option value="">Select ingredient to add...</option>
                        </select>
                        <input type="number" id="ingredientQty" placeholder="Quantity" step="0.01" min="0">
                        <button type="button" class="btn btn-success btn-sm" onclick="addIngredientToForm()">
                            + Add
                        </button>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> Save Recipe
                    </button>
                    <button type="button" class="btn" style="background: #999; color: white;" onclick="closeModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Recipe Modal -->
    <div id="viewRecipeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="viewRecipeName"></h2>
                <button class="close-btn" onclick="closeViewModal()">&times;</button>
            </div>

            <div id="recipeDetails">
                <!-- Recipe details will be loaded here -->
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="editRecipeById()">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button type="button" class="btn" style="background: #999; color: white;" onclick="closeViewModal()">Close</button>
            </div>
        </div>
    </div>

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

    <script>
        let currentRecipeId = null;
        let allRecipes = [];
        let allMenuItems = [];
        let allIngredients = [];
        let recipeIngredients = [];

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            initializeAdminLayout();
            loadData();
            document.getElementById('recipeModal').addEventListener('click', function(e) {
                if (e.target === this) closeModal();
            });
            document.getElementById('viewRecipeModal').addEventListener('click', function(e) {
                if (e.target === this) closeViewModal();
            });
        });

        function initializeAdminLayout() {
            checkAdminAccess();
            document.getElementById('menuToggle').addEventListener('click', toggleSidebar);
            document.getElementById('menuOverlay').addEventListener('click', closeSidebar);
            document.getElementById('logoutBtn').addEventListener('click', logout);
        }

        function checkAdminAccess() {
            let adminData = localStorage.getItem('admin_user') || localStorage.getItem('adminData') || sessionStorage.getItem('admin_user');

            if (adminData) {
                try {
                    const admin = JSON.parse(adminData);
                    updateAdminHeader(admin.name || 'Admin');
                    return;
                } catch (error) {
                    console.error('Error parsing admin data:', error);
                }
            }

            fetch('auth_check.php')
                .then(response => response.json())
                .then(data => {
                    if (data.authenticated && data.user) {
                        updateAdminHeader(data.user.name || 'Admin');
                        localStorage.setItem('admin_user', JSON.stringify(data.user));
                    } else {
                        window.location.href = 'login.php';
                    }
                })
                .catch(error => {
                    console.error('Auth check error:', error);
                    window.location.href = 'login.php';
                });
        }

        function updateAdminHeader(name) {
            document.getElementById('sidebarAdminName').textContent = name;
            document.getElementById('topbarUserName').textContent = name;
            document.getElementById('userInitial').textContent = (name || 'A').charAt(0).toUpperCase();
        }

        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('menuOverlay').classList.toggle('active');
        }

        function closeSidebar() {
            document.getElementById('sidebar').classList.remove('active');
            document.getElementById('menuOverlay').classList.remove('active');
        }

        function logout() {
            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' })
                        .finally(() => {
                            window.location.href = 'login.php';
                        });
                }
            });
        }

        // Load all data
        async function loadData() {
            await Promise.all([
                loadRecipes(),
                loadMenuItems(),
                loadIngredients()
            ]);
        }

        // Load recipes
        async function loadRecipes() {
            try {
                const response = await fetch('../backend/admin_recipes_api.php?action=get_recipes');
                const data = await response.json();

                if (data.success) {
                    allRecipes = data.data || [];
                    renderTable();
                } else {
                    Swal.fire('Error', data.message || 'Failed to load recipes', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // Load menu items
        async function loadMenuItems() {
            try {
                const response = await fetch('../backend/admin_recipes_api.php?action=get_menu_items');
                const data = await response.json();

                if (data.success) {
                    allMenuItems = data.data || [];
                    const select = document.getElementById('recipeMenuItem');
                    select.innerHTML = '<option value="">Select menu item...</option>' +
                        allMenuItems.map(item => `<option value="${item.id}">${item.item_name}</option>`).join('');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // Load ingredients
        async function loadIngredients() {
            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients');
                const data = await response.json();

                if (data.success) {
                    allIngredients = data.data || [];
                    const select = document.getElementById('ingredientToAdd');
                    select.innerHTML = '<option value="">Select ingredient to add...</option>' +
                        allIngredients.map(ing => `<option value="${ing.id}">${ing.name} (${ing.unit})</option>`).join('');
                }
            } catch (error) {
                console.error('Error:', error);
            }
        }

        // Render table
        function renderTable() {
            const tableBody = document.getElementById('recipesTableBody');
            const emptyState = document.getElementById('emptyState');

            if (allRecipes.length === 0) {
                tableBody.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }

            emptyState.style.display = 'none';
            tableBody.innerHTML = allRecipes.map(recipe => {
                const difficultyClass = `difficulty-${recipe.difficulty_level}`;

                return `
                    <tr>
                        <td><strong>${recipe.name}</strong></td>
                        <td>${recipe.item_name || 'N/A'}</td>
                        <td><badge style="background: #e3f2fd; color: #1565c0; padding: 4px 8px; border-radius: 3px; font-size: 12px;">${recipe.ingredient_count} ingredients</badge></td>
                        <td>${recipe.preparation_time} min</td>
                        <td><span class="difficulty-badge ${difficultyClass}">${recipe.difficulty_level.toUpperCase()}</span></td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn btn-info btn-sm" onclick="viewRecipe(${recipe.id})">
                                    👁️
                                </button>
                                <button class="btn btn-primary btn-sm" onclick="editRecipe(${recipe.id})">
                                    ✏️
                                </button>
                                <button class="btn btn-error btn-sm" onclick="deleteRecipe(${recipe.id}, '${recipe.name}')">
                                    ❌
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // Filter table
        function filterTable() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();

            const tableBody = document.getElementById('recipesTableBody');
            tableBody.querySelectorAll('tr').forEach(row => {
                const name = row.cells[0].textContent.toLowerCase();
                const matchesSearch = name.includes(searchText);
                row.style.display = matchesSearch ? '' : 'none';
            });
        }

        // Open add modal
        function openAddModal() {
            currentRecipeId = null;
            recipeIngredients = [];
            document.getElementById('modalTitle').textContent = 'Add New Recipe';
            document.getElementById('recipeForm').reset();
            document.getElementById('ingredientsSection').style.display = 'none';
            document.getElementById('recipeModal').classList.add('active');
        }

        // Load ingredients when menu item selected
        async function loadIngredientsForRecipe() {
            const menuItemId = document.getElementById('recipeMenuItem').value;
            if (menuItemId) {
                document.getElementById('ingredientsSection').style.display = 'block';
            } else {
                document.getElementById('ingredientsSection').style.display = 'none';
            }
        }

        // Add ingredient to form
        function addIngredientToForm() {
            const ingredientId = document.getElementById('ingredientToAdd').value;
            const qty = document.getElementById('ingredientQty').value;

            if (!ingredientId || !qty) {
                Swal.fire('Error', 'Please select ingredient and enter quantity', 'error');
                return;
            }

            const ingredient = allIngredients.find(i => i.id == ingredientId);
            if (!ingredient) return;

            // Check if already added
            if (recipeIngredients.find(i => i.id == ingredientId)) {
                Swal.fire('Error', 'This ingredient is already in the recipe', 'error');
                return;
            }

            recipeIngredients.push({
                id: ingredient.id,
                name: ingredient.name,
                unit: ingredient.unit,
                quantity_required: qty
            });

            renderIngredientsInForm();
            document.getElementById('ingredientToAdd').value = '';
            document.getElementById('ingredientQty').value = '';
        }

        // Render ingredients in form
        function renderIngredientsInForm() {
            const list = document.getElementById('ingredientsList');
            list.innerHTML = recipeIngredients.map((ing, idx) => `
                <div class="ingredient-item">
                    <div class="ingredient-info">
                        <div class="ingredient-name">${ing.name}</div>
                        <div class="ingredient-qty">${ing.quantity_required} ${ing.unit}</div>
                    </div>
                    <button type="button" class="btn btn-error btn-sm" onclick="removeIngredientFromForm(${idx})">
                        Remove
                    </button>
                </div>
            `).join('');
        }

        // Remove ingredient from form
        function removeIngredientFromForm(idx) {
            recipeIngredients.splice(idx, 1);
            renderIngredientsInForm();
        }

        // save recipe
        async function saveRecipe(e) {
            e.preventDefault();

            if (recipeIngredients.length === 0) {
                Swal.fire('Error', 'Please add at least one ingredient to the recipe', 'error');
                return;
            }

            const recipeData = {
                menu_item_id: parseInt(document.getElementById('recipeMenuItem').value),
                name: document.getElementById('recipeName').value,
                preparation_time: parseInt(document.getElementById('recipePrep').value),
                difficulty_level: document.getElementById('recipeDifficulty').value,
                yield_quantity: parseFloat(document.getElementById('recipeYield').value),
                chef_notes: document.getElementById('recipeNotes').value,
                ingredients: recipeIngredients
            };

            if (currentRecipeId) {
                recipeData.id = currentRecipeId;
            }

            try {
                const action = currentRecipeId ? 'update_recipe' : 'create_recipe';
                const response = await fetch(`../backend/admin_recipes_api.php?action=${action}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(recipeData)
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire('Success', data.message || 'Recipe saved successfully', 'success');
                    closeModal();
                    loadRecipes();
                } else {
                    Swal.fire('Error', data.message || 'Failed to save recipe', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to save recipe', 'error');
            }
        }

        // View recipe
        async function viewRecipe(id) {
            try {
                const response = await fetch('../backend/admin_recipes_api.php?action=get_recipe', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id })
                });

                const data = await response.json();

                if (data.success) {
                    const recipe = data.data;
                    currentRecipeId = recipe.id;

                    document.getElementById('viewRecipeName').textContent = recipe.name;

                    let detailsHTML = `
                        <div style="margin-bottom: 20px;">
                            <p><strong>Menu Item:</strong> ${recipe.item_name || 'N/A'}</p>
                            <p><strong>Preparation Time:</strong> ${recipe.preparation_time} minutes</p>
                            <p><strong>Difficulty:</strong> <span class="difficulty-badge difficulty-${recipe.difficulty_level}">${recipe.difficulty_level.toUpperCase()}</span></p>
                            <p><strong>Yield:</strong> ${recipe.yield_quantity} portions</p>
                    `;

                    if (recipe.chef_notes) {
                        detailsHTML += `<p><strong>Chef Notes:</strong><br>${recipe.chef_notes}</p>`;
                    }

                    detailsHTML += `
                        </div>
                        <div class="ingredients-list">
                            <h4>Ingredients</h4>
                    `;

                    if (recipe.ingredients && recipe.ingredients.length > 0) {
                        detailsHTML += recipe.ingredients.map(ing => `
                            <div class="ingredient-item">
                                <div class="ingredient-info">
                                    <div class="ingredient-name">${ing.ingredient_name}</div>
                                    <div class="ingredient-qty">${ing.quantity_required} ${ing.unit}</div>
                                </div>
                            </div>
                        `).join('');
                    } else {
                        detailsHTML += '<p style="color: #999; text-align: center; padding: 20px;">No ingredients added yet</p>';
                    }

                    detailsHTML += '</div>';

                    document.getElementById('recipeDetails').innerHTML = detailsHTML;
                    document.getElementById('viewRecipeModal').classList.add('active');
                } else {
                    Swal.fire('Error', data.message || 'Failed to load recipe', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to load recipe', 'error');
            }
        }

        // Edit recipe
        async function editRecipe(id) {
            try {
                const response = await fetch('../backend/admin_recipes_api.php?action=get_recipe', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id })
                });

                const data = await response.json();

                if (data.success) {
                    const recipe = data.data;
                    currentRecipeId = recipe.id;
                    recipeIngredients = recipe.ingredients.map(ing => ({
                        id: ing.ingredient_id,
                        name: ing.ingredient_name,
                        unit: ing.unit,
                        quantity_required: ing.quantity_required
                    }));

                    document.getElementById('modalTitle').textContent = 'Edit Recipe';
                    document.getElementById('recipeMenuItem').value = recipe.menu_item_id;
                    document.getElementById('recipeName').value = recipe.name;
                    document.getElementById('recipePrep').value = recipe.preparation_time;
                    document.getElementById('recipeDifficulty').value = recipe.difficulty_level;
                    document.getElementById('recipeYield').value = recipe.yield_quantity;
                    document.getElementById('recipeNotes').value = recipe.chef_notes || '';

                    document.getElementById('ingredientsSection').style.display = 'block';
                    renderIngredientsInForm();

                    document.getElementById('recipeModal').classList.add('active');
                } else {
                    Swal.fire('Error', data.message || 'Failed to load recipe', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to load recipe', 'error');
            }
        }

        // Edit recipe from view modal
        function editRecipeById() {
            closeViewModal();
            editRecipe(currentRecipeId);
        }

        // Delete recipe
        function deleteRecipe(id, name) {
            Swal.fire({
                title: 'Delete Recipe?',
                text: `Are you sure you want to delete "${name}"?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f44336',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Delete'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/admin_recipes_api.php?action=delete_recipe', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ id })
                        });

                        const data = await response.json();

                        if (data.success) {
                            Swal.fire('Deleted', 'Recipe deleted successfully', 'success');
                            loadRecipes();
                        } else {
                            Swal.fire('Error', data.message || 'Failed to delete recipe', 'error');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to delete recipe', 'error');
                    }
                }
            });
        }

        // Close modal
        function closeModal() {
            document.getElementById('recipeModal').classList.remove('active');
            currentRecipeId = null;
            recipeIngredients = [];
        }

        // Close view modal
        function closeViewModal() {
            document.getElementById('viewRecipeModal').classList.remove('active');
        }
    </script>
</body>
</html>
