<?php
date_default_timezone_set("Europe/Berlin");
error_reporting(E_ALL);
include_once("config.php");

session_set_cookie_params([
	'lifetime' => 86400,
	'path' => '/',
	'domain' => $RUNTIME['DOMAIN'],
	'httponly' => true,
	'secure' => true,
	'samesite' => 'Lax'
]);

session_start();
if(!isset($_SESSION['csrf']) || strlen($_SESSION['csrf']) != 64) {
	$_SESSION['csrf'] = bin2hex(random_bytes(32));
}

include_once 'classen/MAIL/PHPMailer.php';
include_once 'classen/MAIL/SMTP.php';

include_once("classen/utils.php");
include_once("classen/HTML.php");
include_once("classen/GoogleAuthenticator.php");
include_once("classen/OpenSim.php");
include_once("classen/discord.php");

$RUNTIME['OPENSIM'] = new OpenSim();

function isValidEndpoint(string $pageName, string $dirPrefix) {
	return preg_match("/[a-zA-Z0-9\.]{1,100}/", $pageName) && file_exists("./".$dirPrefix."/".$pageName.".php");
}

//TODO: add API keys and/or rate limiting
if(isset($_REQUEST['api'])) {
	if(isValidEndpoint($_REQUEST['api'], 'api')) {
		include "./api/".$_REQUEST['api'].".php";
	} else {
		die("ERROR; ENDPOINT NOT EXIST");
	}

	die();
}

if ($handle = opendir('./plugins/')) {
	while (false !== ($entry = readdir($handle))) {
		if ($entry != "." && $entry != "..") {
			include_once "./plugins/".$entry;
		}
	}

	closedir($handle);
}

if(isset($_REQUEST['logout']) && $_REQUEST['logout'] == '1') {
	$_SESSION = array();
}

if(isset($_SESSION['LOGIN']) && $_SESSION['LOGIN'] == 'true') {
	if(!isset($_REQUEST['page'])) {
		include './pages/dashboard.php';
	} else if(isValidEndpoint($_REQUEST['page'], 'pages')) {
		include "./pages/".$_REQUEST['page'].".php";
	} else {
		include "./pages/error.php";
	}
	
	die();
}

if(isset($_REQUEST['page']) && $_REQUEST['page'] == "register") {
	include "./pages/register.php";
} else {
	include "./pages/login.php";
}

?>