<?php
// image_optimize.php?src=images/originals/hero-1.jpg&w=1600
$src = $_GET['src'] ?? '';
$width = (int)($_GET['w'] ?? 1600);

if (!$src || !file_exists($src)) {
    http_response_code(404);
    exit("Image not found.");
}

// cache folder
$cacheDir = __DIR__ . "/.cache_images/";
if (!is_dir($cacheDir)) {
    mkdir($cacheDir, 0755, true);
}

$hash = md5($src.$width);
$cachedFile = $cacheDir . $hash . ".webp";

// if cached, serve directly
if (file_exists($cachedFile)) {
    header("Content-Type: image/webp");
    readfile($cachedFile);
    exit;
}

// Load image
$info = getimagesize($src);
$mime = $info['mime'];

switch ($mime) {
    case 'image/jpeg':
        $image = imagecreatefromjpeg($src);
        break;
    case 'image/png':
        $image = imagecreatefrompng($src);
        break;
    case 'image/webp':
        $image = imagecreatefromwebp($src);
        break;
    default:
        http_response_code(415);
        exit("Unsupported image type.");
}

// Resize
$origWidth = imagesx($image);
$origHeight = imagesy($image);
$newHeight = intval(($width / $origWidth) * $origHeight);

$resized = imagecreatetruecolor($width, $newHeight);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $newHeight, $origWidth, $origHeight);

// Save WebP to cache
imagewebp($resized, $cachedFile, 75);

// Serve
header("Content-Type: image/webp");
readfile($cachedFile);

// Clean up
imagedestroy($image);
imagedestroy($resized);
?>
