<?php
session_start();
include_once 'config/db.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: admin_login.php');
    exit;
}

$update_id = isset($_GET['id']) ? (int)$_GET['id'] : null;
if ($update_id === null) {
    header('Location: daily_updates.php');
    exit;
}

// Fetch the update details from the database
$stmt = $pdo->prepare("SELECT * FROM updates WHERE id = :id");
$stmt->bindParam(':id', $update_id);
$stmt->execute();
$update = $stmt->fetch(PDO::FETCH_ASSOC);

// If the update doesn't exist
if (!$update) {
    header('Location: daily_updates.php');
    exit;
}

$existing_images = explode(',', $update['image']); // Existing images from database

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $_POST['title'];
    $description = $_POST['description'];
    $images = [];

    // If new images are uploaded
    if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
        $uploads_dir = 'uploads/';
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            $image_name = basename($_FILES['images']['name'][$key]);
            $target_path = $uploads_dir . $image_name;
            move_uploaded_file($tmp_name, $target_path);
            $images[] = $target_path;
        }
    }

    // Combine old and new images
    $all_images = array_merge($existing_images, $images);
    $image_paths = implode(",", $all_images);

    $stmt = $pdo->prepare("UPDATE updates SET title = :title, description = :description, image = :image, updated_at = NOW() WHERE id = :id");
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':description', $description);
    $stmt->bindParam(':image', $image_paths);
    $stmt->bindParam(':id', $update_id);

    if ($stmt->execute()) {
        header('Location: daily_updates.php');
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('partials/head.php'); ?>
    <style>
        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .preview-item {
            position: relative;
            width: 150px;
            height: 150px;
            border-radius: 10px;
            overflow: hidden;
            border: 2px solid #ddd;
            box-sizing: border-box;
        }
        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .remove-img {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255, 0, 0, 0.5);
            color: white;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            padding: 5px;
        }
    </style>
</head>
<body>
    <div id="global-loader">
        <div class="whirly-loader"></div>
    </div>

    <div class="main-wrapper">
        <?php include('partials/header.php'); ?>
        <?php include('partials/sidebar.php'); ?>

        <div class="page-wrapper" style="max-height: 100vh; overflow-y: auto;">
            <div class="content">
                <div class="page-header mb-3">
                    <div class="page-title">
                        <h4>Edit Update</h4>
                    </div>
                </div>

                <form action="edit_update.php?id=<?= $update_id ?>" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="form-group">
                                        <label for="title">Title</label>
                                        <input type="text" id="title" name="title" class="form-control" value="<?= htmlspecialchars($update['title']) ?>" required>
                                    </div>

                                    <div class="form-group mt-3">
                                        <label for="description">Description</label>
                                        <textarea id="description" name="description" class="form-control" rows="4" required><?= htmlspecialchars($update['description']) ?></textarea>
                                    </div>

                                    <div class="form-group mt-3">
                                        <label for="images">Upload New Images</label>
                                        <input type="file" id="images" name="images[]" class="form-control" multiple accept="image/*" onchange="previewImages()">
                                    </div>

                                    <div id="image-preview" class="image-preview mt-3">
                                        <?php
                                        foreach ($existing_images as $image) {
                                            if ($image) {
                                                echo '<div class="preview-item">';
                                                echo '<img src="' . htmlspecialchars($image) . '" alt="Preview">';
                                                echo '<button type="button" class="remove-img" onclick="removeImage(\'' . htmlspecialchars($image) . '\')">X</button>';
                                                echo '</div>';
                                            }
                                        }
                                        ?>
                                    </div>

                                    <button type="submit" class="btn btn-primary mt-3">Save Changes</button>
                                    <a href="daily_updates.php" class="btn btn-secondary mt-3">Cancel</a>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include('partials/footer.php'); ?>

    <script>
        function previewImages() {
            const previewContainer = document.getElementById('image-preview');
            const files = document.getElementById('images').files;

            // Clear the current preview
            previewContainer.innerHTML = '';

            for (const file of files) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const div = document.createElement('div');
                    div.classList.add('preview-item');

                    const img = document.createElement('img');
                    img.src = e.target.result;
                    div.appendChild(img);

                    const removeButton = document.createElement('button');
                    removeButton.textContent = 'X';
                    removeButton.classList.add('remove-img');
                    removeButton.onclick = function() {
                        div.remove();
                    };
                    div.appendChild(removeButton);

                    previewContainer.appendChild(div);
                };
                reader.readAsDataURL(file);
            }
        }

        function removeImage(imagePath) {
            const previewContainer = document.getElementById('image-preview');
            const images = previewContainer.getElementsByTagName('div');

            // Iterate through the previews to find and remove the image
            for (let i = 0; i < images.length; i++) {
                const imgElement = images[i].getElementsByTagName('img')[0];
                if (imgElement.src === imagePath) {
                    images[i].remove();
                    break;
                }
            }
        }
    </script>
</body>
</html>
