<?php

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Cache;
use Twig\Extra\Intl\IntlExtension;
use Symfony\Component\Finder\Finder;
use Illuminate\Support\Facades\Config;

$template_paths = [];
$template_paths[] = SITE_PATH . '/sites/' . SITE . '/templates/';
$template_paths[] = SITE_PATH . '/sites/default/templates/';

$paths = [
    'loaders'   => ['modules/*/loader.php', 'plugins/*/loader.php'],
    'hooks'     => ['modules/*/hooks.php', 'plugins/*/hooks.php'],
    'templates' => ['modules/*/templates/', 'plugins/*/templates/'],
];

$cacheKeys = [
    'loaders'   => 'twig.modules.plugins',
    'hooks'     => 'twig.modules.plugins.hooks',
    'templates' => 'twig.modules.plugins.templates',
];

$results = [];

foreach ($paths as $type => $patterns) {
    $globbed = function () use ($patterns) {
        $files = [];
        foreach ($patterns as $pattern) {
            $files = array_merge($files, glob(SITE_PATH . '/' . $pattern, GLOB_NOSORT) ?: []);
        }
        return $files;
    };

    if (config('app.env') === 'production') {
        $results[$type] = Cache::rememberForever($cacheKeys[$type], $globbed);
    } else {
        $results[$type] = $globbed();
    }
}

// Assign variables
$loaded_module_paths = $results['loaders'];
$loaded_module_hooks = $results['hooks'];
$template_paths = array_merge($template_paths, $results['templates']);
 
/*
 * Add shop and CMS by default to twig array
 *
 * This stops dependant plugins from throwing errors
 * when using mixins.
 */
if (is_dir(SITE_PATH . '/shop/templates/')) {
    $template_paths[] = SITE_PATH . '/shop/templates/';
}

if (is_dir(SITE_PATH . '/cms/templates/')) {
    $template_paths[] = SITE_PATH . '/cms/templates/';
}

if (is_dir(SITE_PATH . '/abs/templates/')) {
    $template_paths[] = SITE_PATH . '/abs/templates/';
}

$template_paths[] = SITE_PATH . '/core/templates/';

$view_paths = Config::get('view.paths');
foreach ($view_paths as $view_path) {
    $template_paths[] = $view_path;
}

$twig_loader = new \Twig\Loader\FilesystemLoader(
    $template_paths
);

$twigCachePath = storage_path('framework/cache/twig');
$isProduction = config('app.env') === 'production';

$twig = new \Twig\Environment(
    $twig_loader,
    [
        'cache' => ($isProduction && empty($_REQUEST['twig_cache']))
            ? $twigCachePath
            : false,
        'auto_reload' => !$isProduction,
        'debug' => !$isProduction,
    ]
);

$twig->addExtension(new IntlExtension());

App::instance('twig', $twig);
