<?php

require_once __DIR__ . '/classes/ImageHandler.php';

// Get parameters
$file = isset($_GET['file']) ? basename($_GET['file']) : '';
$width = isset($_GET['w']) ? (int)$_GET['w'] : 300;
$height = isset($_GET['h']) ? (int)$_GET['h'] : 300;

// Validate parameters
if (empty($file)) {
    header('HTTP/1.0 400 Bad Request');
    die('Error: File parameter required');
}

if ($width <= 0 || $width > 2000 || $height <= 0 || $height > 2000) {
    header('HTTP/1.0 400 Bad Request');
    die('Error: Invalid dimensions');
}

// Initialize ImageHandler
$imageHandler = new ImageHandler(__DIR__ . '/uploads');

// Check if original exists
$originalPath = __DIR__ . '/uploads/original/' . $file;
if (!file_exists($originalPath)) {
    header('HTTP/1.0 404 Not Found');
    die('Error: Original image not found');
}

// Generate variant if needed (cached check is done inside generateVariant)
$variantName = "{$width}x{$height}";
$variant = $imageHandler->generateVariant($file, $width, $height, $variantName);

if (!$variant) {
    header('HTTP/1.0 500 Internal Server Error');
    die('Error: Failed to resize image');
}

// Get full path to variant
$variantPath = __DIR__ . '/uploads/variants/' . $variant;

if (!file_exists($variantPath)) {
    header('HTTP/1.0 500 Internal Server Error');
    die('Error: Variant file not found after generation');
}

// Get image type
$imageInfo = @getimagesize($variantPath);
if (!$imageInfo) {
    header('HTTP/1.0 500 Internal Server Error');
    die('Error: Invalid image file');
}

$imageType = $imageInfo[2];

// Set appropriate content type header
switch ($imageType) {
    case IMAGETYPE_JPEG:
        header('Content-Type: image/jpeg');
        break;
    case IMAGETYPE_PNG:
        header('Content-Type: image/png');
        break;
    default:
        header('Content-Type: application/octet-stream');
}

// Set cache headers for browser caching
$maxAge = 86400 * 30; // Cache for 30 days
header('Cache-Control: public, max-age=' . $maxAge);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $maxAge) . ' GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($variantPath)) . ' GMT');

// Set content length
header('Content-Length: ' . filesize($variantPath));

// Serve the file
readfile($variantPath);
exit;
?>
