<?php
// Allow requests from any origin (or specify your domain instead of *)
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header('Content-Type: application/json');

$make = strtolower($_GET['make']);
$model = strtolower($_GET['model']);

if (!$make || !$model) {
    echo json_encode(['error' => 'Missing make or model']);
    exit;
}

// Base URL
$base_url = "https://bc.autoportal.ua/img/new-cars-gallery/$make/$model/exterior/";

// Get HTML content of directory
$html = @file_get_contents($base_url);
if (!$html) {
    echo json_encode(['error' => 'Could not fetch directory']);
    exit;
}

// Match all links ending with -1600x1200.jpg
preg_match_all('/href="([^"]*-1600x1200\.jpg)"/i', $html, $matches);

if (!empty($matches[1])) {
    // Pick the first image
    $image_url = $base_url . $matches[1][0];
    echo json_encode(['image' => $image_url]);
} else {
    echo json_encode(['error' => 'No matching image found']);
}
