<?php
use CAE\Lib\Response;

$url = $_GET['url'] ?? '';

if (empty($url)) {
    Response::error('URL is required');
}

// Validate URL
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    Response::error('Invalid URL');
}

try {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    
    $data = curl_exec($ch);
    $info = curl_getinfo($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($data === false) {
        throw new Exception("CURL Error: " . $error);
    }

    $contentType = $info['content_type'] ?? 'image/jpeg';
    
    // Check if it's actually an image
    if (!str_starts_with($contentType, 'image/')) {
        throw new Exception("URL is not a valid image. Content-Type: " . $contentType);
    }

    header("Content-Type: " . $contentType);
    echo $data;
    exit;

} catch (Exception $e) {
    Response::error($e->getMessage());
}
