<?php
session_write_close();
include __DIR__ . '/includes/includes.php';

$shortcut = ['segments', 'hls', 'dash', 'playlist', 'videoplayback', 'poster', 'subtitle', 'filmstrip', 'embed', 'download', 'embed2'];

$uri = get_page_uris();
$page = !empty($uri[0]) ? trim(pathinfo($uri[0], PATHINFO_FILENAME)) : 'home';

$globalPageDir = FRONTEND_PATH . '/';
$globalPage = $globalPageDir . $page . '.php';

if (in_array($page, $shortcut) && is_file($globalPage)) {
    session_write_close();
    include $globalPage;
} else {
    session_write_close();
    $opt = extractOptions(['site_name', 'slug_embed', 'slug_download', 'slug_request']);
    set_env('site_name', $opt['site_name']);
    set_env('page_type', 'website');
    set_env('title', '');
    set_env('description', '');
    set_env('poster', '');
    set_env('slogan', '');
    if ($page === 'e') {
        session_write_close();
        $page = 'embed';
    } elseif ($page === 'd') {
        session_write_close();
        $page = 'download';
    } elseif ($page === 'r') {
        session_write_close();
        $page = 'embed2';
    } else {
        session_write_close();
        $page = strtr($page, [$opt['slug_embed'] => 'embed', $opt['slug_download'] => 'download', $opt['slug_request'] => 'embed2']);
    }
    $error404page = $globalPageDir . '404.php';
    $globalPage = $globalPageDir . $page . '.php';
    $frontendPage = FRONTEND_THEME_PATH . '/views/' . $page . '.php';

    $backendSlug = $page === ADMIN_DIR ? trim(strtr(get_page(), [$page => '']), '/') : '';
    $backendPage = BACKEND_THEME_PATH . '/views/' . $backendSlug . '.php';
    $globalBackendPage = FRONTEND_PATH . '/backend/' . $backendSlug . '.php';

    if (is_file($backendPage)) {
        session_write_close();
        include $backendPage;
    } elseif (is_file($globalBackendPage)) {
        session_write_close();
        include $globalBackendPage;
    } elseif (is_file($frontendPage)) {
        session_write_close();
        include $frontendPage;
    } elseif (is_file($globalPage)) {
        session_write_close();
        include $globalPage;
    } elseif (is_anonymous()) {
        session_write_close();
        include $error404page;
    } else {
        session_write_close();
        echo '<div style="text-align:center">Silence is golden!</div>';
    }
}
