<?php
// manager/pos/get_image.php
// Simple on-the-fly thumbnail generator with caching

$filename = $_GET['f'] ?? '';
$width = intval($_GET['w'] ?? 200);

if (!$filename) {
    exit;
}

// Security: Prevent directory traversal
$filename = basename($filename);

$source_dir = '../../img/products/';
$cache_dir = '../../img/cache/';
$source_path = $source_dir . $filename;
$cache_filename = "thumb_{$width}_{$filename}";
$cache_path = $cache_dir . $cache_filename;

// If source doesn't exist, return 404
if (!file_exists($source_path)) {
    header("HTTP/1.0 404 Not Found");
    exit;
}

// Create cache dir if not exists
if (!file_exists($cache_dir)) {
    mkdir($cache_dir, 0777, true);
}

// If cache exists and is newer than source, serve cache
if (file_exists($cache_path) && filemtime($cache_path) >= filemtime($source_path)) {
    $info = getimagesize($cache_path);
    header("Content-Type: " . $info['mime']);
    readfile($cache_path);
    exit;
}

// Generate Thumbnail
$info = getimagesize($source_path);
if (!$info) {
    exit; // Not an image
}

$mime = $info['mime'];
$src_w = $info[0];
$src_h = $info[1];

// Calculate new height
$height = floor($src_h * ($width / $src_w));

// Create source image resource
switch ($mime) {
    case 'image/jpeg':
        $src = imagecreatefromjpeg($source_path);
        break;
    case 'image/png':
        $src = imagecreatefrompng($source_path);
        break;
    case 'image/gif':
        $src = imagecreatefromgif($source_path);
        break;
    case 'image/webp':
        $src = imagecreatefromwebp($source_path);
        break;
    default:
        exit;
}

if (!$src)
    exit;

// Create destination image
$dst = imagecreatetruecolor($width, $height);

// Handle transparency for PNG/WEBP/GIF
if ($mime == 'image/png' || $mime == 'image/webp' || $mime == 'image/gif') {
    imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
    imagealphablending($dst, false);
    imagesavealpha($dst, true);
}

// Resize
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $src_w, $src_h);

// Save to cache
switch ($mime) {
    case 'image/jpeg':
        imagejpeg($dst, $cache_path, 80);
        break; // 80% quality
    case 'image/png':
        imagepng($dst, $cache_path, 8);
        break;
    case 'image/gif':
        imagegif($dst, $cache_path);
        break;
    case 'image/webp':
        imagewebp($dst, $cache_path, 80);
        break;
}

// Output
header("Content-Type: $mime");
switch ($mime) {
    case 'image/jpeg':
        imagejpeg($dst, null, 80);
        break;
    case 'image/png':
        imagepng($dst, null, 8);
        break;
    case 'image/gif':
        imagegif($dst);
        break;
    case 'image/webp':
        imagewebp($dst, null, 80);
        break;
}

imagedestroy($src);
imagedestroy($dst);
