<?php


$mode = 'production';

if ($argv[1] == 'dev') {
    $mode = 'dev';
}


$base_root = getcwd() . '/../../../';

require_once($base_root. 'vendor/minificator/Utils.php');
require_once($base_root. 'vendor/minificator/Colors.php');
require_once($base_root. 'vendor/minificator/Minifier.php');
require_once($base_root. 'vendor/minificator/JSmin.php');

$css_template_file = $base_root . 'engine/admin/tpls/include/_static_css_headers.htm';
$js_template_file  = $base_root . 'engine/admin/tpls/include/_static_js_headers.htm';

$static_root = '/admin/assets/';

$css_files = [
    "bootstrap.css",
    "chosen.min.css",
    "fonts_full.css",
    "jquery-ui.css",
    "jquery-ui.structure.min.css",
    "jquery-ui.theme.min.css",
    "jquery.autocomplete.css",
    "jquery.fancybox.min.css",
    "jquery.periodpicker.min.css",
    "redactor.css",
    "custom.css"

];

$js_files = [
        "jquery.js",
        "bootstrap4.min.js",
        "chosen.jquery.min.js",
        "clipboard.min.js",
        "jquery.fancybox.min.js",
        "jquery-ui.min.js",
        "jquery.autocomplete.js",
        "jquery.form.js",
        "jquery.input.counter.js",
        "jquery.maskedinput-1.3.min.js",
        "jquery.periodpicker.full.min.js",
        "jquery.tablesorter.min.js",
        "jquery.utils.min.js",
        "redactor.js",
        "bootstrap4.utils.js"
];

$ts = time();

$out_css = '';
$out_js = '';
switch($mode) {
    case 'production':
        // Минифицируем статику
        $cssmin = new Minifier();
        $input_css = "";
        foreach($css_files as $filename) {
            $input_css .= file_get_contents($base_root . 'css/'.$filename);
        }
        $output_css = $cssmin->run($input_css);
        file_put_contents('css/_pack.css', $output_css);
        $out_css .= '<link rel="stylesheet" href="'.$static_root.'css/_pack.css?'.$ts.'">'.PHP_EOL;

        $input_js = "";
        foreach($js_files as $filename) {
            $input_js .= file_get_contents('js/'.$filename);
        }
        $output_js = JSMin::minify($input_js);
        file_put_contents($base_root .'js/_pack.js', $output_js);
        $out_js .= '<script src="'.$static_root.'js/_pack.js?'.$ts.'"></script>'.PHP_EOL;
        break;
    default:
        // Просто сохраняем заголовки
        foreach($css_files as $filename) {
            $out_css .= '<link rel="stylesheet" href="'.$static_root.'css/'.$filename.'?'.$ts.'">'.PHP_EOL;
        }

        foreach($js_files as $filename) {
            $out_js .= '<script src="'.$static_root.'js/'.$filename.'?'.$ts.'"></script>'.PHP_EOL;
        }
        break;
}

// save headers to templates
file_put_contents($css_template_file, $out_css);
file_put_contents($js_template_file, $out_js);
echo $mode . ' mode - done' . PHP_EOL;
