<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Minify and merge css and js files 
 *
 * @author Igor Ratsun
 */
class Assets extends MX_Controller
{

    protected $aliases = [];
    protected $cache_expires = 1209600;

    public function __construct()
    {
        parent::__construct();
        $this->load->allBootstrap();
        $this->aliases = $this->config->item('assets_aliases');
        $this->cache_expires = (int) $this->config->item('assets_cache_expires');
    }

    public function css()
    {
        $alias = $this->uri->uri_string();
        $aliases = $this->aliases['css'];
        if (!isset($aliases[$alias])) {
            show_404();
        }
        $output = $this->load->library('cssmin', $this->load_files($aliases[$alias]))->min();
        
        return $this->set_cache()->output->set_content_type('text/css')->set_output($output);
    }
    
    public function js()
    {
        $alias = $this->uri->uri_string();
        $aliases = $this->aliases['js'];
        if (!isset($aliases[$alias])) {
            show_404();
        }
        $output = $this->load->library('jsmin', '')->minify($this->load_files($aliases[$alias]));
        
        return $this->set_cache()->output->set_content_type('application/javascript')->set_output($output);
    }

    protected function load_files($files = [])
    {
        if (!is_array($files)) {
            return $this->load_files([$files]);
        }
        $output = '';
        foreach ($files as $file) {
            if (file_exists($file)) {
                $output .= file_get_contents($file);
            }
        }

        return $output;
    }

    protected function set_cache()
    {
        // Enable GZip encoding.
        ob_start("ob_gzhandler");
        // Enable caching
        header('Cache-Control: public');
        // Expire in 2 weeks
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $this->cache_expires) . ' GMT');

        return $this;
    }

}
