<?php

// Check if image file and width parameters are provided
if (isset($_GET['fileType']) && isset($_GET['fileName']) && isset($_GET['width'])) {
    
    // Get the parameters from the URL
    $fileType = strtolower($_GET['fileType']);
    $fileName = $_GET['fileName'];
    $desiredWidth = $_GET['width'];

    // Validate fileType
    if ($fileType !== 'jpg' && $fileType !== 'webp') {
        echo 'Invalid file type. Only JPG and WebP are supported.';
        exit;
    }

    // Construct image path
    $imagePath = "media/images/{$fileName}.{$fileType}";

    // Validate image file
    if (file_exists($imagePath)) {

        // Load image based on file type
        if ($fileType === 'webp') {
            $image = new Gmagick($imagePath);
            $originalWidth = $image->getimagewidth();
            $originalHeight = $image->getimageheight();
        } else {
            $image = imagecreatefromjpeg($imagePath);
            $originalWidth = imagesx($image);
            $originalHeight = imagesy($image);
        }

        // Calculate the new height while maintaining the aspect ratio
        $aspectRatio = $originalWidth / $originalHeight;
        $newHeight = $desiredWidth / $aspectRatio;

        // Resize the image
        if ($fileType === 'webp') {
            $image->resizeimage($desiredWidth, $newHeight, Gmagick::FILTER_LANCZOS, 1);
        } else {
            $resizedImage = imagecreatetruecolor($desiredWidth, $newHeight);
            imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $desiredWidth, $newHeight, $originalWidth, $originalHeight);
            $image = $resizedImage;
        }

        // Output the resized image to the browser
        header('Content-Type: image/' . ($fileType === 'jpg' ? 'jpeg' : 'webp'));
        if ($fileType === 'webp') {
            echo $image->getimageblob();
            $image->destroy();
        } else {
            imagejpeg($image);
            imagedestroy($image);
        }

    } else {
        // Invalid image file
        echo 'Invalid image file.';
    }

} else {
    // Parameters not provided
    echo 'Please provide image and width parameters in the URL.';
}

?>
