<?php
// File: image_proxy.php
if (!isset($_GET['url']) || empty($_GET['url'])) { http_response_code(400); die("URL gambar tidak diberikan."); }

$image_url = $_GET['url'];
if (!preg_match('#^https?://#i', $image_url)) { http_response_code(400); die("URL tidak valid."); }

$image_data = FALSE;
$mime_type = 'application/octet-stream';

if (extension_loaded('curl')) {
    // Metode 1: Menggunakan cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $image_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $image_data = curl_exec($ch);
    if (!curl_errno($ch)) {
        $mime_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    }
    curl_close($ch);
} elseif (ini_get('allow_url_fopen')) {
    // Metode 2: Menggunakan file_get_contents
    $image_data = @file_get_contents($image_url);
}

if ($image_data === FALSE) {
    http_response_code(500);
    die("Gagal mengambil gambar. Periksa ekstensi PHP cURL atau konfigurasi allow_url_fopen."); 
}

if ($mime_type == 'application/octet-stream' && class_exists('finfo')) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime_type = $finfo->buffer($image_data);
}

header('Access-Control-Allow-Origin: *');
header('Cache-Control: public, max-age=31536000'); 
if (in_array($mime_type, ['image/jpeg', 'image/png', 'image/gif', 'image/webp'])) {
    header("Content-Type: " . $mime_type);
} else {
    header("Content-Type: image/jpeg");
}
echo $image_data;
?>