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

$dbConnection = null;

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

use Src\ApiLib\App;
use Src\ApiResources\Router;
use Src\ApiSecurity\Authenticator;

use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\Translator;

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();

$queries = array();
$requestMethod = $_SERVER["REQUEST_METHOD"];
$requestUri = str_replace('/api/v1', '', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
$uriParts = explode( '/', $requestUri );

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

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;
}

/*$data = json_decode(file_get_contents('php://input'), true);


foreach ($data as $key => $value) {
    print_r($value);exit;
}

print_r($data);exit;*/

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

if (is_null($routeFound)) {
    header("HTTP/1.1 404 Not Found");
    echo json_encode([
        'errorCode' => 451,
        'errorMessage' => 'Route not Found'
    ]);
    exit(1);
    //exit('Route not Found');
}
if (in_array($routeFound['controller_method'], CHECK_END_POINTS)) {
    $authenticator->checkAuthentication(false);
}
if (in_array($routeFound['controller_method'], SECURED_END_POINTS)) {
    $authenticator->checkAuthentication();
}

$translator = new Translator('de_DE');
$translator->setFallbackLocales(['en', 'de']);
$translator->addLoader('yamlfile', new YamlFileLoader());
$translator->addResource('yamlfile',  "../translations/messages+intl-icu.de.yaml", 'de', 'messages+intl-icu');
$translator->addResource('yamlfile',  "../translations/messages+intl-icu.en.yaml", 'en', 'messages+intl-icu');

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

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