<?php
// api.php - Pure JSON API version with image extraction

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$response = array();

// Get registration from query parameter
$regNumber = isset($_GET['reg']) ? $_GET['reg'] : '';

// Normalize: trim, remove non-alphanumeric, force uppercase
$regNumber = strtoupper(preg_replace('/[^A-Z0-9]/', '', trim($regNumber)));

// Check if empty
if ($regNumber === '') {
    $response['error'] = 'Registration number is required';
    $response['meta']['reg_valid'] = false;
}
// Validate registration format (basic UK formats)
elseif (!preg_match('/^(?:[A-Z]{2}[0-9]{2}[A-Z]{3}|[A-Z][0-9]{3}[A-Z]{3}|[A-Z]{3}[0-9]{3})$/', $regNumber)) {
    $response['error'] = 'Invalid UK registration format';
    $response['meta']['reg_valid'] = false;
}
else {
    $response['meta']['reg_valid'] = true;
    $response['meta']['registration'] = $regNumber;
}


// Target URLs for data and images
$dataUrl = "https://www.carcheck.co.uk/bmw/" . urlencode($regNumber);
$imageUrl = "https://www.mycarcheck.com/vrm/" . urlencode($regNumber);

// Prepare response
$response = [
    'success' => false,
    'registration' => $regNumber,
    'data' => [],
    'images' => [
        'vehicle_image' => null,
        'brand_logo' => null,
        'source' => 'mycarcheck.com'
    ],
    'meta' => [
        'source' => 'carcheck.co.uk',
        'timestamp' => date('c'),
        'reg_provided' => $regNumber
    ],
    'error' => null
];

// Function to extract image using DOMDocument
function extractCarImageDom($html) {
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    
    // Try to find the car image by looking for elements with vehicle images
    $queries = [
        '//img[contains(@data-src, "vehicles")]',
        '//img[contains(@src, "vehicles")]',
        '//img[contains(@class, "ailicenced")]',
        '//img[contains(@alt, "car") or contains(@alt, "vehicle")]',
        '//div[contains(@class, "icon")]//img'
    ];
    
    foreach ($queries as $query) {
        $images = $xpath->query($query);
        if ($images->length > 0) {
            foreach ($images as $img) {
                $src = $img->getAttribute('data-src') ?: $img->getAttribute('src');
                if ($src) {
                    // If the URL is relative, make it absolute
                    if (strpos($src, 'http') !== 0) {
                        $baseUrl = 'https://www.mycarcheck.com';
                        $src = rtrim($baseUrl, '/') . '/' . ltrim($src, '/');
                    }
                    return $src;
                }
            }
        }
    }
    
    return null;
}

// Function to extract image using regex fallback
function extractCarImageRegex($html) {
    // Look for image patterns
    $patterns = [
        '/<img[^>]+data-src="([^"]+)"[^>]*>/i',
        '/<img[^>]+src="([^"]*vehicles[^"]+)"[^>]*>/i',
        '/<img[^>]+src="([^"]*vehicle[^"]+)"[^>]*>/i'
    ];
    
    foreach ($patterns as $pattern) {
        if (preg_match($pattern, $html, $matches)) {
            return $matches[1];
        }
    }
    
    return null;
}

// Function to extract brand logo from app_top_image div
function extractBrandLogo($html) {
    // Pattern to extract the background-image URL from app_top_image div
    $pattern = '/<div class="app_top_image" style="background-image:url\(\'([^\']+)\'\);"><\/div>/';
    
    if (preg_match($pattern, $html, $matches)) {
        return $matches[1];
    }
    
    // Alternative pattern
    $pattern2 = '/<div[^>]*class="[^"]*app_top_image[^"]*"[^>]*style="[^"]*background-image:\s*url\(\'([^\']+)\'\)[^"]*"[^>]*>/';
    
    if (preg_match($pattern2, $html, $matches)) {
        return $matches[1];
    }
    
    return null;
}

// Initialize multi-cURL for parallel requests
$mh = curl_multi_init();
$ch1 = curl_init();
$ch2 = curl_init();

// Configure cURL for data extraction
curl_setopt_array($ch1, [
    CURLOPT_URL => $dataUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_CONNECTTIMEOUT => 10
]);

// Configure cURL for image extraction
curl_setopt_array($ch2, [
    CURLOPT_URL => $imageUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 15,
    CURLOPT_CONNECTTIMEOUT => 10
]);

// Add handles to multi-curl
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// Execute parallel requests
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

// Get data from first request
$dataHtml = curl_multi_getcontent($ch1);
$dataHttpCode = curl_getinfo($ch1, CURLINFO_HTTP_CODE);

// Get image data from second request
$imageHtml = curl_multi_getcontent($ch2);
$imageHttpCode = curl_getinfo($ch2, CURLINFO_HTTP_CODE);

// Close all handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

// Process data extraction
if ($dataHttpCode !== 200 || empty($dataHtml)) {
    $response['error'] = "Data extraction failed: HTTP $dataHttpCode";
    echo json_encode($response, JSON_PRETTY_PRINT);
    exit;
}

// Extract registration from page (actual displayed reg)
if (preg_match('/<div class="app_top_plate">([^<]+)<\/div>/', $dataHtml, $matches)) {
    $response['data']['registration'] = trim($matches[1]);
    $response['meta']['reg_found'] = trim($matches[1]);
} else {
    $response['data']['registration'] = $regNumber;
}

// Extract brand logo from app_top_image div
$brandLogo = extractBrandLogo($dataHtml);
if ($brandLogo) {
    $response['images']['brand_logo'] = $brandLogo;
    $response['images']['brand_logo_extracted'] = true;
} else {
    $response['images']['brand_logo_extracted'] = false;
}

// Define extraction patterns for vehicle data
$patterns = [
    'make' => '/<th[^>]*>Make<\/th>\s*<td>([^<]+)<\/td>/',
    'model' => '/<th[^>]*>Model<\/th>\s*<td>([^<]+)<\/td>/',
    'year' => '/<th[^>]*>Year of manufacture<\/th>\s*<td>([^<]+)<\/td>/',
    'colour' => '/<th[^>]*>Colour<\/th>\s*<td>([^<]+)<\/td>/',
    'fuel_type' => '/<th[^>]*>Fuel type<\/th>\s*<td>([^<]+)<\/td>/',
    'gearbox' => '/<th[^>]*>Gearbox<\/th>\s*<td>([^<]+)<\/td>/',
    'engine_capacity' => '/<th[^>]*>Engine capacity<\/th>\s*<td>([^<]+)<\/td>/',
    'engine_size' => '/<th[^>]*>Engine capacity<\/th>\s*<td>([^<]+)<\/td>/',
    'power' => '/<th[^>]*>Power<\/th>\s*<td>([^<]+)<\/td>/',
    'mot_expiry' => '/<th[^>]*>MOT expiry date<\/th>\s*<td>([^<]+)<\/td>/',
    'co2_emissions' => '/<th[^>]*>CO2 emission<\/th>\s*<td>([^<]+)<\/td>/',
    'vehicle_class' => '/<th[^>]*>Vehicle class<\/th>\s*<td>([^<]+)<\/td>/',
    'body_type' => '/<th[^>]*>Vehicle class<\/th>\s*<td>([^<]+)<\/td>/',
    'top_speed' => '/<th[^>]*>Top speed<\/th>\s*<td>([^<]+)<\/td>/',
    'mileage_history' => '/<th[^>]*>Mileage registrations<\/th>\s*<td>([^<]+)<\/td>/'
];

// Extract data
foreach ($patterns as $key => $pattern) {
    if (preg_match($pattern, $dataHtml, $matches)) {
        $response['data'][$key] = trim($matches[1]);
    }
}

// Extract tax status
if (preg_match('/<th[^>]*>Tax status<\/th>\s*<td>\s*<span[^>]*>Valid until ([^<]+)<\/span>/', $dataHtml, $matches)) {
    $response['data']['tax_status'] = 'Valid until ' . trim($matches[1]);
    $response['data']['tax_due'] = trim($matches[1]);
} elseif (preg_match('/<div class="block-result block-result-positive">\s*Taxed/', $dataHtml)) {
    $response['data']['tax_status'] = 'Taxed';
} elseif (preg_match('/<div class="block-result block-result-negative">\s*Tax/', $dataHtml)) {
    $response['data']['tax_status'] = 'Not Taxed';
}

// Calculate MOT status
if (isset($response['data']['mot_expiry'])) {
    $motDate = DateTime::createFromFormat('Y-m-d', $response['data']['mot_expiry']);
    $today = new DateTime();
    $response['data']['mot_status'] = ($motDate < $today) ? 'Expired' : 'Valid';
    
    // Add days until expiry
    $interval = $today->diff($motDate);
    $response['data']['mot_days_remaining'] = ($motDate > $today) ? $interval->days : 0;
}

// Process image extraction
if ($imageHttpCode === 200 && !empty($imageHtml)) {
    // Try DOM extraction first
    $extractedImageUrl = extractCarImageDom($imageHtml);
    
    // Fallback to regex if DOM fails
    if (!$extractedImageUrl) {
        $extractedImageUrl = extractCarImageRegex($imageHtml);
    }
    
    if ($extractedImageUrl) {
        $response['images']['vehicle_image'] = $extractedImageUrl;
        $response['images']['extraction_success'] = true;
    } else {
        $response['images']['extraction_success'] = false;
        $response['images']['error'] = 'No vehicle image found on page';
    }
} else {
    $response['images']['extraction_success'] = false;
    $response['images']['error'] = "Image source unavailable: HTTP $imageHttpCode";
}

// Set success if we have data
if (count($response['data']) > 0) {
    $response['success'] = true;
    $response['meta']['fields_extracted'] = count($response['data']);
}

// Add image info to meta
$response['meta']['image_attempted'] = true;
$response['meta']['image_source'] = 'mycarcheck.com';
$response['meta']['brand_logo_extracted'] = !empty($response['images']['brand_logo']);

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