<?php

//Init System

require_once("__backend/config.php");
require_once("__backend/regex.php");
require_once("__backend/functions.php");
require_once("__backend/language/language.php");

//Redirect to default language if no language has been picked.

if ($languageDefault) {
    header("location: ".FOLDER."/".LANGUAGE_DEFAULT."/");

    exit;
}

//Router

$page = false;

if (isset($_GET['page']) && !empty($_GET['page'])) {
    foreach ($languagePage as $key => $link) {
        if ($link['link'] == $_GET['page']) {
            $page = $key;

            break;
        }
    }
}

session_start();

$loggedIn = false;

if (isset($_SESSION['id']) && is_numeric($_SESSION['id']) && $_SESSION['id'] > 0) {
    $loggedIn = true;
}

//If page doesn't exists, then redirect the user to either profile or login page.
if ($page === false || !$loggedIn && $languagePage[$page]['display'] == 2 || $loggedIn && $languagePage[$page]['display'] == 1) {
    if ($loggedIn) {
        header("location: {$languagePage['profile']['link']}");
    } else {
        header("location: {$languagePage['login']['link']}");
    }
    
    exit;
}

//Initialize error and success handler
$success[$page] = [];
$error[$page] = [];

//Backend (controller)
require_once("__backend/pages/". $page .".php");

//Frontend part
if ($loggedIn) {
	require_once("template/".TEMPLATE."/_header.php");
	require_once("template/".TEMPLATE."/". $page .".php");
	require_once("template/".TEMPLATE."/_footer.php");
} else {
    require_once("template/".TEMPLATE."/". $page .".php");
}