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

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

    // Handle Favicon Generation
    if (isset($_FILES['favicon_image']) && $_FILES['favicon_image']['error'] == UPLOAD_ERR_OK) {
        $faviconFile = $_FILES['favicon_image']['name'];
        $faviconTempPath = $_FILES['favicon_image']['tmp_name'];
        $faviconExt = strtolower(pathinfo($faviconFile, PATHINFO_EXTENSION));
        $validFaviconTypes = ['jpeg', 'jpg', 'png', 'webp'];

        if (in_array($faviconExt, $validFaviconTypes)) {
            $faviconImage = null;

            switch ($faviconExt) {
                case 'jpeg':
                case 'jpg':
                    $faviconImage = imagecreatefromjpeg($faviconTempPath);
                    break;
                case 'png':
                    $faviconImage = imagecreatefrompng($faviconTempPath);
                    break;
                case 'webp':
                    $faviconImage = imagecreatefromwebp($faviconTempPath);
                    break;
            }

            if ($faviconImage) {
                $faviconSize = 64; // Standard size for favicon
                $faviconOutput = imagecreatetruecolor($faviconSize, $faviconSize);

                imagesavealpha($faviconOutput, true);
                $transparency = imagecolorallocatealpha($faviconOutput, 0, 0, 0, 127);
                imagefill($faviconOutput, 0, 0, $transparency);

                imagecopyresampled($faviconOutput, $faviconImage, 0, 0, 0, 0, $faviconSize, $faviconSize, imagesx($faviconImage), imagesy($faviconImage));

                // Save favicon files
                imagepng($faviconOutput, $uploadDir . 'favicon-32x32.png'); // 32x32 PNG
                imagepng($faviconOutput, $uploadDir . 'favicon-16x16.png'); // 16x16 PNG
                imagewebp($faviconOutput, $uploadDir . 'favicon.ico'); // ICO format

                echo "Favicon files generated successfully.<br>";
                imagedestroy($faviconOutput);
            }

            imagedestroy($faviconImage);
        } else {
            echo "Invalid file type for favicon. Only JPEG, PNG, and WebP are allowed.<br>";
        }
    }

    // Handle Regular Image Uploads
    if (isset($_FILES['images'])) {
        // Get user inputs for heading, type, and the table to update
        $heading = !empty($_POST['heading']) ? $_POST['heading'] : 'Gallery';
        $type = !empty($_POST['type']) ? $_POST['type'] : 'Gallery';
        $table = !empty($_POST['table']) ? $_POST['table'] : 'gallery_photo';

        // Fetch the columns in the selected table
        $columnsQuery = $pdo->query("SHOW COLUMNS FROM `$table`");
        $columns = $columnsQuery->fetchAll(PDO::FETCH_COLUMN);

        foreach ($_FILES['images']['name'] as $key => $name) {
            $originalFileName = pathinfo($name, PATHINFO_FILENAME);
            $sanitizedFileName = preg_replace("/[^a-zA-Z0-9]/", "", $originalFileName);
            $imageFileType = strtolower(pathinfo($name, PATHINFO_EXTENSION));

            // Convert the image to WebP
            $webpFile = $uploadDir . $sanitizedFileName . '.webp';
            $image = null;

            // Load the image based on its type
            switch ($imageFileType) {
                case 'jpeg':
                case 'jpg':
                    $image = imagecreatefromjpeg($_FILES['images']['tmp_name'][$key]);
                    break;
                case 'png':
                    $image = imagecreatefrompng($_FILES['images']['tmp_name'][$key]);
                    break;
                case 'gif':
                    $image = imagecreatefromgif($_FILES['images']['tmp_name'][$key]);
                    break;
                case 'bmp':
                    $image = imagecreatefrombmp($_FILES['images']['tmp_name'][$key]);
                    break;
                case 'webp':
                    $image = imagecreatefromwebp($_FILES['images']['tmp_name'][$key]);
                    break;
                default:
                    echo "Unsupported file type for " . $sanitizedFileName . ". Only images are accepted.<br>";
                    continue;
            }

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

                $dbFileName = $sanitizedFileName . '.webp';

                // Update the database
                if (in_array('headingimg', $columns)) {
                    $stmt = $pdo->prepare("SELECT * FROM `$table` WHERE headingimg = ? LIMIT 1");
                    $stmt->execute([$heading]);
                    $existingData = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($existingData) {
                        $updates = [];
                        $updateValues = [];

                        if (in_array('headingimg', $columns) && $existingData['headingimg'] != $dbFileName) {
                            $updates[] = 'headingimg = ?';
                            $updateValues[] = $dbFileName;
                        }

                        if (!empty($updates)) {
                            $updateQuery = "UPDATE `$table` SET " . implode(', ', $updates) . " WHERE headingimg = ?";
                            $stmtUpdate = $pdo->prepare($updateQuery);
                            $updateValues[] = $heading;

                            $stmtUpdate->execute($updateValues);
                            echo "Image file names updated in the database.<br>";
                        }
                    } else {
                        echo "No existing entry found for heading " . $heading . ".<br>";
                    }
                }
            } else {
                echo "Failed to convert " . $sanitizedFileName . " to WebP format.<br>";
            }

            if ($image) {
                imagedestroy($image);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Images and Generate Favicon</title>
    <!-- Add Favicon Links -->
    <link rel="apple-touch-icon" sizes="180x180" href="images/favicon.ico">
    <link rel="icon" type="image/png" sizes="32x32" href="images/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="images/favicon-16x16.png">
</head>
<body>
    <form action="" method="post" enctype="multipart/form-data">
        <!-- Set the maximum file size (700 MB) -->
        <input type="hidden" name="MAX_FILE_SIZE" value="734003200">
        
        <h3>Upload Regular Images:</h3>
        <label for="images">Select images to upload:</label>
        <input type="file" name="images[]" id="images" accept=".jpeg,.jpg,.png,.webp,.gif,.bmp,.avif" multiple><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>

        <label for="table">Select Table:</label>
        <select name="table" id="table">
            <option value="gallery_photo">Gallery Photo</option>
            <option value="food_page">Food Page</option>
            <option value="festival_info">Festival Info</option>
            <option value="top">Destinations</option>
            <option value="about">About Us</option>
            <option value="home">Home</option>
        </select><br><br>

        <h3>Upload Favicon Image:</h3>
        <label for="favicon_image">Select favicon image:</label>
        <input type="file" name="favicon_image" id="favicon_image" accept=".jpeg,.jpg,.png,.webp"><br><br>

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