<?php
/**
 * Main includes file for core
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */

use Illuminate\Support\Facades\App;

define('START_TIME', microtime(true));
define('SITE_PATH', dirname(dirname(__DIR__)));

/* Composer Integration */
require_once SITE_PATH . '/vendor/autoload.php';

session_start();

require_once SITE_PATH . '/core/includes/container.php';

// Exclude legacy aspects from being loaded always
// E.g. Laravel won't need setting of headers on all requests, just web ones (which are added through middleware)
if (!defined('LARAVEL_START')) {
    require_once SITE_PATH . '/core/includes/legacy.php';
}

/** @var Twig_Environment $twig */
$twig = App::make('twig');
$twig_loader = App::make('twig_loader');

/**
* Register auto loader function located in core/src/helpers.php
*/
spl_autoload_register('__mtc_autoload_classes');

foreach (\Mtc\Core\Providers\CoreModuleServiceProvider::getComponentHooks() as $module_hook) {
    require_once $module_hook;
}

if (defined('CMS_ENABLED') && CMS_ENABLED && empty($exclude_header_inc['cms'])) {
    require_once SITE_PATH . '/cms/includes/header.inc.php';
}

if (request()->wantsJson() == false) {
    Mtc\Core\Seo\Redirect::redirectToPage(request()->getPathInfo());
}
$nofollow = DEV_MODE;

/* Admin area authentication */
if (strpos(getcwd() . '/', '/admin/') && php_sapi_name() !== 'cli') {
    if (empty($noauth)) {
        // keep session alive
        if (!empty($_GET['keep_alive'])) {
            session_start();
            exit();
        }

        $adminuser = \Mtc\Core\Gate\Auth::loadUser();
    }
}

foreach (\Mtc\Core\Providers\CoreModuleServiceProvider::getComponentLoaders() as $module_loader) {
    require_once $module_loader;
}

/* Get all user defined settings */
$settings = get_defined_constants(true);
$settings = $settings['user'];

/* Set Global Twig Variables */
$twig->addGlobal('settings', $settings);

if ((defined('ENVIRONMENT') && ENVIRONMENT !== 'production') || $nofollow === true) {
    $page_meta['robots'] ='noindex, nofollow';
} else {
    $page_meta['robots'] ='index, follow';
}

// Only when not in admin area
if (!strpos(getcwd() . '/', '/admin/') && empty($exclude_header_inc['cross_platform_controller'])) {
    // Cross Platform Controller
    require_once SITE_PATH . THEME_PATH . '/templates/controllers/cross.platform.controller.php';
}

if (request()->wantsJson() == false) {
    //Add Twig Globals
    $twig->addGlobal('page_meta', $page_meta);
}

/**
 * Image folders on site - Legacy support ONLY!
 *
 * @var array $image_folders
 * @deprecated
 */
$image_folders = \Mtc\Core\Facades\Media::getFolders();
