<?php
session_start();

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Include the database connection
require 'db_connection.php';

// Handle delete request
if (isset($_GET['delete_id'])) {
    $deleteId = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM recipes WHERE id = ?");
    $stmt->bind_param('i', $deleteId);
    if ($stmt->execute()) {
        echo "<script>alert('Recipe deleted successfully.'); window.location.href = 'manage_recipes.php';</script>";
    } else {
        echo "<script>alert('Failed to delete the recipe.');</script>";
    }
}

// Handle edit request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_id'])) {
    $editId = intval($_POST['edit_id']);
    $heading = htmlspecialchars($_POST['heading']);
    $details = $_POST['details'];
    $youtubeLink = !empty($_POST['youtube_link']) ? htmlspecialchars($_POST['youtube_link']) : null;

    $stmt = $conn->prepare("UPDATE recipes SET heading = ?, details = ?, youtube_link = ? WHERE id = ?");
    $stmt->bind_param('sssi', $heading, $details, $youtubeLink, $editId);
    if ($stmt->execute()) {
        echo "<script>alert('Recipe updated successfully.'); window.location.href = 'manage_recipes.php';</script>";
    } else {
        echo "<script>alert('Failed to update the recipe.');</script>";
    }
}

// Fetch all recipes
$result = $conn->query("SELECT * FROM recipes ORDER BY id DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Recipes</title>
    <link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f4f4f4;
        }
        .action-buttons a {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <h1>Manage Recipes</h1>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Heading</th>
                <th>Details</th>
                <th>YouTube Link</th>
                <th>Images</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['heading']) ?></td>
                    <td><?= substr(strip_tags($row['details']), 0, 100) ?>...</td>
                    <td><?= $row['youtube_link'] ? "<a href='{$row['youtube_link']}' target='_blank'>View</a>" : 'N/A' ?></td>
                    <td>
                        <?php 
                        $images = json_decode($row['images'], true); 
                        if ($images):
                            foreach ($images as $image): ?>
                                <img src="<?= htmlspecialchars($image['path']) ?>" alt="<?= htmlspecialchars($image['name']) ?>" style="width: 50px; height: 50px; object-fit: cover;">
                            <?php endforeach; 
                        else: 
                            echo 'No Images';
                        endif;
                        ?>
                    </td>
                    <td class="action-buttons">
                        <a href="manage_recipes.php?edit_id=<?= $row['id'] ?>">Edit</a>
                        <a href="manage_recipes.php?delete_id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete this recipe?');">Delete</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>

    <?php if (isset($_GET['edit_id'])): 
        $editId = intval($_GET['edit_id']);
        $stmt = $conn->prepare("SELECT * FROM recipes WHERE id = ?");
        $stmt->bind_param('i', $editId);
        $stmt->execute();
        $editResult = $stmt->get_result();
        if ($editResult->num_rows > 0):
            $editRow = $editResult->fetch_assoc();
    ?>
        <h2>Edit Recipe</h2>
        <form method="post">
            <input type="hidden" name="edit_id" value="<?= $editRow['id'] ?>">
            <label for="heading">Recipe Heading:</label><br>
            <input type="text" id="heading" name="heading" value="<?= htmlspecialchars($editRow['heading']) ?>" required><br><br>

            <label for="details">Recipe Details:</label><br>
            <div id="editor-container" style="height: 300px; border: 1px solid #ccc;"></div>
            <input type="hidden" id="details" name="details" value="<?= htmlspecialchars($editRow['details']) ?>">
            <br><br>

            <label for="youtube_link">YouTube Link (optional):</label><br>
            <input type="url" id="youtube_link" name="youtube_link" value="<?= htmlspecialchars($editRow['youtube_link']) ?>"><br><br>

            <button type="submit">Update Recipe</button>
        </form>

        <script>
            var quill = new Quill('#editor-container', {
                theme: 'snow',
                placeholder: 'Write your recipe details here...',
                modules: {
                    toolbar: [
                        [{ header: [1, 2, false] }],
                        ['bold', 'italic', 'underline', 'strike'],
                        [{ list: 'ordered' }, { list: 'bullet' }],
                        ['link'],
                        ['clean']
                    ]
                }
            });

            // Set initial content
            quill.root.innerHTML = document.getElementById('details').value;

            // Update hidden input on form submit
            document.querySelector('form').onsubmit = function () {
                document.querySelector('#details').value = quill.root.innerHTML;
            };
        </script>
    <?php 
        else:
            echo "<p>Recipe not found!</p>";
        endif;
    endif; ?>
</body>
</html>
