<?php
// image_proxy.php - Safe image proxy
$image_path = $_GET['path'] ?? '';

// Security validation
if (empty($image_path)) {
    http_response_code(400);
    die('Image path required');
}

// Only allow image files
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
$extension = strtolower(pathinfo($image_path, PATHINFO_EXTENSION));

if (!in_array($extension, $allowed_extensions)) {
    http_response_code(403);
    die('Invalid file type');
}

// Prevent directory traversal
if (strpos($image_path, '..') !== false || strpos($image_path, '//') !== false) {
    http_response_code(403);
    die('Invalid path');
}

// Construct full path
$full_path = __DIR__ . '/uploads/images/' . basename($image_path);

// Check if file exists and is readable
if (!file_exists($full_path) || !is_readable($full_path)) {
    http_response_code(404);
    die('Image not found');
}

// Set appropriate headers
$mime_types = [
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png' => 'image/png',
    'gif' => 'image/gif',
    'webp' => 'image/webp',
    'svg' => 'image/svg+xml'
];

header('Content-Type: ' . ($mime_types[$extension] ?? 'image/jpeg'));
header('Cache-Control: max-age=2592000, public');
header('Access-Control-Allow-Origin: *');
header('Content-Length: ' . filesize($full_path));

// Output image
readfile($full_path);
?>