<?php
declare(strict_types=1);

function optimizeAndSaveImage(string $sourcePath, string $destinationPath, int $maxWidth = 1920, int $quality = 85): bool
{
    if (!file_exists($sourcePath) || !is_readable($sourcePath)) {
        error_log("ImageOptimizer: Source file not found or unreadable: " . $sourcePath);
        return false;
    }

    $imageInfo = @getimagesize($sourcePath);
    if ($imageInfo === false) {
        error_log("ImageOptimizer: Failed to get image info: " . $sourcePath);
        return false;
    }
    
    $imageType = $imageInfo[2];
    $originalWidth = $imageInfo[0];
    $originalHeight = $imageInfo[1];

    // Ensure quality is within valid WebP range
    $quality = max(0, min(100, $quality));

    $image = null;
    $newImage = null;

    try {
        switch ($imageType) {
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($sourcePath);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($sourcePath);
                break;
            case IMAGETYPE_WEBP:
                $image = imagecreatefromwebp($sourcePath);
                break;
            case IMAGETYPE_GIF:
                error_log("ImageOptimizer: GIF format not supported for WebP conversion.");
                return false; 
            default:
                error_log("ImageOptimizer: Unsupported image type: " . $imageType);
                return false;
        }

        if (!$image) {
            error_log("ImageOptimizer: Failed to create image resource.");
            return false;
        }

        $newWidth = $originalWidth;
        $newHeight = $originalHeight;

        if ($originalWidth > $maxWidth) {
            $ratio = $originalWidth / $originalHeight;
            $newWidth = $maxWidth;
            $newHeight = (int)($newWidth / $ratio);
        }

        $newImage = imagecreatetruecolor($newWidth, $newHeight);

        if ($imageType === IMAGETYPE_PNG || $imageType === IMAGETYPE_WEBP) {
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
        }
        
        imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
        
        $destinationDir = dirname($destinationPath);
        if (!is_dir($destinationDir)) {
            if (!mkdir($destinationDir, 0755, true)) {
                error_log("ImageOptimizer: Failed to create directory: " . $destinationDir);
                return false;
            }
        }

        return imagewebp($newImage, $destinationPath, $quality);

    } catch (Throwable $e) {
        error_log("ImageOptimizer Exception: " . $e->getMessage());
        return false;
    } finally {
        if ($image instanceof GdImage) {
            imagedestroy($image);
        }
        if ($newImage instanceof GdImage) {
            imagedestroy($newImage);
        }
    }
}
?>