<?php
/**
 * Main Core Controller
 *
 * @author  Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 * @version 0.1
 */

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

/**
 * -----------------------------------------------------------------------------------------
 * Based on `https://github.com/mecha-cms/mecha-cms/blob/master/system/kernel/converter.php`
 * -----------------------------------------------------------------------------------------
 */

// CSS Minifier => http://ideone.com/Q5USEF + improvement(s)
function minify_css($input) {
    if(trim($input) === "") return $input;
    return preg_replace(
        array(
            // Remove comment(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s',
            // Remove unused white-space(s)
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~+]|\s*+-(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si',
            // Replace `0(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)` with `0`
            '#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si',
            // Replace `:0 0 0 0` with `:0`
            '#:(0\s+0|0\s+0\s+0\s+0)(?=[;\}]|\!important)#i',
            // Replace `background-position:0` with `background-position:0 0`
            '#(background-position):0(?=[;\}])#si',
            // Replace `0.6` with `.6`, but only when preceded by `:`, `,`, `-` or a white-space
            '#(?<=[\s:,\-])0+\.(\d+)#s',
            // Minify string value
            '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
            '#(\/\*(?>.*?\*\/))|(\burl\()([\'"])([^\s]+?)\3(\))#si',
            // Minify HEX color code
            '#(?<=[\s:,\-]\#)([a-f0-6]+)\1([a-f0-6]+)\2([a-f0-6]+)\3#i',
            // Replace `(border|outline):none` with `(border|outline):0`
            '#(?<=[\{;])(border|outline):none(?=[;\}\!])#',
            // Remove empty selector(s)
            '#(\/\*(?>.*?\*\/))|(^|[\{\}])(?:[^\s\{\}]+)\{\}#s'
        ),
        array(
            '$1',
            '$1$2$3$4$5$6$7',
            '$1',
            ':0',
            '$1:0 0',
            '.$1',
            '$1$3',
            '$1$2$4$5',
            '$1$2$3',
            '$1:0',
            '$1$2'
        ),
        $input);
}
// JavaScript Minifier
function minify_js($input) {
    if(trim($input) === "") return $input;
    return preg_replace(
        array(
            // Remove comment(s)
            '#\s*("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')\s*|\s*\/\*(?!\!|@cc_on)(?>[\s\S]*?\*\/)\s*|\s*(?<![\:\=])\/\/.*(?=[\n\r]|$)|^\s*|\s*$#',
            // Remove white-space(s) outside the string and regex
            '#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/)|\/(?!\/)[^\n\r]*?\/(?=[\s.,;]|[gimuy]|$))|\s*([!%&*\(\)\-=+\[\]\{\}|;:,.<>?\/])\s*#s',
            // Remove the last semicolon
            '#;+\}#',
            // Minify object attribute(s) except JSON attribute(s). From `{'foo':'bar'}` to `{foo:'bar'}`
            '#([\{,])([\'])(\d+|[a-z_][a-z0-9_]*)\2(?=\:)#i',
            // --ibid. From `foo['bar']` to `foo.bar`
            '#([a-z0-9_\)\]])\[([\'"])([a-z_][a-z0-9_]*)\2\]#i'
        ),
        array(
            '$1',
            '$1$2',
            '}',
            '$1$3',
            '$1.$3'
        ),
        $input);
}

if(in_array(config('app.env'), ['demo', 'production'])) {
    ob_start("minify_html");
}









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

/**
 * Check if page caching is set
 * TODO : Change to just CACHE_PAGES as caching should be handled by core.
 */
if (defined('CMS_HTML_CACHE_PAGES') && CMS_HTML_CACHE_PAGES === true) {
    $cache_html = true;
} elseif (!isset($cache_html)) {
    $cache_html = false;
}

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']) && count($seoadmin->data['canonical_path']) > 0) {
     $page_meta['canonical'] = $seoadmin->data['canonical_path'][0];
}

if (defined('BREADCRUMBS') && BREADCRUMBS === true) {
    if(!empty($breadcrumbs)) {
        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';

$args = [
    isset($p) ? $p : null,
    &$page_meta,
    &$twig_variables,
    &$breadcrumbs
];

HooksAdapter::do_action_ref_array('set_page_settings', [$args]);

$twig_variables['page_meta'] = $page_meta;


if (defined('BREADCRUMBS') && BREADCRUMBS === true) {
    $twig_variables['breadcrumbs'] =  $breadcrumbs;
}

if ($cache_html === true) {
    ob_start();
}

// Render the page
echo template(
    'pages/' . $page_meta['page_template'],
    $twig_variables
);

if ($cache_html === true) {

    $page_html = ob_get_contents();
    ob_end_flush();

    $cache_disclaimer = "<!--CACHE FOR PAGE ID:"
    . $p->id . " SLUG:"
    . $p->slug . " GENERATED ".date("d/m/Y H:i:s")
    . " -->";

    if ($not_found_page === true) {
        $cache_file_path = SITE_PATH . THEME_PATH . "/" . $p->slug . ".html";
    } else {
        $cache_file_path = SITE_PATH . THEME_PATH . "/cache/" . $p->id . ".html";
    }

    $fw = fopen($cache_file_path, "w");

    fputs(
        $fw,
        $page_html . $cache_disclaimer,
        strlen($page_html . $cache_disclaimer)
    );

    fclose($fw);

}
