<?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 received data
error_log("Received POST Data: " . print_r($postData, true));

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

// Validate required fields
$required_fields = ['pid', 'key', 'type', 'task', 'start', 'end', 'sloc', 'eloc'];
$missing_fields = [];

foreach ($required_fields as $field) {
    if (!isset($postData[$field]) || empty($postData[$field])) {
        $missing_fields[] = $field;
    }
}

// If missing fields, return error
if (!empty($missing_fields)) {
    echo json_encode(["error" => "Missing required fields", "missing_fields" => $missing_fields]);
    exit;
}

// Convert POST Data into GET URL Format
$api_url = "https://api.motorclub.gr/info.php?"
         . "pid=" . urlencode($postData['pid'])
         . "&key=" . urlencode($postData['key'])
         . "&type=" . urlencode($postData['type'])
         . "&task=" . urlencode($postData['task'])
         . "&start=" . urlencode($postData['start'])
         . "&end=" . urlencode($postData['end'])
         . "&sloc=" . urlencode($postData['sloc'])
         . "&eloc=" . urlencode($postData['eloc'])
         . "&cars=0";  // **Added required parameter**

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

// Fetch API response
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
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);

$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 Code: $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;
?>
