<?php
$config = require __DIR__ . '/config.php';

$album = $_GET['a'] ?? '';
$photo = $_GET['p'] ?? '';
$size  = $_GET['s'] ?? 'md';

if (!preg_match('/^[\w\-. ]+$/u', $album) || !preg_match('/^[\w\-. ]+\.(jpe?g|png|gif|webp)$/iu', $photo)) {
    http_response_code(400); exit('bad request');
}
if (!isset($config['thumb_sizes'][$size])) { http_response_code(400); exit('bad size'); }

$src = $config['photos_dir'] . '/' . $album . '/' . $photo;
if (!file_exists($src)) { http_response_code(404); exit('not found'); }

$w = $config['thumb_sizes'][$size];
$cacheDir = $config['thumbs_dir'] . '/' . $album;
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0755, true);

$cacheFile = $cacheDir . '/' . $size . '_' . $photo;
if (preg_match('/\.(png|gif|webp)$/i', $cacheFile)) {
    $cacheFile = preg_replace('/\.(png|gif|webp)$/i', '.jpg', $cacheFile);
}

if (file_exists($cacheFile) && filemtime($cacheFile) >= filemtime($src)) {
    header('Content-Type: image/jpeg');
    header('Cache-Control: public, max-age=31536000');
    readfile($cacheFile); exit;
}

$info = getimagesize($src);
if (!$info) { http_response_code(500); exit('bad image'); }

switch ($info[2]) {
    case IMAGETYPE_JPEG: $img = imagecreatefromjpeg($src); break;
    case IMAGETYPE_PNG:  $img = imagecreatefrompng($src);  break;
    case IMAGETYPE_GIF:  $img = imagecreatefromgif($src);  break;
    case IMAGETYPE_WEBP: $img = imagecreatefromwebp($src); break;
    default: http_response_code(500); exit('unsupported');
}

$srcW = imagesx($img);
$srcH = imagesy($img);
$ratio = $srcH / $srcW;
$newW = min($w, $srcW);
$newH = (int)round($newW * $ratio);

$dst = imagecreatetruecolor($newW, $newH);
imagecopyresampled($dst, $img, 0, 0, 0, 0, $newW, $newH, $srcW, $srcH);

imagejpeg($dst, $cacheFile, $config['jpeg_quality']);
header('Content-Type: image/jpeg');
header('Cache-Control: public, max-age=31536000');
imagejpeg($dst, null, $config['jpeg_quality']);
imagedestroy($img); imagedestroy($dst);
