<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

//TODO: log errors

$validateGet = function ($request, $response, $next) {
    if ($request->isGet()) {
	    $response = $next($request, $response);
    } else {
	    $response = $response->withJson(['status'=>'err', 'msg'=>'Not valid method']);
	}
	
    return $response;
};

$validateApi = function ($request, $response, $next) {
	global $config;
	
	$apiKey = $config['settings']['api-key'];
	
    if ($request->isPost()) {
	    $headerApiKey = $request->getHeader('Api-Key');
	    if ($headerApiKey[0] != $apiKey) {
		    $response = $response->withJson(['status'=>'err', 'msg'=>'Not valid API request']);
	    } else {
		    $response = $next($request, $response);
	    }
    } else {
	    $response = $response->withJson(['status'=>'err', 'msg'=>'Not valid API request method']);
	}
	
    return $response;
};

if ($config['settings']['debug']) {
	$app->get('/testcall', function (Request $request, Response $response, array $args) {
		global $layout;
			
		$response->getBody()->write($layout->getPage('urlit'));
		
		return $response;
		
	})->add($validateGet);
}

$app->get('/global-js', function (Request $request, Response $response, array $args) {
	
	global $layout;
		
	$response->getBody()->write(Dispatch::route('public', 'getGloablJs'));
	
	return $response;
	
})->add($validateGet);

$app->get('/email-preview[/{id}]', function (Request $request, Response $response, array $args) {
	
	global $layout;
		
	$response->getBody()->write(Dispatch::route('public', 'emailPreview', $args));
	
	return $response;
	
})->add($validateGet);

$app->get('/dashboard-redirect', function (Request $request, Response $response, array $args) {
	
	header('Location: /#/dashboard');
	exit();
	
})->add($validateGet);

$app->get('/', function (Request $request, Response $response, array $args) {
	
	global $layout;
		
	$response->getBody()->write($layout->getPage('main'));
	
	return $response;
	
})->add($validateGet);


$app->group('/api', function() {
	
	$this->any('/{controller}/{action}[/{params:.*}]', function ($request, $response, $args) {
				
		$controller = !empty($args['controller']) ? $args['controller'] : 'login';
		$action = !empty($args['action']) ? $args['action'] : 'index';
		
		return Dispatch::route($controller, $action, $args);
	
	});
	
})->add($validateApi);