<?php
function drawCircleFocus(
    $img,
    $focusX,
    $focusY,
    $radius = 80,
    $zoom = 1.4,
    $circleX = null,
    $circleY = null
) {
    $imgW = imagesx($img);
    $imgH = imagesy($img);

    // Default circle position (left side)
    if ($circleX === null) $circleX = max($radius + 10, $focusX - 200);
    if ($circleY === null) $circleY = $focusY;

    $diameter = $radius * 2;

    // Create circle canvas
    $circle = imagecreatetruecolor($diameter, $diameter);
    imagealphablending($circle, false);
    imagesavealpha($circle, true);
    $transparent = imagecolorallocatealpha($circle, 0, 0, 0, 127);
    imagefill($circle, 0, 0, $transparent);

    // Copy & zoom focused area
    imagecopyresampled(
        $circle,
        $img,
        0,
        0,
        max(0, $focusX - ($radius / $zoom)),
        max(0, $focusY - ($radius / $zoom)),
        $diameter,
        $diameter,
        $diameter / $zoom,
        $diameter / $zoom
    );

    // Mask to circle
    for ($x = 0; $x < $diameter; $x++) {
        for ($y = 0; $y < $diameter; $y++) {
            $dx = $x - $radius;
            $dy = $y - $radius;
            if (($dx * $dx + $dy * $dy) > ($radius * $radius)) {
                imagesetpixel($circle, $x, $y, $transparent);
            }
        }
    }

    // Draw circle border
    $borderColor = imagecolorallocate($img, 255, 255, 255);
    imageellipse($circle, $radius, $radius, $diameter - 2, $diameter - 2, $borderColor);

    // Copy circle onto main image
    imagecopy($img, $circle, $circleX - $radius, $circleY - $radius, 0, 0, $diameter, $diameter);

    // Draw pointer line
    $lineColor = imagecolorallocate($img, 255, 255, 255);
    imageline($img, $focusX, $focusY, $circleX, $circleY, $lineColor);

    imagedestroy($circle);
}


$backgroundImageUrl = isset($_GET['car']) ? urldecode($_GET['car']) : null; $overlayImageName = isset($_GET['car']) ? $_GET['car'] : null;


$defaultBackgroundPath = __DIR__ . '/default-news-bg.jpg';

$background = downloadImageWithFallback($backgroundImageUrl, $defaultBackgroundPath);


if (isset($_GET['fx'], $_GET['fy'])) {
    drawCircleFocus(
        $background,
        intval($_GET['fx']),
        intval($_GET['fy']),
        $_GET['r'] ? 80 : "",
        $_GET['z'] ? 1.4 : ""
    );
}






/**
 * Download image with multiple fallback strategies
 */
function downloadImageWithFallback($url, $defaultPath) {
    // Strategy 1: Try with proper headers
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        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',
        CURLOPT_REFERER => 'https://www.google.com/',
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER => [
            'Accept: image/webp,image/apng,image/*,*/*;q=0.8',
            'Accept-Language: en-US,en;q=0.9',
            'Accept-Encoding: gzip, deflate, br',
            'Connection: keep-alive',
            'Cache-Control: max-age=0'
        ]
    ]);
    
    $imageData = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // Check if download was successful
    if ($httpCode === 200 && !empty($imageData) && substr($imageData, 0, 4) !== '<!do') {
        $img = imagecreatefromstring($imageData);
        if ($img !== false) {
            return $img;
        }
    }
    
    // Strategy 2: Try file_get_contents with context
    $context = stream_context_create([
        'http' => [
            'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n"
        ]
    ]);
    
    $imageData = @file_get_contents($url, false, $context);
    if ($imageData !== false) {
        $img = imagecreatefromstring($imageData);
        if ($img !== false) {
            return $img;
        }
    }
    
    // Strategy 3: Use local cached version if available
    $cacheDir = __DIR__ . '/cache/';
    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }
    
    $cacheFile = $cacheDir . md5($url) . '.jpg';
    if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 86400) {
        $img = imagecreatefromjpeg($cacheFile);
        if ($img !== false) {
            return $img;
        }
    }
    
    // Strategy 4: Use default background
    if (file_exists($defaultPath)) {
        $img = imagecreatefromjpeg($defaultPath);
        if ($img !== false) {
            return $img;
        }
    }
    
    // Final fallback: Create a solid color background
    $fallback = imagecreatetruecolor(800, 600);
    $bgColor = imagecolorallocate($fallback, 230, 230, 230);
    imagefilledrectangle($fallback, 0, 0, 800, 600, $bgColor);
    
    // Add text indicating it's a placeholder
    $textColor = imagecolorallocate($fallback, 150, 150, 150);
    imagestring($fallback, 5, 300, 280, 'News Image', $textColor);
    imagestring($fallback, 3, 250, 320, 'Could not load original', $textColor);
    
    return $fallback;
}
