<?php
/* Fast thumbnail/cache endpoint: reduces heavy PNG/JPG/WebP images for product grids */
$src = isset($_GET['src']) ? trim($_GET['src']) : '';
$w = isset($_GET['w']) ? (int)$_GET['w'] : 360;
$h = isset($_GET['h']) ? (int)$_GET['h'] : 360;
$fit = isset($_GET['fit']) ? $_GET['fit'] : 'contain';
if($w<20)$w=360; if($h<20)$h=360; if($w>1600)$w=1600; if($h>1600)$h=1600;
$base = __DIR__;
$fallback = $base.'/assets/images/products/no-image.svg';
function out_svg($file){ header('Content-Type:image/svg+xml'); readfile($file); exit; }
if($src==='' || preg_match('/\.svg(\?.*)?$/i',$src)) out_svg($fallback);
$cacheDir = $base.'/cache/thumbs';
if(!is_dir($cacheDir)) @mkdir($cacheDir,0777,true);
$key = sha1($src.'|'.$w.'|'.$h.'|'.$fit);
$cache = $cacheDir.'/'.$key.'.webp';
if(is_file($cache) && filesize($cache)>100){ header('Content-Type:image/webp'); header('Cache-Control: public, max-age=2592000'); readfile($cache); exit; }
$data = false;
if(preg_match('#^https?://#i',$src)){
    if(function_exists('curl_init')){
        $ch=curl_init($src); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); curl_setopt($ch,CURLOPT_TIMEOUT,12); curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0'); $data=curl_exec($ch); $code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE); curl_close($ch); if($code>=400)$data=false;
    }
}else{
    $src = str_replace('\\','/',$src); $src = ltrim($src,'/');
    if(strpos($src,'../')!==false) out_svg($fallback);
    $file = $base.'/'.$src;
    if(is_file($file)) $data = file_get_contents($file);
}
if(!$data || strlen($data)<100) out_svg($fallback);
if(!function_exists('imagecreatefromstring')){ header('Content-Type:image/jpeg'); echo $data; exit; }
$im = @imagecreatefromstring($data); if(!$im) out_svg($fallback);
$sw=imagesx($im); $sh=imagesy($im);
$canvas=imagecreatetruecolor($w,$h); imagesavealpha($canvas,true); $trans=imagecolorallocatealpha($canvas,255,255,255,127); imagefill($canvas,0,0,$trans);
if($fit==='cover') { $scale=max($w/$sw,$h/$sh); } else { $scale=min($w/$sw,$h/$sh); }
$nw=(int)max(1,round($sw*$scale)); $nh=(int)max(1,round($sh*$scale)); $dx=(int)(($w-$nw)/2); $dy=(int)(($h-$nh)/2);
imagecopyresampled($canvas,$im,$dx,$dy,0,0,$nw,$nh,$sw,$sh);
if(function_exists('imagewebp')){ imagewebp($canvas,$cache,76); header('Content-Type:image/webp'); header('Cache-Control: public, max-age=2592000'); readfile($cache); }
else { header('Content-Type:image/jpeg'); imagejpeg($canvas,null,78); }
imagedestroy($im); imagedestroy($canvas); exit;
?>
