<?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;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .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: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 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) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            table {
                font-size: 12px;
            }
            
            table th,
            table td {
                padding: 8px;
            }
            
            .add-ingredient-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <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>

    <!-- 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() {
            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();
            });
        });

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