<?php
declare(strict_types=1);

session_start();

require_once "connection.php";

// ========================================
// 1. ADMIN AUTHENTICATION
// ========================================

if (
    !isset($_SESSION['admin_id']) ||
    !is_int($_SESSION['admin_id']) ||
    $_SESSION['admin_id'] <= 0 ||
    ($_SESSION['start'] ?? false) !== true
) {
    header("Location: login.php");
    exit;
}

// ========================================
// 2. CSRF TOKEN
// ========================================

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$error = '';

$uploadDir = __DIR__ . "/assets/images/slider/";

// ========================================
// 3. SECURE IMAGE UPLOAD FUNCTION
// ========================================

function saveSliderImage(
    array $file,
    string $prefix,
    string $uploadDir
): string {

    if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException("Image upload failed.");
    }

    // Maximum 5 MB
    if ($file['size'] <= 0 || $file['size'] > 5 * 1024 * 1024) {
        throw new RuntimeException("Image size must be less than 5 MB.");
    }

    if (!is_uploaded_file($file['tmp_name'])) {
        throw new RuntimeException("Invalid uploaded file.");
    }

    // Verify image
    $imageInfo = getimagesize($file['tmp_name']);

    if ($imageInfo === false) {
        throw new RuntimeException("Invalid image file.");
    }

    $allowedTypes = [
        IMAGETYPE_JPEG,
        IMAGETYPE_PNG,
        IMAGETYPE_WEBP
    ];

    if (!in_array($imageInfo[2], $allowedTypes, true)) {
        throw new RuntimeException(
            "Only JPG, JPEG and WEBP images are allowed."
        );
    }

    // Check dimensions
    if ($imageInfo[0] > 8000 || $imageInfo[1] > 8000) {
        throw new RuntimeException("Image dimensions are too large.");
    }

    // Verify MIME type
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);

    $allowedMime = [
        'image/jpeg',
        'image/png',
        'image/webp'
    ];

    if (!in_array($mime, $allowedMime, true)) {
        throw new RuntimeException("Invalid image format.");
    }

    // Check GD WebP support
    if (
        !function_exists('imagecreatefromstring') ||
        !function_exists('imagewebp')
    ) {
        throw new RuntimeException(
            "PHP GD WebP support is not enabled."
        );
    }

    // Read image contents
    $imageData = file_get_contents($file['tmp_name']);

    if ($imageData === false) {
        throw new RuntimeException("Unable to read image.");
    }

    // Re-encode image
    $image = imagecreatefromstring($imageData);

    if ($image === false) {
        throw new RuntimeException("Unable to process image.");
    }

    if (function_exists('imageistruecolor') && !imageistruecolor($image)) {
        imagepalettetotruecolor($image);
    }

    imagealphablending($image, false);
    imagesavealpha($image, true);

    // Create upload directory
    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
            imagedestroy($image);
            throw new RuntimeException("Upload directory unavailable.");
        }
    }

    // Random filename
    $fileName = $prefix . bin2hex(random_bytes(16)) . ".webp";

    $destination = $uploadDir . $fileName;

    // Save as WebP
    $saved = imagewebp($image, $destination, 85);

    imagedestroy($image);

    if (!$saved) {
        throw new RuntimeException("Unable to save image.");
    }

    return $fileName;
}


// ========================================
// 4. GET SLIDER ID
// ========================================

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$id || $id <= 0) {
    http_response_code(400);
    exit("Invalid slider ID.");
}


// ========================================
// 5. FETCH EXISTING SLIDER
// ========================================

$stmt = mysqli_prepare(
    $con,
    "SELECT id, Image, PImage FROM slider WHERE id = ? LIMIT 1"
);

mysqli_stmt_bind_param($stmt, "i", $id);

mysqli_stmt_execute($stmt);

$result = mysqli_stmt_get_result($stmt);

$slider = mysqli_fetch_assoc($result);

mysqli_stmt_close($stmt);

if (!$slider) {
    http_response_code(404);
    exit("Slider not found.");
}


// ========================================
// 6. HANDLE UPDATE
// ========================================

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    $savedFiles = [];

    try {

        // Validate CSRF
        if (
            !isset($_POST['csrf_token']) ||
            !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
        ) {
            throw new RuntimeException(
                "Invalid request. Please refresh the page."
            );
        }

        // Keep existing images by default
        $newImage = $slider['Image'];
        $newPImage = $slider['PImage'];

        $oldImage = $slider['Image'];
        $oldPImage = $slider['PImage'];

        // ========================================
        // DESKTOP IMAGE (OPTIONAL ON EDIT)
        // ========================================

        if (
            isset($_FILES['Image']) &&
            $_FILES['Image']['error'] !== UPLOAD_ERR_NO_FILE
        ) {

            $newImage = saveSliderImage(
                $_FILES['Image'],
                'desktop_',
                $uploadDir
            );

            $savedFiles[] = $newImage;
        }

        // ========================================
        // MOBILE IMAGE (OPTIONAL)
        // ========================================

        if (
            isset($_FILES['PImage']) &&
            $_FILES['PImage']['error'] !== UPLOAD_ERR_NO_FILE
        ) {

            $newPImage = saveSliderImage(
                $_FILES['PImage'],
                'mobile_',
                $uploadDir
            );

            $savedFiles[] = $newPImage;
        }

        // ========================================
        // DATABASE UPDATE
        // ========================================

        $updateSql = "
            UPDATE slider
            SET Image = ?, PImage = ?
            WHERE id = ?
        ";

        $stmt = mysqli_prepare($con, $updateSql);

        mysqli_stmt_bind_param(
            $stmt,
            "ssi",
            $newImage,
            $newPImage,
            $id
        );

        mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

        // ========================================
        // DELETE OLD IMAGES AFTER DB SUCCESS
        // ========================================

        $safeDelete = function (?string $fileName) use ($uploadDir) {

            if (
                empty($fileName) ||
                basename($fileName) !== $fileName
            ) {
                return;
            }

            $filePath = $uploadDir . $fileName;

            if (is_file($filePath) && !is_link($filePath)) {
                unlink($filePath);
            }
        };

        // Delete old desktop image if replaced
        if ($oldImage !== $newImage) {
            $safeDelete($oldImage);
        }

        // Delete old mobile image if replaced
        if ($oldPImage !== $newPImage) {
            $safeDelete($oldPImage);
        }

        // Refresh CSRF token
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

        // Redirect
        header("Location: viewslider.php");
        exit;

    } catch (Throwable $e) {

        // Delete newly uploaded files if update fails
        foreach ($savedFiles as $fileName) {

            $filePath = $uploadDir . $fileName;

            if (is_file($filePath) && !is_link($filePath)) {
                unlink($filePath);
            }
        }

        error_log("Slider Update Error: " . $e->getMessage());

        if ($e instanceof RuntimeException) {
            $error = $e->getMessage();
        } else {
            $error = "Something went wrong. Please try again.";
        }
    }
}

// ========================================
// 7. ADMIN HEADER
// ========================================

include("header.php");


// Safe filename for displaying existing images
function safeSliderImageUrl(?string $filename): ?string
{
    if (
        empty($filename) ||
        basename($filename) !== $filename ||
        !preg_match('/\A[a-zA-Z0-9._-]+\.(jpg|jpeg|png|webp)\z/i', $filename)
    ) {
        return null;
    }

    return "./assets/images/slider/" . rawurlencode($filename);
}

$desktopUrl = safeSliderImageUrl($slider['Image']);
$phoneUrl = safeSliderImageUrl($slider['PImage']);

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">

    <title>Edit Slider</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" href="../images/logo.png">

    <!-- Plugins CSS -->
    <link href="assets/libs/dropzone/dropzone.css" rel="stylesheet">

    <link rel="stylesheet"
        href="https://use.fontawesome.com/releases/v5.8.1/css/all.css">

    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css"
        id="bootstrap-style"
        rel="stylesheet">

    <!-- Icons CSS -->
    <link href="assets/css/icons.min.css" rel="stylesheet">

    <!-- App CSS -->
    <link href="assets/css/app.min.css"
        id="app-style"
        rel="stylesheet">

    <style>

        .form .input {
            width: 100%;
            background: white;
            border: none;
            padding: 15px 20px;
            border-radius: 20px;
            margin-bottom: 9px;
            margin-top: 15px;
            box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
            border-inline: 2px solid transparent;
        }

        input[name='Image'],
        input[name='PImage'] {
            display: none;
        }

        .upload-btn {
            cursor: pointer;
        }

        .upload-btn:hover {
            background: #f8f9fa;
        }

        .filepath {
            display: none;
            margin-top: 15px;
        }

        .filepath img,
        .current-image {
            max-width: 150px;
            max-height: 120px;
            object-fit: contain;
            border: 1px solid #ddd;
            padding: 5px;
            border-radius: 5px;
        }

    </style>

</head>


<body data-sidebar="dark">

    <div id="layout-wrapper">

        <div class="w-80">

            <div class="page-content"
                style="width: 80%; margin-left: 260px;">

                <div class="container">


                    <!-- PAGE TITLE -->

                    <div class="row">

                        <div class="col-12">

                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">

                                <h4 class="mb-sm-0 font-size-18">
                                    EDIT SLIDER
                                </h4>

                            </div>

                        </div>

                    </div>


                    <!-- EDIT FORM -->

                    <div class="row">

                        <div class="col-12">

                            <div class="card">

                                <div class="card-body">

                                    <form
                                        class="form"
                                        action="editslider.php?id=<?php echo (int)$id; ?>"
                                        method="POST"
                                        enctype="multipart/form-data">

                                        <!-- CSRF TOKEN -->

                                        <input
                                            type="hidden"
                                            name="csrf_token"
                                            value="<?php echo htmlspecialchars(
                                                $_SESSION['csrf_token'],
                                                ENT_QUOTES,
                                                'UTF-8'
                                            ); ?>">


                                        <!-- ERROR MESSAGE -->

                                        <?php if (!empty($error)): ?>

                                            <div class="alert alert-danger">

                                                <?php echo htmlspecialchars(
                                                    $error,
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ); ?>

                                            </div>

                                        <?php endif; ?>


                                        <div class="row">


                                            <!-- DESKTOP SLIDER -->

                                            <div class="col-lg-6">

                                                <h5>Desktop Slider</h5>

                                                <!-- CURRENT IMAGE -->

                                                <?php if ($desktopUrl): ?>

                                                    <p>Current Image:</p>

                                                    <img
                                                        src="<?php echo htmlspecialchars($desktopUrl, ENT_QUOTES, 'UTF-8'); ?>"
                                                        class="current-image"
                                                        alt="Current desktop slider">

                                                    <br><br>

                                                <?php else: ?>

                                                    <p class="text-muted">
                                                        No valid desktop image available.
                                                    </p>

                                                <?php endif; ?>


                                                <div class="dropzone">

                                                    <div class="fallback">

                                                        <input
                                                            name="Image"
                                                            id="Image"
                                                            type="file"
                                                            accept="image/jpeg,image/png,image/webp">

                                                    </div>

                                                    <div
                                                        class="dz-message needsclick upload-btn"
                                                        data-target="Image">

                                                        <div class="mb-3">

                                                            <i class="display-4 text-muted bx bxs-cloud-upload"></i>

                                                        </div>

                                                        <h4>
                                                            Click to upload new desktop image.
                                                        </h4>

                                                        <p class="text-muted">
                                                            Leave empty to keep current image.
                                                        </p>

                                                    </div>

                                                </div>


                                                <!-- DESKTOP PREVIEW -->

                                                <div
                                                    class="filepath"
                                                    id="Image-preview">

                                                    <img src="" alt="desktop-preview">

                                                    <span class="filename"></span>

                                                </div>

                                            </div>


                                            <!-- PHONE SLIDER -->

                                            <div class="col-lg-6">

                                                <h5>Phone Slider (Optional)</h5>


                                                <!-- CURRENT PHONE IMAGE -->

                                                <?php if ($phoneUrl): ?>

                                                    <p>Current Image:</p>

                                                    <img
                                                        src="<?php echo htmlspecialchars($phoneUrl, ENT_QUOTES, 'UTF-8'); ?>"
                                                        class="current-image"
                                                        alt="Current phone slider">

                                                    <br><br>

                                                <?php else: ?>

                                                    <p>
                                                        <span class="badge bg-secondary">
                                                            No phone image set.
                                                        </span>
                                                    </p>

                                                <?php endif; ?>


                                                <div class="dropzone">

                                                    <div class="fallback">

                                                        <input
                                                            name="PImage"
                                                            id="PImage"
                                                            type="file"
                                                            accept="image/jpeg,image/png,image/webp">

                                                    </div>

                                                    <div
                                                        class="dz-message needsclick upload-btn"
                                                        data-target="PImage">

                                                        <div class="mb-3">

                                                            <i class="display-4 text-muted bx bxs-cloud-upload"></i>

                                                        </div>

                                                        <h4>
                                                            Click to upload new phone image.
                                                        </h4>

                                                        <p class="text-muted">
                                                            Leave empty to keep current image.
                                                        </p>

                                                    </div>

                                                </div>


                                                <!-- PHONE PREVIEW -->

                                                <div
                                                    class="filepath"
                                                    id="PImage-preview">

                                                    <img src="" alt="phone-preview">

                                                    <span class="filename"></span>

                                                </div>

                                            </div>

                                        </div>


                                        <br>


                                        <!-- BUTTONS -->

                                        <div class="text-center mt-4">

                                            <button
                                                type="submit"
                                                name="submit"
                                                class="btn btn-primary"
                                                value="submit">

                                                Update

                                            </button>


                                            <a href="viewslider.php"
                                                class="btn btn-danger">

                                                Back to List

                                            </a>

                                        </div>


                                    </form>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>


    <!-- JAVASCRIPT -->

    <script src="assets/libs/jquery/jquery.min.js"></script>

    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>

    <script src="assets/libs/metismenu/metisMenu.min.js"></script>

    <script src="assets/libs/simplebar/simplebar.min.js"></script>

    <script src="assets/libs/node-waves/waves.min.js"></script>

    <script src="assets/libs/dropzone/dropzone-min.js"></script>

    <script src="assets/js/pages/form-file-upload.init.js"></script>

    <script src="assets/js/app.js"></script>


    <!-- IMAGE UPLOAD PREVIEW -->

    <script>

        // Open file selector

        document.querySelectorAll(".upload-btn").forEach(function(btn) {

            btn.addEventListener("click", function() {

                const inputId = this.getAttribute("data-target");

                document.getElementById(inputId).click();

            });

        });


        // Preview selected image

        function previewFile(inputId) {

            const input = document.getElementById(inputId);

            const previewBox = document.getElementById(inputId + "-preview");

            const fileNameSpan = previewBox.querySelector(".filename");

            const imgTag = previewBox.querySelector("img");

            let objectURL = null;


            input.addEventListener("change", function() {

                if (objectURL) {
                    URL.revokeObjectURL(objectURL);
                    objectURL = null;
                }

                if (input.files && input.files[0]) {

                    const file = input.files[0];

                    // Maximum 5 MB
                    if (file.size > 5 * 1024 * 1024) {

                        alert("Image size must be less than 5 MB.");

                        input.value = "";

                        previewBox.style.display = "none";

                        return;
                    }

                    fileNameSpan.textContent = file.name;

                    objectURL = URL.createObjectURL(file);

                    imgTag.src = objectURL;

                    previewBox.style.display = "block";

                } else {

                    previewBox.style.display = "none";

                }

            });

        }


        // Apply preview

        previewFile("Image");

        previewFile("PImage");

    </script>


</body>

</html>
