<?php
/**
 * Main Core Controller
 *
 * @author  Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 * @version 0.1
 */
require_once $path . "core/includes/header.inc.php";

// sitemap redirect
if ($_SERVER['REQUEST_URI'] == "/sitemap.xml") {
    header("Location: " . THEME_PATH . "/generator/sitemap.xml");
    die();
}

// initialise SEO Admin
$seoadmin = new Seo();

if (defined('CMS_ENABLED') && CMS_ENABLED === true) {
    include_once $path . 'cms/index.php';
}

$seoadmin->getSeoData();

// allow SEO admin to override page title and description if available
if (!empty($seoadmin->data['title'])) {
    $page_meta['title'] = $seoadmin->data['title'];
}

if (!empty($seoadmin->data['description'])) {
    $page_meta['description'] = $seoadmin->data['description'];
}

// add canonical url if available
if (isset($seoadmin->data['canonical_path']) && !empty($seoadmin->data['canonical_path'])) {
    $page_meta['canonical'] = $seoadmin->data['canonical_path'][0];
}

if (defined('BREADCRUMBS') && BREADCRUMBS === true) {
    if (is_array($breadcrumbs)) {
        array_unshift($breadcrumbs, [
            'url' => '/',
            'name' => 'Home',
        ]);
        if (defined('BREADCRUMBS_LINK_LAST_CRUMB') && BREADCRUMBS_LINK_LAST_CRUMB === false) {
            $breadcrumbs[count($breadcrumbs) - 1]['url'] = null;
        }
    }
}

$page_meta['page_template'] = 'content.twig';
$page_meta['layout'] = 'default.twig';

if (class_exists(ContentManager::class)) {
    ContentManager::setPageSettings([
        isset($p) ? $p : null,
        &$page_meta,
        &$twig_variables,
        &$breadcrumbs
    ]);
}

$twig_variables['page_meta'] = $page_meta;


if (defined('BREADCRUMBS') && BREADCRUMBS === true) {
    $twig->addGlobal('breadcrumbs', $breadcrumbs);
}

// Render the page
$twig->display(
    'pages/' . $page_meta['page_template'],
    $twig_variables
);
