<?php
//ini_set("display_errors",true);

$dbConnection = null;
$translator = null;
$queries = [];
$uriParts = [];
$requestUri = '';
$requestMethod = $_SERVER["REQUEST_METHOD"];

require __DIR__."/../boostrap.php";

use Src\ApiException\HTTPCodeEnum;
use Src\ApiHelper\LangEnum;
use Src\ApiLib\App;
use Src\ApiResources\Router;
use Src\ApiSecurity\Authenticator;

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,PUT");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // HTTP/1.0
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");

App::run();
$authenticator = new Authenticator();
$authenticator->checkApiKey();

$router = new Router();
$routeFound = null;

if (preg_match('/^\/(de|en|fr)\/offers\/testError\/?$/', $requestUri)) {
    $message = match (LangEnum::getFormValues()[$uriParts[1]]) {
        LangEnum::FRENCH => 'Something has gone terribly wrong. We are working flat out to find a solution.',
        LangEnum::ENGLISH => 'Il y a eu un énorme problème. On met tout en œuvre pour trouver une solution.',
        default => 'Da ist etwas furchtbar schiefgelaufen. Wir geben Vollgas, um eine Lösung zu finden.',
    };
    header("HTTP/1.1 512 Internal Server Error");
    echo json_encode(
        HTTPCodeEnum::getStandardErrorResponse(HTTPCodeEnum::INTERNAL_SERVER_ERROR, $message)
    );
    exit(1);
}

if (isset($_SERVER['QUERY_STRING'])) {
    parse_str($_SERVER['QUERY_STRING'], $queries);
}

if (!array_key_exists('limit', $queries)) {
    $queries['limit'] = 20;
}
if (!array_key_exists('offset', $queries)) {
    $queries['offset'] = 0;
}

foreach ($router->getRoutes() as $route) {
    if ($route['method'] == $requestMethod &&
        preg_match($route['expression'], $requestUri)) {
        $routeFound = $route;
        break;
    }
}

if (is_null($routeFound)) {
    if (in_array($uriParts[1], LangEnum::getArray())) {
        $message = match (LangEnum::getFormValues()[$uriParts[1]]) {
            LangEnum::ENGLISH => 'Malfunctioned request',
            default => 'Fehlerhafte Anfrage',
        };
    } else {
        $message = 'Malfunctioned request';
    }
    header("HTTP/1.1 404 Not Found");
    echo json_encode(
        HTTPCodeEnum::getStandardErrorResponse(HTTPCodeEnum::NOT_FOUND, $message)
    );
    exit(1);
}
if (in_array($routeFound['controller_method'], CHECK_END_POINTS)) {
    $authenticator->checkAuthentication(false);
}
if (in_array($routeFound['controller_method'], SECURED_END_POINTS)) {
    $authenticator->checkAuthentication();
}

$controllerName = $routeFound['controller_name'];
$methodName = $routeFound['controller_method'];

$controller = new $controllerName($dbConnection, $uriParts, $queries, $translator);
$controller->$methodName();