<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
ob_start();
require_once("../../backend/functions.php");
require_once("../../db/connection.php");
session_write_close();
$settings = get_settings();
$openrouteservice_api_key = $settings['openrouteservice_api_key'];
$requestData = json_decode(file_get_contents('php://input'), true);
if($requestData) {
    $profile = $requestData['profile'];
    $source_lat = $requestData['s_lat'];
    $source_lon = $requestData['s_lon'];
    $dest_lat = $requestData['d_lat'];
    $dest_lon = $requestData['d_lon'];
    $language = isset($requestData['language']) ? $requestData['language'] : 'en';
    $apiDirectionsUrl = 'https://api.openrouteservice.org/v2/directions/'.$profile.'/geojson';
    $coords = [];
    $coords[] = [(float)$source_lon, (float)$source_lat];
    if (isset($requestData['waypoints']) && is_array($requestData['waypoints'])) {
        foreach ($requestData['waypoints'] as $wp) {
            if (isset($wp['lon']) && isset($wp['lat'])) {
                $coords[] = [(float)$wp['lon'], (float)$wp['lat']];
            }
        }
    }
    $coords[] = [(float)$dest_lon, (float)$dest_lat];
    $postData = [
        'coordinates' => $coords,
        'language' => $language
    ];
    $jsonPayload = json_encode($postData);
    $ch = curl_init($apiDirectionsUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonPayload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Accept: application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
        'Content-Type: application/json; charset=utf-8',
        'Authorization: ' . $openrouteservice_api_key
    ]);
    $response = curl_exec($ch);
    if(curl_errno($ch)){
        $response = json_encode(['error' => ['message' => curl_error($ch)]]);
    }
    curl_close($ch);
    header('Content-Type: application/json');
    ob_end_clean();
    echo $response;
}
?>