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


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

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

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

    // Maximum file 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 genuine uploaded file
    if (!is_uploaded_file($file['tmp_name'])) {
        throw new RuntimeException("Invalid uploaded file.");
    }

    // Verify image contents
    $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, JPEG 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(
            "Image processing is not available on the server."
        );
    }

    // Read and re-encode the image
    $imageData = file_get_contents($file['tmp_name']);

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

    $image = imagecreatefromstring($imageData);

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

    // Preserve transparency
    imagepalettetotruecolor($image);
    imagealphablending($image, false);
    imagesavealpha($image, true);

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

    // Generate unpredictable 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 uploaded image.");
    }

    return $fileName;
}


// ========================================
// 4. HANDLE FORM SUBMISSION
// ========================================

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

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

    $savedFiles = [];

    try {

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

        // Desktop image is compulsory
        if (
            !isset($_FILES['Image']) ||
            $_FILES['Image']['error'] !== UPLOAD_ERR_OK
        ) {
            throw new RuntimeException(
                "Please upload Desktop Slider image."
            );
        }

        // Upload desktop image
        $Image = saveSliderImage(
            $_FILES['Image'],
            'desktop_',
            $uploadDir
        );

        $savedFiles[] = $Image;

        // Mobile image is optional
        $PImage = null;

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

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

            $savedFiles[] = $PImage;
        }

        // ========================================
        // 5. INSERT INTO DATABASE
        // ========================================

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

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

        mysqli_stmt_bind_param(
            $stmt,
            "ss",
            $Image,
            $PImage
        );

        mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

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

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

    } catch (Throwable $e) {

        // Remove uploaded files if database insertion fails
        foreach ($savedFiles as $fileName) {

            $filePath = $uploadDir . $fileName;

            if (is_file($filePath)) {
                unlink($filePath);
            }
        }

        // Log technical errors
        error_log("Slider Upload Error: " . $e->getMessage());

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

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 content="Premium Multipurpose Admin & Dashboard Template" name="description" />

    <meta content="Themesbrand" name="author" />

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

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

    <link rel="stylesheet"
        type="text/css"
        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'],
        input[name='PImage'] {
            display: none;
        }

        div#upload {
            cursor: pointer;
        }

        ::-webkit-file-upload-button {
            display: none;
        }

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

        img[alt="img"] {
            width: clamp(50px, 15%, 100px);
            aspect-ratio: 1/0.70;
        }

        .upload-btn {
            cursor: pointer;
        }

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

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

    </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">

                                    <div>

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


                                            <div class="row">

                                                <!-- DESKTOP SLIDER -->

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

                                                    <h5>Desktop Slider</h5>

                                                    <div class="dropzone">

                                                        <div class="fallback">

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

                                                        </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>
                                                                Drop files here or click to upload.
                                                            </h4>

                                                        </div>

                                                    </div>


                                                    <!-- DESKTOP PREVIEW -->

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

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

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

                                                    </div>

                                                </div>


                                                <!-- PHONE SLIDER -->

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

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

                                                    <div class="dropzone">

                                                        <div class="fallback">

                                                            <input
                                                                placeholder="PImage"
                                                                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>
                                                                Drop files here or click to upload.
                                                            </h4>

                                                        </div>

                                                    </div>


                                                    <!-- PHONE PREVIEW -->

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

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

                                                        <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">

                                                    Submit

                                                </button>


                                                <a href="viewslider.php">

                                                    <button
                                                        type="button"
                                                        class="btn btn-danger">

                                                        View Data

                                                    </button>

                                                </a>

                                            </div>


                                        </form>

                                    </div>

                                </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 when upload area is clicked

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

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

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

                document.getElementById(inputId).click();

            });

        });


        // Image preview function

        function previewFile(inputId) {

            const input = document.getElementById(inputId);

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

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

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


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

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

                    const file = input.files[0];

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

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

                        input.value = "";

                        previewBox.style.display = "none";

                        return;
                    }

                    // Preview selected image
                    fileNameSpan.textContent = file.name;

                    const objectURL = URL.createObjectURL(file);

                    imgTag.src = objectURL;

                    previewBox.style.display = "block";

                    imgTag.onload = function() {
                        URL.revokeObjectURL(objectURL);
                    };

                } else {

                    previewBox.style.display = "none";

                }

            });

        }


        // Apply preview to both inputs

        previewFile("Image");

        previewFile("PImage");

    </script>


</body>

</html>
