<?php
use App\Security\Token;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require __DIR__ . '/../../vendor/autoload.php';
require_once (__DIR__.'/Config.php');
$c = new \Slim\Container(); //Create Your container
//Override the default Not Found Handler before creating App
/*comentado*/
$c['notFoundHandler'] = function ($c) {
    return function ($request, $response) use ($c) {
        $respuesta = array('estado'=>'ERROR', 'mensaje'=>'Dirección no encontrada', 'status'=>404);
        return $response
            ->withJson($respuesta,404);
            
    };
};
$c['notAllowedHandler'] = function ($c) {
    return function ($request, $response, $methods) use ($c) {
        $respuesta = array('estado'=>'ERROR', 'mensaje'=>'Metodo HTTP no permitido', 'status'=>405);
        return $response
            ->withHeader('Allow', implode(', ', $methods))
            ->withJson($respuesta,405);
    };
};
$c['errorHandler'] = function ($c) {
    return function ($request, $response, $exception) use ($c) {
        $respuesta = array('estado'=>'ERROR', 'mensaje'=>$exception->getMessage(), 'status'=>500);
        return $response
            ->withJson($respuesta,500);
    };
};
/*comentado*/

//Create Slim
$app = new \Slim\App($c);
$app->add(function (Request $request, Response $response, callable $next) {
        
        $uri = $request->getUri();
        //removemos parametros del uri para validar URL
        $idxInicio = strpos($uri,'?');
        if($idxInicio !== false){
            $uri = substr($uri,0,$idxInicio);
            
        }
        $uri = str_replace(' ','',$uri);
        $method = $request->getMethod();
        
        if(array_search($uri,URL_BYPASS) !==false){
            $response = $next($request, $response);
            $parsedBody = $request->getParsedBody();
            if(is_null($parsedBody) && $method == 'POST'){
                
                $data = array('estado'=>'ERROR', 'mensaje'=>'Parametros no pueden estar en blanco', 'status'=>400);
                $payload = json_encode($data);
                $response->getBody()->write($payload);
                $response = $response->withStatus(400);  
                
            }
        }else{
            
            $headToken = $request->getHeaderLine('Authorization');
            
            if($headToken == ""){
                $headToken = $request->getHeader('authorization');
            }
            
            if(!is_null($headToken)){
                $headToken = str_replace("Bearer ", "", $headToken);
                
                $securityToken = new Token();
                $validateToken = $securityToken->validateToken($headToken);
            
                if($validateToken == 'OK'){
                    
                    $request = $request->withAttribute('id', $securityToken->id);
                    $request = $request->withAttribute('login', $securityToken->login);
                    $request = $request->withAttribute('emp_codigo', $securityToken->emp_codigo);
                    $request = $request->withAttribute('amb_codigo', $securityToken->amb_codigo);
                    $request = $request->withAttribute('new_token', strval($securityToken->newToken));
                    $response = $next($request, $response);
                    
                }else{
                    
                    $data = array('estado'=>'ERROR', 'mensaje'=>$validateToken, 'status'=>401);
                    $payload = json_encode($data);
                    $response->getBody()->write($payload);
                    $response = $response->withStatus(401);
                }
            }else{
                
                $data = array('estado'=>'ERROR', 'mensaje'=>'Token de seguridad no enviado, por favor intente nuevamente', 'status'=>400);
                $payload = json_encode($data);
                $response->getBody()->write($payload);
                $response = $response->withStatus(400);
            }
        }
        return $response;
 
    
});
$app->add(new Tuupola\Middleware\CorsMiddleware([
    "origin" => ["*"],
    "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE","OPTIONS"],
    "headers.allow" => ["X-Requested-With", "Content-Type", "Accept","Origin","Authorization","authorization"],
    "headers.expose" => ['application/json','application/x-www-form-urlencoded'],
    "credentials" => true,
    "cache" => 0,
]));
require __DIR__.'/Routes.php';
$app->run();
