<?php
#require_once('../../../adminsavvy/vendor/autoload.php');
$profile  = getenv("SAVVY_PROFILE");
if ($profile) {
  require_once("../../core/backend.${profile}.php");
} else {
  require_once( '../../core/backend.php' );
}

require_once '../common/Api.php';
require_once '../common/Db.php';

require_once 'AddressToArea.php';
require_once 'AddressToAreaApi.php';
require_once 'GeofenceAreaModel.php';
require_once 'GeofenceAreaApi.php';
require_once 'HourlyAverages.php';
require_once 'HourlyAveragesApi.php';
require_once 'PopularDestinations.php';
require_once 'PopularDestinationsApi.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] == 'addresstoarea') {
        $api = new AddressToAreaApi($requestUri, false);
    } else if ($requestUri[0] == 'geofencearea') {
        $api = new geofenceAreaApi($requestUri, false);
    } else if ($requestUri[0] == 'hourlyaverages') {
        $api = new HourlyAveragesApi($requestUri, false);
    } else if ($requestUri[0] == 'populardestinations') {
        $api = new PopularDestinationsApi($requestUri, false);
    } else {
        echo json_encode(array('error' => 'Invalid API request'));
    }
    echo $api->run();
} catch (Exception $e) {
    echo json_encode(array('error' => $e->getMessage()));
}


/**
 * @OA\Info(
 *   title="Geofence Area Endpoint API",
 *   version="1.0",
 *   @OA\Contact(
 *     email="support@float.sg"
 *   )
 * )
 */
/**
 * @OA\SecurityScheme(
 *   securityScheme="token",
 *   type="apiKey",
 *   name="Authorization",
 *   in="header"
 * )
 */