<?php
// car-color-overlay.php
// Usage: car-color-overlay.php?car=URL&color=URL&text=COLOR_NAME

// Enable error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Set image headers
header('Content-Type: image/jpeg');
header('Cache-Control: max-age=3600, public');

// Get parameters with correct names
$car_image_url = isset($_GET['car']) ? urldecode($_GET['car']) : '';
$color_image_url = isset($_GET['color']) ? urldecode($_GET['color']) : '';
$color_name = isset($_GET['text']) ? urldecode($_GET['text']) : '';

// Set default URLs if parameters are empty
if (empty($car_image_url)) {
    $car_image_url = 'https://parkers-images.bauersecure.com/Scale/wp-images/287005/cut-out/900x600/070-bmw-550e.jpg';
}
if (empty($color_image_url)) {
    $color_image_url = 'https://scratchrepaircar.co.uk/cdn/shop/files/sr_100951725_b177735d-6061-442b-a8a7-518cd61f3a35_300x225.jpg?v=1707742269';
}
if (empty($color_name)) {
    $color_name = 'Carbon Black Metallic 2020 416';
}

// Debug logging
error_log("Car URL: " . substr($car_image_url, 0, 100));
error_log("Color URL: " . substr($color_image_url, 0, 100));
error_log("Color Name: " . $color_name);

try {
    // Download and create images from URLs
    error_log("Downloading car image...");
    $car_image = downloadImage($car_image_url);
    error_log("Downloading color swatch...");
    $color_swatch = downloadImage($color_image_url);
    
    if (!$car_image) {
        throw new Exception("Failed to download car image from: " . substr($car_image_url, 0, 100));
    }
    
    if (!$color_swatch) {
        throw new Exception("Failed to download color swatch from: " . substr($color_image_url, 0, 100));
    }
    
    // Get dimensions
    $car_width = imagesx($car_image);
    $car_height = imagesy($car_image);
    error_log("Car image dimensions: {$car_width}x{$car_height}");
    
    // Calculate swatch size (15% of car image height)
    $swatch_size = intval($car_height * 0.15);
    error_log("Swatch size: {$swatch_size}px");
    
    // Resize color swatch to square
    $color_swatch_resized = imagecreatetruecolor($swatch_size, $swatch_size);
    imagealphablending($color_swatch_resized, false);
    imagesavealpha($color_swatch_resized, true);
    
    // Get original swatch dimensions
    $swatch_orig_width = imagesx($color_swatch);
    $swatch_orig_height = imagesy($color_swatch);
    error_log("Original swatch dimensions: {$swatch_orig_width}x{$swatch_orig_height}");
    
    // Resize swatch to square
    imagecopyresampled($color_swatch_resized, $color_swatch, 0, 0, 0, 0, 
                      $swatch_size, $swatch_size, $swatch_orig_width, $swatch_orig_height);
    
    // Create a circular mask for the swatch
    $swatch_circle = createCircularImage($color_swatch_resized, $swatch_size);
    imagedestroy($color_swatch_resized);
    
    // Create final image canvas (same size as car image)
    $final_image = imagecreatetruecolor($car_width, $car_height);
    
    // Copy car image to canvas
    imagecopy($final_image, $car_image, 0, 0, 0, 0, $car_width, $car_height);
    
    // Calculate swatch position (bottom-left with padding)
    $padding = intval($car_height * 0.03); // 3% padding
    $swatch_x = $padding;
    $swatch_y = $car_height - $swatch_size - $padding;
    error_log("Swatch position: x={$swatch_x}, y={$swatch_y}");
    
    // Add circular swatch to final image
    imagecopy($final_image, $swatch_circle, $swatch_x, $swatch_y, 0, 0, $swatch_size, $swatch_size);
    
    // Add color name text
    addColorNameText($final_image, $color_name, $swatch_x + $swatch_size + $padding, 
                    $swatch_y + ($swatch_size / 2), $car_width);
    
    // Add a subtle border around swatch for visibility
    $border_color = imagecolorallocate($final_image, 255, 255, 255);
    imageellipse($final_image, $swatch_x + ($swatch_size / 2), 
                $swatch_y + ($swatch_size / 2), 
                $swatch_size, $swatch_size, $border_color);
    
    // Output as JPEG with high quality
    imagejpeg($final_image, null, 90);
    
    // Cleanup
    imagedestroy($car_image);
    imagedestroy($color_swatch);
    imagedestroy($swatch_circle);
    imagedestroy($final_image);
    
} catch (Exception $e) {
    error_log("Exception caught: " . $e->getMessage());
    
    // Create error image
    $error_img = imagecreatetruecolor(800, 600);
    $bg_color = imagecolorallocate($error_img, 40, 40, 40);
    $text_color = imagecolorallocate($error_img, 255, 100, 100);
    $text_color2 = imagecolorallocate($error_img, 200, 200, 200);
    
    imagefilledrectangle($error_img, 0, 0, 800, 600, $bg_color);
    
    imagestring($error_img, 5, 50, 50, 'Car Color Image Generator - Error', $text_color);
    imagestring($error_img, 4, 50, 100, 'Error: ' . $e->getMessage(), $text_color2);
    
    // Show the URLs that were attempted
    imagestring($error_img, 3, 50, 150, 'Car URL: ' . substr($car_image_url, 0, 80), $text_color2);
    imagestring($error_img, 3, 50, 180, 'Color URL: ' . substr($color_image_url, 0, 80), $text_color2);
    
    imagejpeg($error_img, null, 90);
    imagedestroy($error_img);
}

/**
 * Download image from URL with better error handling
 */
function downloadImage($url) {
    // Clean URL (remove any trailing quotes)
    $url = trim($url, '"\'');
    
    $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_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_HEADER => true,  // Include headers in response
        CURLOPT_FAILONERROR => true  // Fail on HTTP error codes
    ]);
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    
    error_log("Download attempt: $url");
    error_log("HTTP Code: $http_code");
    error_log("Content-Type: $content_type");
    
    if ($error) {
        error_log("CURL Error: $error");
        return false;
    }
    
    if ($http_code !== 200) {
        error_log("Failed to download image. HTTP Code: $http_code");
        return false;
    }
    
    // Separate headers from body
    $headers = substr($response, 0, $header_size);
    $image_data = substr($response, $header_size);
    
    if (empty($image_data)) {
        error_log("No image data received");
        return false;
    }
    
    // Log first few bytes to see what we're getting
    $first_bytes = bin2hex(substr($image_data, 0, 4));
    error_log("First 4 bytes (hex): $first_bytes");
    
    // Check for common image signatures
    $signatures = [
        '89504e47' => 'PNG',
        'ffd8ffe0' => 'JPEG',
        'ffd8ffe1' => 'JPEG',
        '47494638' => 'GIF',
        '52494646' => 'WEBP'
    ];
    
    if (isset($signatures[$first_bytes])) {
        error_log("Detected image format: " . $signatures[$first_bytes]);
    } else {
        error_log("Unknown image signature: $first_bytes");
    }
    
    // Check if it's HTML instead of an image
    $text_start = strtolower(substr($image_data, 0, 200));
    if (strpos($text_start, '<!doctype') !== false || 
        strpos($text_start, '<html') !== false ||
        strpos($text_start, '<?xml') !== false) {
        error_log("Received HTML/XML instead of image");
        error_log("First 200 chars: " . substr($image_data, 0, 200));
        return false;
    }
    
    // Try to create image from string
    $image = @imagecreatefromstring($image_data);
    
    if ($image === false) {
        error_log("imagecreatefromstring() failed");
        error_log("Data length: " . strlen($image_data) . " bytes");
        
        // Try to save the data to a file for debugging
        $debug_file = __DIR__ . '/debug_image_data.bin';
        file_put_contents($debug_file, $image_data);
        error_log("Raw data saved to: $debug_file");
        
        return false;
    }
    
    error_log("Image successfully created from string");
    return $image;
}

/**
 * Create circular image from square image
 */
function createCircularImage($square_image, $size) {
    $circle_image = imagecreatetruecolor($size, $size);
    imagealphablending($circle_image, false);
    $transparent = imagecolorallocatealpha($circle_image, 0, 0, 0, 127);
    imagefilledrectangle($circle_image, 0, 0, $size, $size, $transparent);
    imagesavealpha($circle_image, true);
    
    // Create circular mask
    $center_x = $size / 2;
    $center_y = $size / 2;
    $radius = $size / 2;
    
    for ($x = 0; $x < $size; $x++) {
        for ($y = 0; $y < $size; $y++) {
            $dx = $x - $center_x;
            $dy = $y - $center_y;
            $distance = sqrt($dx * $dx + $dy * $dy);
            
            if ($distance <= $radius) {
                $color = imagecolorat($square_image, $x, $y);
                imagesetpixel($circle_image, $x, $y, $color);
            }
        }
    }
    
    return $circle_image;
}

/**
 * Add color name text to image
 */
function addColorNameText($image, $text, $x, $y, $image_width) {
    // Define colors
    $text_color = imagecolorallocate($image, 255, 255, 255); // White text
    $shadow_color = imagecolorallocate($image, 0, 0, 0);     // Black shadow
    
    // Try to load a font (use default if not available)
    $font_paths = [
        __DIR__ . '/arial.ttf',
        __DIR__ . '/fonts/arial.ttf',
        '/usr/share/fonts/truetype/msttcorefonts/arial.ttf',
        'C:/Windows/Fonts/arial.ttf'
    ];
    
    $font_size = 28;
    $font_file = null;
    
    foreach ($font_paths as $path) {
        if (file_exists($path)) {
            $font_file = $path;
            break;
        }
    }
    
    // Calculate text width to ensure it doesn't overflow
    $max_width = $image_width - $x - 20; // Leave 20px padding on right
    
    if ($font_file) {
        // Split text into parts if needed
        $parts = explode(' ', $text);
        $current_line = '';
        $line_height = $font_size * 1.2;
        $current_y = $y - ($font_size / 3); // Adjust vertical alignment
        
        foreach ($parts as $part) {
            $test_line = $current_line . ($current_line ? ' ' : '') . $part;
            $bbox = imagettfbbox($font_size, 0, $font_file, $test_line);
            $test_width = $bbox[2] - $bbox[0];
            
            if ($test_width > $max_width && $current_line) {
                // Draw current line
                imagettftext($image, $font_size, 0, $x + 2, $current_y + 2, $shadow_color, $font_file, $current_line);
                imagettftext($image, $font_size, 0, $x, $current_y, $text_color, $font_file, $current_line);
                
                // Start new line
                $current_line = $part;
                $current_y += $line_height;
            } else {
                $current_line = $test_line;
            }
        }
        
        // Draw the last line
        if ($current_line) {
            imagettftext($image, $font_size, 0, $x + 2, $current_y + 2, $shadow_color, $font_file, $current_line);
            imagettftext($image, $font_size, 0, $x, $current_y, $text_color, $font_file, $current_line);
        }
    } else {
        // Fallback to built-in font
        $font_size = 5;
        imagestring($image, $font_size, $x + 1, $y + 1, $text, $shadow_color);
        imagestring($image, $font_size, $x, $y, $text, $text_color);
    }
}