<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");

// Get raw POST data
$rawPostData = file_get_contents("php://input");
error_log("Received POST Data: " . $rawPostData); // Debugging log

// Decode JSON request
$postData = json_decode($rawPostData, true);

// Validate required parameters
if (!$postData || !isset($postData['pid']) || !isset($postData['key']) || !isset($postData['vehicle_type'])) {
    error_log("Invalid request data.");
    echo json_encode(["error" => "Missing required fields"]);
    exit;
}

// Define API URL
$api_url = "https://api.motorclub.gr/info.php";

// Initialize cURL
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); // Send JSON data
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

// Execute request
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

// Log API response
error_log("API Response (HTTP $http_code): " . $response);

// Handle API errors
if ($error) {
    echo json_encode(["error" => "cURL Error: $error"]);
    exit;
}

if (!$response) {
    echo json_encode(["error" => "Empty response from API"]);
    exit;
}

// Return API response
echo $response;
?>
