<?php

namespace Config;

use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;

Events::on('pre_system', static function () {
    if (ENVIRONMENT !== 'testing') {
/*
        if (ini_get('zlib.output_compression')) {
            throw FrameworkException::forEnabledZlibOutputCompression();
        }
        */

        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        ob_start(static fn ($buffer) => $buffer);
    }

    /*
     * --------------------------------------------------------------------
     * Debug Toolbar Listeners.
     * --------------------------------------------------------------------
     * If you delete, they will no longer be collected.
     */
    if (CI_DEBUG && ! is_cli()) {
        Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
        Services::toolbar()->respond();
        // Hot Reload route - for framework use on the hot reloader.
        if (ENVIRONMENT === 'development') {
            Services::routes()->get('__hot-reload', static function () {
                (new HotReloader())->run();
            });
        }
    }
});


Events::on('post_controller_constructor', function () {

    if (ENVIRONMENT !== 'testing') {
        if(!site_config('optimize',true)){
            return ;
        }
        while (ob_get_level() > 0)
        {
            ob_end_clean();
        }
  
        ob_start(function ($buffer) {
        $search = array(
            '/\n/', '/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '/<!--(.|\s)*?-->/' 
        );
    
        $replace = array('','>','<','\\1','');    
        $buffer = preg_replace($search, $replace, $buffer);
        return $buffer;
        });
    
        }

    
  });