<?php

use Illuminate\Support\Facades\Event;

/**
 * This file is called from the main core index file
 * and is used to add CMS functionality to the core.
 */
if (!defined('CMS_ENABLED') || CMS_ENABLED === false) {
    header("HTTP/1.0 403 Forbidden");
    exit('This file cannot be called directly.');
}

if ($cm->page_load_init_vars['not_found_page']) {
    Event::dispatch('404');
    header("HTTP/1.0 404 Not Found");
}

if (! $p) {
    header("Location: /");
    exit();
}

redirect_if_trailing_slash();

// For times when the item needs to be in the navigation - but it self doesnt really have any content and is just needed to contain its sub items
// So when you click on it - it redriects to its first child
if ($p->redchild == 1) {
    $children = $p->retrieve_subs($p->id, 1);
    if (count($children) > 0) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: ".$children[0]->get_url());
        exit();
    }
}

if ($cache_html === true) {
    if ($cm->page_load_init_vars['not_found_page']) {
        $cache_file_path = SITE_PATH . THEME_PATH . '/' . $p->slug . ".html";
        if (file_exists($cache_file_path)) {
            include($cache_file_path);
            exit();
        }
    } else {
        $cache_file_path = SITE_PATH . THEME_PATH . "/cache/" . $p->id . ".html";
        if (file_exists($cache_file_path)) {
            include($cache_file_path);
            exit();
        }
    }
}

$seoadmin->setCmsPage($p);

if($cm->controller_exists('master.twig')) {
    include($cm->get_controller('master.twig'));
}

if($cm->controller_exists($p->template)) {
    include($cm->get_controller($p->template));
}

