<?php

$profile  = getenv("SAVVY_PROFILE");
if ($profile) {
  require_once("../../core/backend.${profile}.php");
} else {
  require_once( '../../core/backend.php' );
}

include_once '../config.php';
require_once('../constants.php');

require_once('../common/vendor/autoload.php');
require_once('../common/Api.php');
require_once('../common/Db.php');
require_once('../common/GoogleKMS.php');
require_once('../common/Logger.php');

require_once('../trips/MultiModalFilter.php');

require_once('Options.php');
require_once('OptionsApi.php');
require_once('Quote.php');
require_once('QuoteApi.php');
require_once('Route.php');
require_once('RouteApi.php');
require_once('AutocabApi.php');
require_once('autocab/Autocab.php');
require_once('Booking.php');
require_once('../trips/SGBikeApi.php');

$httpAuthToken = $savvyext->cfgReadChar('system.oauth2_token');

header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header('Content-type: application/json');

if ("OPTIONS" === $_SERVER['REQUEST_METHOD']) {
    exit();
}

$headers = getallheaders();
if ((!isset($headers["Authorization"]) || substr($headers["Authorization"],-strlen($httpAuthToken))!=$httpAuthToken) &&
    (!isset($headers["authorization"]) || substr($headers["authorization"],-strlen($httpAuthToken))!=$httpAuthToken)) {
    header('HTTP/1.1 401 Unauthorized');
    header('Status: 401 Unauthorized');
    echo "{\"status\":\"Missing authorization\"}";
    exit();
}

try {
	if (strpos($_SERVER['REQUEST_URI'],'/api/')===false) {
		throw new Exception("Invalid API request");
	}
	$requestUri = explode('/', trim($_SERVER['REQUEST_URI'],'/'));
	while (array_shift($requestUri) !== 'api') {
	};
	if ($requestUri[0]=='options') {
		$api = new OptionsApi($requestUri);
	}
	else if ($requestUri[0]=='route') {
		$api = new RouteApi($requestUri);
	}	
	else if ($requestUri[0]=='quote') {
		$api = new QuoteApi($requestUri);
	}
	else if ($requestUri[0]=='autocab') {
		$api = new AutocabApi($requestUri);
	}
	else {
		echo json_encode(Array('error' => 'Invalid API request'));
	}
	echo $api->run();
}
catch (Exception $e) {
	echo json_encode(Array('error' => $e->getMessage()));
}

