<?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';

// Function to resize image if it's greater than a certain size
function resizeImageIfNeeded($filePath, $maxSizeKB = 50, $maxWidth = 800) {
    $imageSize = filesize($filePath);
    if ($imageSize > $maxSizeKB * 1024) { // Check if the image exceeds the size limit
        $image = imagecreatefromstring(file_get_contents($filePath));
        if ($image) {
            $width = imagesx($image);
            $height = imagesy($image);
            $newWidth = $maxWidth;
            $newHeight = intval($height * $newWidth / $width);

            $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
            imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

            // Overwrite the file with resized image
            imagejpeg($resizedImage, $filePath, 85); // Adjust quality to control size
            imagedestroy($resizedImage);
            imagedestroy($image);
        }
    }
}

// Handle form submission (Post or Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $heading = htmlspecialchars($_POST['heading']);
    $details = $_POST['details']; // Contains rich text
    $youtubeLink = !empty($_POST['youtube_link']) ? htmlspecialchars($_POST['youtube_link']) : null;

    // Process image uploads with details
    $imageDetails = [];
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $imageName = basename($_FILES['images']['name'][$key]);
                $imagePath = 'uploads/' . uniqid() . '_' . $imageName;

                // Save the image to the server
                move_uploaded_file($tmpName, $imagePath);

                // Resize the image if necessary
                resizeImageIfNeeded($imagePath, 50, 800);

                // Add the image details
                $imageDetails[] = [
                    'path' => $imagePath,
                    'name' => htmlspecialchars($_POST['image_names'][$key] ?? ''),
                ];
            }
        }
    }

    // Insert new recipe into the database
    if (isset($_POST['edit_id']) && !empty($_POST['edit_id'])) { // Edit Recipe
        $editId = (int)$_POST['edit_id'];

        // Update the recipe with new details and images
        $stmt = $conn->prepare("UPDATE recipes SET heading = ?, details = ?, youtube_link = ?, images = ? WHERE id = ?");
        $stmt->bind_param('ssssi', $heading, $details, $youtubeLink, json_encode($imageDetails), $editId);

        if ($stmt->execute()) {
            echo "Recipe updated successfully.";
        } else {
            echo "Error: " . $stmt->error;
        }
    } else { // New Recipe
        // Insert the recipe into the database
        $stmt = $conn->prepare("INSERT INTO recipes (heading, details, youtube_link, images) VALUES (?, ?, ?, ?)");
        $stmt->bind_param('ssss', $heading, $details, $youtubeLink, json_encode($imageDetails));

        if ($stmt->execute()) {
            echo "Recipe posted successfully.";
        } else {
            echo "Error: " . $stmt->error;
        }
    }
}

// Get recipe details for editing (if edit mode is active)
$recipe = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    $stmt = $conn->prepare("SELECT * FROM recipes WHERE id = ?");
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $result = $stmt->get_result();
    $recipe = $result->fetch_assoc();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post or Edit Recipe</title>
    <!-- Include Quill.js -->
    <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>
</head>
<body>
    <h1><?php echo $recipe ? 'Edit Recipe' : 'Post Recipe'; ?></h1>
    <form method="post" enctype="multipart/form-data">
        <?php if ($recipe): ?>
            <input type="hidden" name="edit_id" value="<?php echo $recipe['id']; ?>">
        <?php endif; ?>
<style>/* General Styles */
body {
    font-family: Arial, sans-serif;
    margin: 20px;
    padding: 0;
    background-color: #f9f9f9;
    color: #333;
}

h1 {
    text-align: center;
    color: #4CAF50;
}

/* Form Styles */
form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

label {
    font-weight: bold;
    margin-bottom: 5px;
    display: inline-block;
}

input[type="text"],
input[type="url"],
input[type="file"],
textarea {
    width: 100%;
    padding: 10px;
    margin: 10px 0 20px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    font-size: 14px;
}

input[type="file"] {
    border: none;
}

button[type="submit"] {
    width: 100%;
    padding: 10px;
    background: #4CAF50;
    color: #fff;
    font-size: 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button[type="submit"]:hover {
    background: #45a049;
}

/* Quill.js Editor Styles */
#editor-container {
    border-radius: 4px;
    background: #fff;
}

/* Image Upload Section */
#image-upload-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.image-upload {
    display: flex;
    align-items: center;
    gap: 10px;
}

.image-upload input[type="text"] {
    flex-grow: 1;
}

.image-upload button {
    background: #e74c3c;
    color: #fff;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.image-upload button:hover {
    background: #c0392b;
}

/* Add Image Button */
button[type="button"] {
    background: #3498db;
    color: #fff;
    border: none;
    padding: 10px 20px;
    margin-top: 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

button[type="button"]:hover {
    background: #2980b9;
}
</style>
        <label for="heading">Recipe Heading:</label><br>
        <input type="text" id="heading" name="heading" value="<?php echo $recipe['heading'] ?? ''; ?>" required><br><br>

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

        <label for="youtube_link">YouTube Link (optional):</label><br>
        <input type="url" id="youtube_link" name="youtube_link" value="<?php echo $recipe['youtube_link'] ?? ''; ?>" placeholder="https://youtube.com/..."><br><br>

        <label>Upload Images (optional):</label><br>
        <div id="image-upload-container">
            <?php
            if ($recipe && $recipe['images']) {
                $images = json_decode($recipe['images'], true);
                foreach ($images as $image) {
                    echo '<div class="image-upload">';
                    echo '<input type="file" name="images[]" accept="image/*">';
                    echo '<input type="text" name="image_names[]" value="' . $image['name'] . '" placeholder="Image name">';
                    echo '<button type="button" onclick="removeImage(this)">Remove</button>';
                    echo '</div>';
                }
            }
            ?>
            <div class="image-upload">
                <input type="file" name="images[]" accept="image/*">
                <input type="text" name="image_names[]" placeholder="Image name">
                <button type="button" onclick="removeImage(this)">Remove</button>
            </div>
        </div>
        <button type="button" onclick="addImage()">Add Image</button>
        <br><br>

        <button type="submit"><?php echo $recipe ? 'Update Recipe' : 'Post Recipe'; ?></button>
    </form>

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

        // Update hidden input on form submit
        document.querySelector('form').onsubmit = function () {
            document.querySelector('#details').value = quill.root.innerHTML;
        };

        // Add image upload fields dynamically
        function addImage() {
            const container = document.getElementById('image-upload-container');
            const div = document.createElement('div');
            div.classList.add('image-upload');
            div.innerHTML = `
                <input type="file" name="images[]" accept="image/*">
                <input type="text" name="image_names[]" placeholder="Image name">
                <button type="button" onclick="removeImage(this)">Remove</button>
            `;
            container.appendChild(div);
        }

        // Remove image upload fields
        function removeImage(button) {
            button.parentElement.remove();
        }
    </script>
</body>
</html>
