<?php
declare(strict_types=1);

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

ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');

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. CSRF TOKEN
// =============================================

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

$error = '';


// =============================================
// 5. SECURE IMAGE UPLOAD FUNCTION
// =============================================

function uploadSliderImage(array $file, string $uploadDir): string
{
    // Check upload error
    if (
        !isset($file['error']) ||
        $file['error'] !== UPLOAD_ERR_OK
    ) {
        throw new RuntimeException("Please select a valid image.");
    }

    // Maximum size 5 MB
    $maxSize = 5 * 1024 * 1024;

    if ($file['size'] <= 0 || $file['size'] > $maxSize) {
        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("Uploaded file is not a valid image.");
    }

    // 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 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 (!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 as WebP
    $saved = imagewebp($image, $destination, 85);

    imagedestroy($image);

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

    return $fileName;
}


// =============================================
// 6. HANDLE FORM SUBMISSION
// =============================================

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

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

    $uploadedImage = 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."
            );
        }

        // Check image selection
        if (
            !isset($_FILES['Image']) ||
            $_FILES['Image']['error'] === UPLOAD_ERR_NO_FILE
        ) {
            throw new RuntimeException("Please select a slider image.");
        }

        // Upload and validate image
        $uploadedImage = uploadSliderImage(
            $_FILES['Image'],
            $uploadDir
        );

        // =============================================
        // 7. INSERT USING PREPARED STATEMENT
        // =============================================

        $sql = "INSERT INTO slider (Image) VALUES (?)";

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

        mysqli_stmt_bind_param(
            $stmt,
            "s",
            $uploadedImage
        );

        mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

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

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

    } catch (Throwable $e) {

        // Remove uploaded image if database insert fails
        if ($uploadedImage !== null) {

            $filePath = $uploadDir . $uploadedImage;

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

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

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


// =============================================
// 8. ADMIN HEADER
// =============================================

include("header.php");

?>

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

<head>

    <meta charset="utf-8">

    <title>ADD Slider</title>

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

    <meta name="description" content="Add 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: none;
            margin-top: 15px;
        }

        .filepath img {
            width: 150px;
            max-height: 120px;
            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">
                                    ADD SLIDER
                                </h4>

                            </div>

                        </div>

                    </div>


                    <!-- FORM SECTION -->

                    <div class="row">

                        <div class="col-12">

                            <div class="card">

                                <div class="card-body">


                                    <form
                                        class="form"
                                        action=""
                                        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
                                                    name="Image"
                                                    id="Image"
                                                    type="file"
                                                    accept="image/jpeg,image/png,image/webp"
                                                    required>

                                            </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"
                                            id="image-preview">

                                            <img
                                                src=""
                                                alt="Slider image preview">

                                            <br>

                                            <span id="filename"></span>

                                        </div>


                                        <br>


                                        <!-- BUTTONS -->

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

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

                                                Submit

                                            </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/libs/dropzone/dropzone-min.js"></script>

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


    <!-- IMAGE UPLOAD PREVIEW -->

    <script>

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

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

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

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

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

        let previewURL = null;


        // Open file selector

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

            imageInput.click();

        });


        // Image preview

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

            if (previewURL) {

                URL.revokeObjectURL(previewURL);

                previewURL = null;

            }

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

                const file = imageInput.files[0];

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

                // Check file type in browser
                if (!allowedTypes.includes(file.type)) {

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

                    imageInput.value = "";

                    previewBox.style.display = "none";

                    return;

                }

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

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

                    imageInput.value = "";

                    previewBox.style.display = "none";

                    return;

                }

                fileName.textContent = file.name;

                previewURL = URL.createObjectURL(file);

                previewImage.src = previewURL;

                previewBox.style.display = "block";

            } else {

                previewBox.style.display = "none";

            }

        });

    </script>


</body>

</html>
