<?php
declare(strict_types=1);

use Twig\Extra\Intl\IntlExtension;

require_once($path . 'cms/includes/settings.php');
require_once($path . 'cms/includes/image_folders.php');
require_once($path . 'cms/includes/functions.php');

if (php_sapi_name() != 'cli' && (!defined('CMS_SETUP') || !CMS_SETUP)) {
    require_once($path . 'cms/admin/includes/install.php');
}

$cm = new ContentManager();

// Register cms native event listeners
(new Mtc\Cms\Events\EventServiceProvider())->register();

/*
 * Only when not in admin area
 * and a page has been requested from the CMS
 */
if (!isAdminSection()
    && (
        !isset($_SERVER['REQUEST_URI'])
        || isset($_SERVER['REDIRECT_FULLCMS_SLUG_URI'])
        || parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) == '/'
        || parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) == '/index.php'
    )
) {

    $temp_server = $_SERVER;
    if (php_sapi_name() == 'cli') {
        $temp_server['REQUEST_URI'] = 'cli';
    }

    $cm->initLoadPage($temp_server, $_GET, $_SESSION);

    if (isset($cm->page_load_init_vars['uri_parts']['id_param'])) {
        $_GET['id_param'] = $cm->page_load_init_vars['uri_parts']['id_param'];
    }

    $cache_html = $cm->page_load_init_vars['cache_html'];
    $not_found_page = $cm->page_load_init_vars['not_found_page'];

    $cms_page_to_display = \Mtc\Cms\Models\Page::find($cm->page_load_init_vars['page_id_to_load']);
    if ($cms_page_to_display) {
        $cm->page_load_init_vars['page_id_to_load'] = $cms_page_to_display->id;
    }

    $p = $cm->loadPage(
        $cm->page_load_init_vars['page_id_to_load'],
        $cm->page_load_init_vars['language']
    ); // object of page you are on

    if (
        !empty($_SESSION['adminId']) && defined("CMS_PAGE_PREVIEW") &&
        CMS_PAGE_PREVIEW === true && CMS_PAGE_PREVIEW_ADV === true && !empty($_GET['_cms_preview_page_id'])
    ) {
        $p->id = $p->draft_for_page_id;
    }

    if (defined('CMS_MULTI_LANG') && CMS_MULTI_LANG === true) {
        $twig->addExtension(new IntlExtension());
        $cm_languages = $cm->loadLanguages($p);
        $twig->addGlobal("cm_languages", $cm_languages);
    }
    $twig->addGlobal("p", $p);

    HooksAdapter::add_action('set_page_settings', 'ContentManager::setPageSettings', 10, 1);
    if ($cm->page_load_init_vars['not_found_page'] == false) {
        ContentManager::setPageSettings([$p, &$page_meta, &$twig_variables, &$breadcrumbs]);
    }
}
