<?php
// Define base path
$basePath = '/usr/home/btsvps1/public_html/baysidemarinecorp/';

// Get parameters safely
$src = $_GET['src'] ?? '';
$width = isset($_GET['width']) && is_numeric($_GET['width']) ? (int) $_GET['width'] : 0;
$height = isset($_GET['height']) && is_numeric($_GET['height']) ? (int) $_GET['height'] : 0;

// Define cache directory
$cacheDir = __DIR__ . '/cache/';

// Ensure cache directory exists
if (!is_dir($cacheDir) && !mkdir($cacheDir, 0755, true)) {
    http_response_code(500);
    exit("Error: Failed to create cache directory.");
}

// Sanitize file path to prevent directory traversal attacks
$src = str_replace(['../', '..\\'], '', $src);
$filePath = $basePath . ltrim($src, '/');

// Validate image existence
if (!file_exists($filePath) || !is_file($filePath)) {
    http_response_code(404);
    exit("Error: Image not found.");
}

// Generate cache filename
$cacheFile = $cacheDir . md5($src . $width . $height) . '.jpg';

// Serve cached image if available
if (file_exists($cacheFile)) {
    header("Content-Type: image/jpeg");
    header("Cache-Control: public, max-age=604800"); // Cache for 7 days
    readfile($cacheFile);
    exit;
}

// Get original image info
$info = getimagesize($filePath);
$mime = $info['mime'] ?? '';

// Load the original image
$imageCreateFunctions = [
    'image/jpeg' => 'imagecreatefromjpeg',
    'image/png'  => 'imagecreatefrompng',
    'image/gif'  => 'imagecreatefromgif'
];

if (!isset($imageCreateFunctions[$mime])) {
    http_response_code(415);
    exit("Error: Unsupported image format.");
}

$img = $imageCreateFunctions[$mime]($filePath);
if (!$img) {
    http_response_code(500);
    exit("Error: Failed to load image.");
}

// Get original dimensions
[$origWidth, $origHeight] = [$info[0], $info[1]];

// Auto-scale if width or height is zero
if ($width > 0 && $height == 0) {
    $height = (int) round(($width / $origWidth) * $origHeight);
} elseif ($height > 0 && $width == 0) {
    $width = (int) round(($height / $origHeight) * $origWidth);
} elseif ($width == 0 && $height == 0) {
    [$width, $height] = [$origWidth, $origHeight];
}

// Create resized image
$resized = imagecreatetruecolor($width, $height);

// Preserve transparency for PNG & GIF
if ($mime === 'image/png') {
    imagealphablending($resized, false);
    imagesavealpha($resized, true);
    $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
    imagefill($resized, 0, 0, $transparent);
} elseif ($mime === 'image/gif') {
    $transparentIndex = imagecolortransparent($img);
    if ($transparentIndex !== -1) {
        $transparentColor = imagecolorsforindex($img, $transparentIndex);
        $transparentIndex = imagecolorallocate($resized, $transparentColor['red'], $transparentColor['green'], $transparentColor['blue']);
        imagefill($resized, 0, 0, $transparentIndex);
        imagecolortransparent($resized, $transparentIndex);
    }
}

// High-quality resize
imagecopyresampled($resized, $img, 0, 0, 0, 0, $width, $height, $origWidth, $origHeight);

// Save resized image to cache
if (!imagejpeg($resized, $cacheFile, 90)) {
    http_response_code(500);
    exit("Error: Failed to save resized image.");
}

// Serve the resized image
header("Content-Type: image/jpeg");
header("Cache-Control: public, max-age=604800"); // Cache for 7 days
readfile($cacheFile);

// Cleanup
imagedestroy($img);
imagedestroy($resized);
?>
