<?php
include('include/auth.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// Ensure request is POST
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode(["error" => "Invalid request method. Only POST allowed."]);
    exit;
}

// Read and decode JSON input
$rawPostData = file_get_contents("php://input");
$postData = json_decode($rawPostData, true);

// Log the received request
error_log("Received POST Data: " . print_r($postData, true));

if (!$postData) {
    echo json_encode(["error" => "Invalid JSON input"]);
    exit;
}

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

// Convert POST Data into GET URL Format (Like Postman)
$api_url = "https://api.motorclub.gr/info.php?"
         . "pid=" . urlencode($postData['pid'])
         . "&key=" . urlencode($postData['key'])
         . "&vehicle_type=" . urlencode($postData['vehicle_type'])
         . "&task=3";  // Ensure Task 3 is passed

if (!empty($postData['car_alias'])) {
    $api_url .= "&car_alias=" . urlencode($postData['car_alias']);
}

// Log the API request URL
error_log("Requesting API URL: " . $api_url);

// Initialize cURL
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); // Explicitly use POST method
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Cache-Control: no-cache",
    "Postman-Token: ".uniqid(),
    "Content-Type: application/json",
    "User-Agent: PostmanRuntime/7.43.2",
    "Accept: */*",
    "Accept-Encoding: gzip, deflate, br",
    "Connection: keep-alive"
]);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Handle redirects

$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): " . print_r($response, true));

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

if (!$response || empty($response)) {
    echo json_encode(["error" => "Empty response from API", "debug_url" => $api_url, "http_code" => $http_code]);
    exit;
}

// Return API response
echo $response;
?>
