<?php
/**
 * i-doit
 *
 * Call stylesheet data through cache/smarty.
 *
 * @package     i-doit
 * @subpackage  General
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

use PhpParser\Node\Expr\BinaryOp\LogicalAnd;

header("Content-Type: text/css");

/**
 * Enabling a cache lifetime of one month
 *
 * Cache will reload after installing a module or updating i-doit because
 * of a new token parameter with the value of the last system update timestamp
 */
isys_core::expire(isys_convert::MONTH);

$tpl = isys_application::instance()->container->get('template');

global $g_dirs;

if (file_exists(isys_glob_get_temp_dir() . 'compiled-style.css')) {
    echo file_get_contents(isys_glob_get_temp_dir() . 'compiled-style.css');
    die;
}

// Read every file from this directory.
$cssDirectory = $g_dirs["css_abs"];

// Set CSS variables to use.
$tpl->assign("dir_images", $g_dirs["images"]);

isys_component_signalcollection::get_instance()
    ->emit('mod.css.beforeProcess');

try {
    $tpl->loadFilter('output', 'TrimWhiteSpaceEnhanced');
} catch (Exception $e) {
    // Do nothing.
}

try {
    if (!is_dir($cssDirectory)) {
        throw new isys_exception_filesystem('"' . $cssDirectory . '" is not a directory!', 'The given directory "' . $cssDirectory . '" is no directory or does not exist.');
    }

    if (!file_exists($cssDirectory . '/style.css') || !is_readable($cssDirectory . '/style.css')) {
        throw new isys_exception_filesystem('The main "style.css" file does not exist or is not readable - please go sure that the latest i-doit update ran without errors!');
    }

    $combinedCss = $tpl->fetch($cssDirectory . '/style.css') . PHP_EOL . PHP_EOL;

    foreach (glob($cssDirectory . '/*.css') as $file) {
        // Skip print and 'base' styles.
        if (in_array(basename($file), ['style.css', 'print.css'], true)) {
            continue;
        }

        $combinedCss .= '/* Contents of ' . basename($file) . ' */' . PHP_EOL . $tpl->fetch($file) . PHP_EOL . PHP_EOL;
    }
} catch (isys_exception $exception) {
    die("Error while creating CSS: " . $exception->getMessage());
}

isys_component_signalcollection::get_instance()
    ->emit('mod.css.processed', $combinedCss);

echo $combinedCss;

if (isys_settings::get('css.caching.cache-to-temp', true)) {
    isys_file_put_contents(isys_glob_get_temp_dir() . 'compiled-style.css', $combinedCss);
}

die;
