<?php
function d() {
	
}

function error($code = 403) {
	if($code == 404) {
		header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
		header("Status: 404 Not Found");
		$_SERVER['REDIRECT_STATUS'] = 404;
		return $GLOBALS['basedir'] . 'pages/errors/404.php';
	} else {
		header($_SERVER["SERVER_PROTOCOL"]." 403 Forbidden");
		header("Status: 403 Forbidden");
		$_SERVER['REDIRECT_STATUS'] = 403;
		return $GLOBALS['basedir'] . 'pages/errors/403.php';
	}
}

function getRequestPage($request = '') {
	if($request == '' or $request == '/') {
		return array(array(), array());
	}
	$rArray = explode('/', $request);
	$args = array();
	while(!file_exists($file = 'pages/' . implode('/', $rArray) . '.php') and $rArray != NULL) {
		array_unshift($args, array_pop($rArray));
	}
	return array($rArray, $args);
}

include 'libs/utils.php';

$baseurl = trim(full_url($_SERVER), '/') . '/';
$basedir = dirname($_SERVER['SCRIPT_FILENAME']) . '/';

$dirty_req = preg_replace('/(\?.*)/', '', $_SERVER['REQUEST_URI']);

$dn = dirname($_SERVER['SCRIPT_NAME']);
$dirty_req = substr($dirty_req, strlen($dn));

$dirty_req = trim($dirty_req, '/');
if(strlen($dirty_req) > 0) {
	$baseurl = substr(trim(preg_replace('/(\?.*)/', '', $baseurl), '/'), 0, -strlen($dirty_req));
}

if(strlen($dirty_req) > 0) {
	if(substr($_SERVER['REQUEST_URI'], -1) === '/') {
		$redirect_url = trim(full_url($_SERVER), '/');
		header("HTTP/1.1 301 Moved Permanently"); 
		header("Location: $redirect_url");
		die;
	}
}

$request = $dirty_req;

ob_start();

$r = getRequestPage($request);
$GLOBALS['args'] = $r[1];

if(empty($r[0])) {
	if(empty($r[1])) {
		include $basedir . 'pages/home.php';
	} else {
		include error(404);
	}
} else {
	include $basedir.'pages/'.implode('/', $r[0]).'.php';
}

$html = ob_get_clean();

echo $html;