<?php
declare(strict_types=1);

// =============================================
// 1. SECURE SESSION
// =============================================

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// =============================================
// 2. DATABASE CONNECTION
// =============================================

require_once "connection.php";

// =============================================
// 3. 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;
}

// =============================================
// 4. VALIDATE 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
// =============================================

// Fetch slider record (single-image version)

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

if (!$stmt) {
    error_log("Slider prepare error: " . mysqli_error($con));
    http_response_code(500);
    exit("Database error. Please contact administrator.");
}

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

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result(
    $stmt,
    $sliderId,
    $sliderImage
);

$found = mysqli_stmt_fetch($stmt);

mysqli_stmt_close($stmt);

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

$row = [
    'id' => $sliderId,
    'Image' => $sliderImage
];

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

// =============================================
// 6. GENERATE CSRF TOKEN
// =============================================

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

$error = '';


// =============================================
// 7. SECURE IMAGE UPLOAD FUNCTION
// =============================================

function saveSliderImage(array $file, string $uploadDir): string
{
    // Check upload error
    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."
        );
    }

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

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

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

    // Allowed image types
    $allowedTypes = [
        IMAGETYPE_JPEG,
        IMAGETYPE_PNG,
        IMAGETYPE_WEBP
    ];

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

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

    // Check 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
    $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.");
    }

    // Preserve transparency
    if (!imageistruecolor($image)) {
        imagepalettetotruecolor($image);
    }

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

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

    // Random filename
    $fileName = 'desktop_' . bin2hex(random_bytes(16)) . '.webp';

    $destination = $uploadDir . $fileName;

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

    imagedestroy($image);

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

    return $fileName;
}


// =============================================
// 8. SAFE OLD IMAGE DELETION
// =============================================

function deleteOldSliderImage(
    ?string $filename,
    int $currentId,
    mysqli $con,
    string $uploadDir
): void {

    if (
        empty($filename) ||
        basename($filename) !== $filename ||
        !preg_match(
            '/\A[a-zA-Z0-9._-]+\.(jpg|jpeg|png|webp)\z/i',
            $filename
        )
    ) {
        return;
    }

    // Check whether another slider uses this image
    $stmt = mysqli_prepare(
        $con,
        "SELECT COUNT(*) FROM slider
         WHERE Image = ? OR PImage = ?"
    );

    mysqli_stmt_bind_param(
        $stmt,
        "ss",
        $filename,
        $filename
    );

    mysqli_stmt_execute($stmt);

    mysqli_stmt_bind_result($stmt, $count);

    mysqli_stmt_fetch($stmt);

    mysqli_stmt_close($stmt);

    // Do not delete an image still referenced by another record
    if ($count > 0) {
        return;
    }

    $filePath = $uploadDir . $filename;

    if (is_file($filePath) && !is_link($filePath)) {
        if (!unlink($filePath)) {
            error_log("Unable to delete old slider image: " . $filename);
        }
    }
}


// =============================================
// 9. HANDLE UPDATE
// =============================================

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

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

    $newImage = null;

    try {

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

        // Get old image directly from database
        $oldImage = $row['Image'];

        // Keep existing image if no new file is selected
        $Image = $oldImage;

        // =============================================
        // HANDLE NEW IMAGE
        // =============================================

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

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

            $Image = $newImage;
        }

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

        $sql = "UPDATE slider SET Image = ? WHERE id = ?";

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

        mysqli_stmt_bind_param(
            $stmt,
            "si",
            $Image,
            $id
        );

        mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

        // =============================================
        // DELETE OLD IMAGE AFTER SUCCESSFUL UPDATE
        // =============================================

        if ($oldImage !== $Image) {

            deleteOldSliderImage(
                $oldImage,
                $id,
                $con,
                $uploadDir
            );
        }

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

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

    } catch (Throwable $e) {

        // Remove newly uploaded image if update failed
        if ($newImage !== null) {

            $filePath = $uploadDir . $newImage;

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

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

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


// =============================================
// 10. PREPARE SAFE IMAGE URL
// =============================================

$existingImageUrl = null;

if (
    !empty($row['Image']) &&
    basename($row['Image']) === $row['Image'] &&
    preg_match(
        '/\A[a-zA-Z0-9._-]+\.(jpg|jpeg|png|webp)\z/i',
        $row['Image']
    )
) {
    $existingImageUrl = "./assets/images/slider/" .
        rawurlencode($row['Image']);
}

// =============================================
// 11. ADMIN HEADER
// =============================================

include("header.php");

?>

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

<head>

    <meta charset="utf-8">

    <title>Slider Update</title>

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

    <meta name="description" content="Update slider image">

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


    <!-- Plugins CSS -->

    <link href="assets/libs/dropzone/dropzone.css"
        rel="stylesheet"
        type="text/css">

    <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"
        type="text/css">


    <!-- Icons CSS -->

    <link href="assets/css/icons.min.css"
        rel="stylesheet"
        type="text/css">


    <!-- App CSS -->

    <link href="assets/css/app.min.css"
        id="app-style"
        rel="stylesheet"
        type="text/css">


    <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'] {
            display: none;
        }

        #upload {
            cursor: pointer;
        }

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

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

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

    </style>

</head>


<body data-sidebar="dark">


    <!-- BEGIN PAGE -->

    <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">
                                    SLIDER UPDATE
                                </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; ?>


                                        <!-- IMAGE UPLOAD -->

                                        <div class="dropzone upload-area">

                                            <div class="fallback">

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

                                            </div>


                                            <div
                                                class="dz-message needsclick"
                                                id="upload">

                                                <div class="mb-3">

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

                                                </div>

                                                <h4>
                                                    Drop files here or click to upload.
                                                </h4>

                                                <p class="text-muted">
                                                    JPG, PNG and WEBP only. Maximum 5 MB.
                                                </p>

                                            </div>

                                        </div>


                                        <!-- IMAGE PREVIEW -->

                                        <div class="filepath">

                                            <?php if ($existingImageUrl): ?>

                                                <img
                                                    id="previewImg"
                                                    src="<?php echo htmlspecialchars(
                                                        $existingImageUrl,
                                                        ENT_QUOTES,
                                                        'UTF-8'
                                                    ); ?>"
                                                    alt="Current slider image">

                                            <?php else: ?>

                                                <img
                                                    id="previewImg"
                                                    src=""
                                                    alt="Current slider image"
                                                    style="display:none;">

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

                                            <?php endif; ?>


                                            <br><br>

                                            <span id="filename">

                                                <?php echo htmlspecialchars(
                                                    $row['Image'] ?? '',
                                                    ENT_QUOTES,
                                                    'UTF-8'
                                                ); ?>

                                            </span>

                                        </div>


                                        <br>


                                        <!-- BUTTONS -->

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

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

                                                Update

                                            </button>


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

                                                View Data

                                            </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/js/app.js"></script>


    <!-- IMAGE PREVIEW -->

    <script>

        const imgInput = document.getElementById("imageInput");

        const uploadBox = document.getElementById("upload");

        const previewImg = document.getElementById("previewImg");

        const filenameSpan = document.getElementById("filename");

        let previewURL = null;


        // Open file selector

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

            imgInput.click();

        });


        // Preview image

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

            if (previewURL) {

                URL.revokeObjectURL(previewURL);

                previewURL = null;

            }

            if (imgInput.files.length > 0) {

                const file = imgInput.files[0];

                const allowedTypes = [
                    "image/jpeg",
                    "image/png",
                    "image/webp"
                ];

                // Validate image type
                if (!allowedTypes.includes(file.type)) {

                    alert("Only JPG, PNG and WEBP images are allowed.");

                    imgInput.value = "";

                    return;

                }

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

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

                    imgInput.value = "";

                    return;

                }

                // Preview
                previewURL = URL.createObjectURL(file);

                previewImg.src = previewURL;

                previewImg.style.display = "inline-block";

                filenameSpan.textContent = file.name;

            }

        });

    </script>


</body>

</html>
