<?php
/*
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
*/

// Extract filename and dimensions from the URL
if (isset($_SERVER['REQUEST_URI'])) {
    $url = basename($_SERVER['REQUEST_URI'], '.webp');
    if (str_contains($url,'og')) {
        $filename = $url;
        
        $filename = str_replace("-og","",$filename);
        $isOriginal = true;
    } else {
        
        list($filename, $dimensions) = explode('-', $url);
        list($width, $height) = explode('x', $dimensions);
        $isOriginal = false;
        
        
    }
} else {
    header("HTTP/1.0 404 Not Found");
    die("Invalid request.");
}

// Define the path to the images folder
$imagePath = __DIR__ . '/images/' . $filename . '.webp'; // Assuming images are in JPG format




// Check if the image file exists
if (!file_exists($imagePath)) {
    header("HTTP/1.0 404 Not Found");
    include_once('404.php');
    die();
}

// Check if the request is for the original image
if ($isOriginal) {
    // Serve the original image directly
    header('Content-Type: image/webp');
    readfile($imagePath);
    exit;
}


// Create an image resource from the file
$image = imagecreatefromwebp($imagePath); // Change to imagecreatefrompng or other functions if needed
if (!$image) {
    header("HTTP/1.0 404 Not Found");
    echo ' did this brake?';
    include_once('404.php');
    die();
}

// Resize the image
$resizedImage = imagescale($image, $width, $height);
if (!$resizedImage) {
    header("HTTP/1.0 404 Not Found");
    include_once('404.php');
    die();
}

// Set the content type header
header('Content-Type: image/webp');

// Output the image in WebP format
imagewebp($resizedImage);

// Free up memory
imagedestroy($image);
imagedestroy($resizedImage);
?>
