<?php

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

/**
 * Upgrade ciext module to version 3.0.12
 *
 * @author Igor Ratsun
 */
class Ciext_upgrade_3_0_11 extends Abstract_upgrade
{

    public function up()
    {
        // Install ciext_help
        class_alias('Ciext\Controller\AbstractInstallController', 'InstallController');
        Modules::run('ciext_help/ciext_help_install/install');
        
        $file = APPPATH . 'config' . DIRECTORY_SEPARATOR . 'config_assets.php';
        if (!$this->in_file($file, '$config[\'assets_aliases\']')) {
            file_put_contents($file, file_get_contents($file) . PHP_EOL . $this->get_data());
        }

        $routes = APPPATH . 'config' . DIRECTORY_SEPARATOR . 'routes.php';
        if (!$this->in_file($routes, '$route[\'assets\/(.*)\.css\']')) {
            $r_data = str_replace('\'ciext/core/get_assets/$1\';', '\'ciext/core/get_assets/$1\';'
                    . PHP_EOL . '$route[\'assets\/(.*)\.css\'] = \'ciext/assets/css\';'
                    . PHP_EOL . '$route[\'assets\/(.*)\.js\'] = \'ciext/assets/js\';'
                    , file_get_contents($routes));
            file_put_contents($routes, $r_data);
        }

        return ($this->in_file($file, '$config[\'assets_aliases\']') && $this->in_file($routes, '$route[\'assets\/(.*)\.css\']')) ? '3.0.12' : $this->down();
    }

    public function down()
    {
        return '3.0.11';
    }

    protected function in_file($file, $data)
    {
        return (strpos(file_get_contents($file), $data) !== false);
    }

    protected function get_data()
    {
        return '
/**
 * Assets aliases. Like key => full path
 * Example: 
 * \'css\' => [
        \'assets/css/style.min.css\' => FCPATH . \'assets/css/style.css\'
    ],
 */
$config[\'assets_aliases\'] = [
    \'css\' => [],
    \'js\'  => [],
];
$config[\'assets_cache_expires\'] = 1209600;
';
    }

}
