<?php
// Include the config file for DB connection
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['images'])) {
    $uploadDir = 'images/';

    // Get user inputs for heading and type
    $heading = !empty($_POST['heading']) ? $_POST['heading'] : 'Gallery'; // Default to 'Gallery' if not provided
    $type = !empty($_POST['type']) ? $_POST['type'] : 'Gallery'; // Default to 'Gallery' if not provided

    // Get and sanitize the file name
    $originalFileName = pathinfo($_FILES['images']['name'], PATHINFO_FILENAME);
    $sanitizedFileName = preg_replace("/[^a-zA-Z0-9]/", "", $originalFileName); // Only alphanumeric characters

    // Set the upload path
    $uploadFile = $uploadDir . $sanitizedFileName . '.' . strtolower(pathinfo($_FILES['images']['name'], PATHINFO_EXTENSION));
    $imageFileType = strtolower(pathinfo($uploadFile, PATHINFO_EXTENSION));

    // File name to be stored in the database (filename-og.webp)
    $dbFileName = $sanitizedFileName . '-og.webp';

    // Check if the file is already a WebP image
    if ($imageFileType == 'webp') {
        if (move_uploaded_file($_FILES['images']['tmp_name'], $uploadFile)) {
            echo "WebP file " . $sanitizedFileName . " uploaded successfully.<br>";

            // Insert into the database as filename-og.webp
            $stmt = $pdo->prepare("INSERT INTO `gallery_photo` (`img`, `heading`, `type`) VALUES (?, ?, ?)");
            $stmt->execute([$dbFileName, $heading, $type]);
        } else {
            echo "Failed to upload WebP file " . $sanitizedFileName . ".<br>";
        }
    } else {
        // Check if the file is an image (for non-WebP images)
        $check = getimagesize($_FILES['images']['tmp_name']);
        if ($check === false) {
            echo "File " . $sanitizedFileName . " is not a valid image.<br>";
            return;
        }

        // Move the uploaded file to the images directory
        if (move_uploaded_file($_FILES['images']['tmp_name'], $uploadFile)) {
            // Convert the image to WebP format
            $webpFile = $uploadDir . $sanitizedFileName . '.webp'; // Store it as filename.webp

            // Determine image type and create from respective format
            switch ($imageFileType) {
                case 'jpeg':
                case 'jpg':
                    $image = imagecreatefromjpeg($uploadFile);
                    break;
                case 'png':
                    $image = imagecreatefrompng($uploadFile);
                    break;
                default:
                    echo "Unsupported file type for " . $sanitizedFileName . ".<br>";
                    return;
            }

            // Save the image in WebP format
            if (imagewebp($image, $webpFile)) {
                echo "File " . $sanitizedFileName . " uploaded and converted to WebP format successfully.<br>";

                // Insert the converted WebP file into the database as filename-og.webp
                $stmt = $pdo->prepare("INSERT INTO `gallery_photo` (`img`, `heading`, `type`) VALUES (?, ?, ?)");
                $stmt->execute([$dbFileName, $heading, $type]);
            } else {
                echo "Failed to convert " . $sanitizedFileName . " to WebP format.<br>";
            }

            // Free up memory
            imagedestroy($image);
        } else {
            echo "Failed to upload file " . $sanitizedFileName . ".<br>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload and Convert Images</title>
</head>
<body>
    <form action="" method="post" enctype="multipart/form-data">
        <label for="images">Select image to upload:</label>
        <input type="file" name="images" id="images" accept=".jpeg,.jpg,.png,.webp"><br><br>

        <label for="heading">Heading:</label>
        <input type="text" name="heading" id="heading" placeholder="Enter heading (default is Gallery)"><br><br>

        <label for="type">Type:</label>
        <select name="type" id="type">
            <option value="Gallery">Gallery</option>
            <option value="Food Page">Food Page</option>
        </select><br><br>

        <input type="submit" value="Upload Image">
    </form>
</body>
</html>
