<?php
// Allow all origins
header("Access-Control-Allow-Origin: *");

// Allow common HTTP methods
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

// Allow common headers
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Set content type to JSON
header('Content-Type: application/json');

// Get manufacturer and model from GET parameters
$manufacturer = isset($_GET['manufacturer']) 
    ? preg_replace('/\s+/', '-', trim($_GET['manufacturer'])) 
    : '';

$model = isset($_GET['model']) ? trim($_GET['model']) : '';

// Initialize response array
$response = [
    'success' => false,
    'manufacturer' => $manufacturer,
    'model' => $model,
    'logo' => null,  // ADD THIS LINE FOR LOGO
    'hero_image' => null,
    'gallery_images' => [],
    'total_gallery_images' => 0,
    'url_used' => null,
    'error' => null
];

// Check if parameters are provided
if (empty($manufacturer)) {
    $response['error'] = 'Missing manufacturer parameter.';
    echo json_encode($response, JSON_PRETTY_PRINT);
    exit;
}

// Generate URL from parameters
$manufacturerEncoded = strtolower($manufacturer);
$modelEncoded = strtolower($model);

// Function to get all models data
function getAllModelsData($manufacturerEncoded) {
    $allModelsResponse = [
        'success' => false,
        'all_models_data' => [],
        'total_ranges' => 0,
        'total_images_found' => 0,
        'url_used' => null,
        'logo' => null,  // ADD THIS LINE
        'error' => null
    ];
    
    // For "all models", scrape the manufacturer's specs page with the new structure
    if (empty($model) || preg_match('/ALL MODELS/i', $model)) {
        $url = "https://www.parkers.co.uk/{$manufacturerEncoded}/reviews/";
    } else {
        $url = "https://www.parkers.co.uk/{$manufacturerEncoded}/specs/";
    }
    
    $allModelsResponse['url_used'] = $url;
    
    // Initialize cURL
    $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_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    // Execute request
    $html = curl_exec($ch);

    if (curl_errno($ch)) {
        $allModelsResponse['error'] = 'cURL Error: ' . curl_error($ch);
        curl_close($ch);
        return $allModelsResponse;
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Check if page was fetched successfully
    if ($httpCode !== 200) {
        $allModelsResponse['error'] = "Failed to fetch page. HTTP Code: {$httpCode}";
        return $allModelsResponse;
    }
    
    // Parse the HTML to extract images from the new structure
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);
    
    // Extract logo from the specs page
    $logoUrl = extractLogo($html);
    $allModelsResponse['logo'] = $logoUrl;
    
    // Find all model ranges (sections)
    $modelRanges = $xpath->query('//section[contains(@class, "vehicle-selector__latest-models__range")]');
    
    $allModelsData = [];
    $totalImages = 0;
    
    foreach ($modelRanges as $range) {
        // Extract range name
        $rangeHeading = $xpath->query('.//h3[contains(@class, "vehicle-selector__latest-models__range__heading")]/a', $range);
        $rangeName = $rangeHeading->length > 0 ? trim($rangeHeading->item(0)->textContent) : 'Unknown Range';
        $rangeLink = $rangeHeading->length > 0 ? $rangeHeading->item(0)->getAttribute('href') : null;
        
        // Find all model items in this range
        $modelItems = $xpath->query('.//li[contains(@class, "model-grid__item")]', $range);
        
        $rangeModels = [];
        
        foreach ($modelItems as $item) {
            // Extract model details
            $modelNameNode = $xpath->query('.//span[contains(@class, "model-grid__item__detail__header")]', $item);
            $modelName = $modelNameNode->length > 0 ? trim($modelNameNode->item(0)->textContent) : 'Unknown Model';
            
            // Extract model years
            $modelYearsNode = $xpath->query('.//span[contains(@class, "model-grid__item__detail__text-container__text--inline")][position()=2]', $item);
            $modelYears = $modelYearsNode->length > 0 ? trim($modelYearsNode->item(0)->textContent) : '';
            
            // Extract image URL
            $imgNode = $xpath->query('.//img', $item);
            $imgSrc = null;
            if ($imgNode->length > 0) {
                $imgSrc = $imgNode->item(0)->getAttribute('src');
                if (!$imgSrc || strpos($imgSrc, 'transparent.png') !== false) {
                    $imgSrc = $imgNode->item(0)->getAttribute('data-src');
                }
            }
            
            // Extract model link
            $linkNode = $xpath->query('.//a[contains(@class, "model-grid__item__image")]', $item);
            $modelLink = $linkNode->length > 0 ? $linkNode->item(0)->getAttribute('href') : null;
            
            // Extract alt text
            $altText = $imgNode->length > 0 ? $imgNode->item(0)->getAttribute('alt') : '';
            
            $modelData = [
                'model_name' => $modelName,
                'model_years' => $modelYears,
                'image_url' => $imgSrc,
                'model_link' => $modelLink,
                'alt_text' => $altText
            ];
            
            if ($imgSrc) {
                $totalImages++;
            }
            
            $rangeModels[] = $modelData;
        }
        
        if (!empty($rangeModels)) {
            $allModelsData[] = [
                'range_name' => $rangeName,
                'range_link' => $rangeLink,
                'models' => $rangeModels,
                'models_count' => count($rangeModels)
            ];
        }
    }
    
    $allModelsResponse['success'] = true;
    $allModelsResponse['all_models_data'] = $allModelsData;
    $allModelsResponse['total_ranges'] = count($allModelsData);
    $allModelsResponse['total_images_found'] = $totalImages;
    
    return $allModelsResponse;
}

// Function to extract hero image URL from HTML
function extractHeroImage($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);
    
    // Try multiple strategies to find the hero image
    $queries = [
        '//img[contains(@class, "hero-image__image")]',
        '//img[contains(@alt, "rated")]',
        '//img[contains(@data-interchange, "bauersecure.com")]',
        '//div[contains(@class, "hero-image")]//img'
    ];
    
    foreach ($queries as $query) {
        $images = $xpath->query($query);
        if ($images->length > 0) {
            foreach ($images as $img) {
                // First check data-interchange attribute
                $dataInterchange = $img->getAttribute('data-interchange');
                if ($dataInterchange) {
                    // Extract the largest image URL from data-interchange
                    if (preg_match_all('/\[([^,\]]+bauersecure\.com[^,\]]+\.jpg[^,\]]*)/i', $dataInterchange, $matches)) {
                        if (!empty($matches[1])) {
                            // Return the last one (usually largest) or search for xlarge
                            foreach ($matches[1] as $match) {
                                if (strpos($match, 'xlarge') !== false || strpos($match, '900x600') !== false) {
                                    return trim($match);
                                }
                            }
                            return trim(end($matches[1]));
                        }
                    }
                }
                
                // Fallback to src or data-src
                $src = $img->getAttribute('src');
                if (!$src || strpos($src, 'transparent.png') !== false) {
                    $src = $img->getAttribute('data-src');
                }
                
                if ($src && strpos($src, '.jpg') !== false) {
                    return $src;
                }
            }
        }
    }
    
    return null;
}

// Function to extract gallery images from HTML
function extractGalleryImages($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);
    
    $galleryImages = [];
    
    // Look for gallery images in the full-screen-gallery__slider
    $queries = [
        '//div[contains(@class, "full-screen-gallery__slider")]//a[contains(@class, "rsImg")]',
        '//div[contains(@class, "royalSlider")]//a[contains(@class, "rsImg")]',
        '//a[@class="rsImg"]'
    ];
    
    foreach ($queries as $query) {
        $galleryLinks = $xpath->query($query);
        if ($galleryLinks->length > 0) {
            foreach ($galleryLinks as $link) {
                $imageData = [
                    'title' => trim($link->textContent),
                    'large' => $link->getAttribute('href'),
                    'medium_large' => $link->getAttribute('data-href-l'),
                    'medium' => $link->getAttribute('data-href-m'),
                    'small' => $link->getAttribute('data-href-s'),
                    'thumbnail' => null
                ];
                
                // Get thumbnail from img tag inside
                $thumbnailImgs = $xpath->query('.//img', $link);
                if ($thumbnailImgs->length > 0) {
                    $imageData['thumbnail'] = $thumbnailImgs->item(0)->getAttribute('src');
                }
                
                // Only add if we have at least one valid image URL
                if ($imageData['large'] || $imageData['medium_large'] || $imageData['medium'] || $imageData['small']) {
                    $galleryImages[] = $imageData;
                }
            }
            break; // Stop after first successful query
        }
    }
    
    return $galleryImages;
}

// Function to extract logo URL from HTML
// Function to extract logo URL from HTML
function extractLogo($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
    $xpath = new DOMXPath($dom);
    
    // Priority 1: Look for page-heading__logo
    $logos = $xpath->query('//img[contains(@class, "page-heading__logo")]');
    if ($logos->length > 0) {
        foreach ($logos as $logo) {
            $src = $logo->getAttribute('src');
            if (!$src || strpos($src, 'transparent.png') !== false) {
                $src = $logo->getAttribute('data-src');
            }
            
            if ($src && (strpos($src, 'jpg') !== false || strpos($src, 'png') !== false || strpos($src, 'svg') !== false)) {
                return formatImageUrl($src);
            }
        }
    }
    
    // Priority 2: Look for main-heading__logo
    $logos = $xpath->query('//div[contains(@class, "main-heading__logo")]//img');
    if ($logos->length > 0) {
        foreach ($logos as $logo) {
            $src = $logo->getAttribute('src');
            if (!$src || strpos($src, 'transparent.png') !== false) {
                $src = $logo->getAttribute('data-src');
            }
            
            if ($src && (strpos($src, 'jpg') !== false || strpos($src, 'png') !== false || strpos($src, 'svg') !== false)) {
                return formatImageUrl($src);
            }
        }
    }
    
    return null;
}

// Helper function to format image URLs correctly
function formatImageUrl($src) {
    if (strpos($src, 'http') !== 0 && strpos($src, '//') !== 0) {
        // Relative URL
        $src = 'https://www.parkers.co.uk' . (strpos($src, '/') === 0 ? '' : '/') . $src;
    } elseif (strpos($src, '//') === 0) {
        // Protocol-relative URL
        $src = 'https:' . $src;
    }
    return trim($src);
}
// Main logic
if(empty($model) || strtolower($model) == "all models") {
    // For "all models" or empty model
    $allModelsResponse = getAllModelsData($manufacturerEncoded);
    
    // Merge the responses
    $response = array_merge($response, $allModelsResponse);
    
    // If getting all models data failed, add the error to response
    if (!$allModelsResponse['success']) {
        $response['error'] = $allModelsResponse['error'];
    }
    
} else {
    // For specific model
    $url = "https://www.parkers.co.uk/{$manufacturerEncoded}/{$modelEncoded}/review/";
    
    $response['url_used'] = $url;
    
    // Initialize cURL
    $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_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_NOBODY, false); // We need the body for content analysis

    // Execute request
    $html = curl_exec($ch);

    if (curl_errno($ch)) {
        $response['error'] = 'cURL Error: ' . curl_error($ch);
        curl_close($ch);
        echo json_encode($response, JSON_PRETTY_PRINT);
        exit;
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Check if page was fetched successfully - if 404, fall back to all models
    if ($httpCode == 404) {
        // Model not found - send empty model (fall back to all models)
        $allModelsResponse = getAllModelsData($manufacturerEncoded);
        
        // Merge the responses
        $response = array_merge($response, $allModelsResponse);
        $response['model'] = ''; // Clear the model parameter
        $response['note'] = 'Model not found, returning all models data instead';
        
        // If getting all models data failed, add the error to response
        if (!$allModelsResponse['success']) {
            $response['error'] = $allModelsResponse['error'];
        }
        
    } elseif ($httpCode !== 200) {
        $response['error'] = "Failed to fetch page. HTTP Code: {$httpCode}";
        echo json_encode($response, JSON_PRETTY_PRINT);
        exit;
    } else {
        // Page fetched successfully - extract logo, hero and gallery images
        $logoUrl = extractLogo($html);  // Extract logo
        $heroImageUrl = extractHeroImage($html);
        $galleryImages = extractGalleryImages($html);

        // Update response
        $response['success'] = true;
        $response['logo'] = $logoUrl;  // Add logo to response
        $response['hero_image'] = $heroImageUrl;
        $response['gallery_images'] = $galleryImages;
        $response['total_gallery_images'] = count($galleryImages);
    }
}

// Output JSON
echo json_encode($response, JSON_PRETTY_PRINT);