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

            // Generate favicon images
            $faviconPath = $uploadDir . 'favicon.ico';
            $favicon32 = $uploadDir . 'favicon-32x32.png';
            $favicon16 = $uploadDir . 'favicon-16x16.png';

            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, $favicon32); // 32x32 PNG
                imagepng($faviconOutput, $favicon16); // 16x16 PNG
                imagepng($faviconOutput, $faviconPath); // 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));

            $uploadFile = $uploadDir . $sanitizedFileName . '.' . $imageFileType;

            if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $uploadFile)) {
                echo "File " . $sanitizedFileName . " uploaded successfully.<br>";

                $validImageTypes = ['jpeg', 'jpg', 'png', 'gif', 'bmp', 'webp'];
                if (!in_array($imageFileType, $validImageTypes)) {
                    echo "Unsupported file type for " . $sanitizedFileName . ". Only images are accepted.<br>";
                    continue;
                }

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

                switch ($imageFileType) {
                    case 'jpeg':
                    case 'jpg':
                        $image = imagecreatefromjpeg($uploadFile);
                        break;
                    case 'png':
                        $image = imagecreatefrompng($uploadFile);
                        break;
                    case 'gif':
                        $image = imagecreatefromgif($uploadFile);
                        break;
                    case 'bmp':
                        $image = imagecreatefrombmp($uploadFile);
                        break;
                    case 'webp':
                        $image = imagecreatefromwebp($uploadFile);
                        break;
                }

                if ($image) {
                    if (imagewebp($image, $webpFile)) {
                        echo "File " . $sanitizedFileName . " converted to WebP format successfully.<br>";

                        $dbFileName = $sanitizedFileName . '.webp';

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