<?php
require "secrets/config.php";

session_start();

$default_page = "domov";

$template_dir = "templates/";

$page_dir = "pages/";

$dynamic_page_dir = "dynamic/";

$subdomain = basename(explode('.', $_SERVER['HTTP_HOST'])[0]);
$page_name = basename($_SERVER["QUERY_STRING"]);;


$srvname = $_SERVER["SERVER_NAME"];

$protocol = $_SERVER['PROTOCOL'] = isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) ? "https://" : "http://";

if (empty($page_name)){
    header("Location: $protocol$srvname/$default_page");
    return;
}


$dynamic_page_file = $page_dir . $subdomain . "/" . $page_name . ".php";
$page_file = $page_dir . $subdomain . "/" . $page_name . ".html";

echo "pozeram do: $page_file";
$dynamic_page_file_global = $page_dir . "global/" . $page_name . ".php";
$page_file_global = $page_dir . "global/" . $page_name . ".html";

$skeleton = file_get_contents($template_dir . "skeleton.html");
$nav = file_get_contents($template_dir . "nav.html");

if (file_exists($dynamic_page_file_global)){
    $page = include_once $dynamic_page_file_global;
}
elseif (file_exists($page_file_global)){
    $page = file_get_contents($page_file_global);
}
elseif (file_exists($dynamic_page_file)){
    $page = include_once $dynamic_page_file;
}
elseif (file_exists($page_file)){
    $page = file_get_contents($page_file);
}
else{
    $page = file_get_contents($template_dir . "404.html");
}

$nav = str_replace("href=\"/$page_name\"", "href=\"/$page_name\" class=\"active\"", $nav);

$out = $skeleton;
$out = str_replace("__TEMPLATE__NAV__", $nav, $out);
$out = str_replace("__TEMPLATE__PAGE__", $page, $out);
$out = str_replace("__TEMPLATE_PAGE_NAME__", $page_name, $out);

echo $out;

?>