<?php

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

/**
 * Description of install
 *
 * @author Igor Ratsun
 */
class install extends MX_Controller
{

    public function __construct()
    {
        $this->load->library(array('parser', 'js_css', 'ciext/ciext'));
        $this->load->config('ciext/install');

        $this->ciext->load_bootstrap();
        $ciext_assets_dir = base_url() . $this->config->item('assets_folder') . '/' . $this->config->item('components_folder') . '/ciext';
        $this->js_css->add_css($ciext_assets_dir . '/css/reset.css');
        $this->js_css->add_css($ciext_assets_dir . '/css/install.css');

        $this->lang->load('ciext/install');
    }

    private function show($content = '')
    {

        $step = $this->uri->get_next_segment('install');
        if (empty($step)) {
            $step = 'check_folders';
        }

        // Create step_nav
        $step_nav_items = array();
        $triger = FALSE;
        foreach ($this->lang->line('step_nav_items') as $k => $v) {
            $step_nav_items[] = array(
                'name'  => (!$triger && $step != $k) ? '<i class="icon-ok"></i> ' . $v : $v,
                'class' => ($step == $k) ? 'active' : 'disabled'
            );
            if ($step == $k) {
                $this->lang->language['title'] .= ' - ' . $v;
                $triger = TRUE;
            }
        }

        $content_array = array(
            'step_nav' => $this->parser->parse('ciext/install/step_nav', array_merge(array('item' => $step_nav_items), $this->lang->language), TRUE),
            'content'  => $content,
            'js_list'  => $this->js_css->get_js_string(),
            'css_list' => $this->js_css->get_css_string()
        );

        $this->parser->parse('ciext/install/template', array_merge($content_array, $this->lang->language));
    }

    public function index()
    {

        $this->check_folders();
    }

    public function check_folders()
    {
        $next = TRUE;
        $items = array();
        foreach ($this->config->item('check_folders') as $v) {
            $perms = substr(sprintf("%o", fileperms($v)), -4);
            if ($perms == '0775' || PHP_OS == 'WINNT') {
                $check = 'ok';
                $class = '';
            } else {
                $check = 'remove';
                $class = 'class="error"';
                $next = FALSE;
            }

            $items[] = array(
                'class'  => $class,
                'folder' => $v,
                'access' => $check
            );
        }

        $content = array_merge(array(
            'items'     => $items,
            'btn_class' => ($next) ? 'btn-success' : 'btn-danger disabled" onclick="return false;void(0);'
                ), $this->lang->language);

        $this->show($this->parser->parse('ciext/install/template_check_folders', $content, TRUE));
    }

    public function configuration()
    {
        $this->check_access();

        // Save configuration
        if (!empty($_POST['super_user_login'])) {
            $allowed_language = $this->config->item('allowed_language');
            $_POST['language'] = $allowed_language[$_POST['language_short']];
            $ciext_path = APPPATH . 'config/ciext.php';
            file_put_contents($ciext_path, str_replace(array(
                '\'admin\'',
                '$config[\'system_login\'] = \'\';',
                '$config[\'system_password_hash\'] = \'\';',
                            ), array(
                '\'' . $_POST['admin_page'] . '\'',
                '$config[\'system_login\'] = \'' . $_POST['super_user_login'] . '\';',
                '$config[\'system_password_hash\'] = \'' . md5(md5($_POST['super_user_pass'] . $_POST['encryption_key'])) . '\';',
                            ), file_get_contents($ciext_path)));
            $config_path = APPPATH . 'config/config.php';
            file_put_contents($config_path, str_replace(array(
                '\'english\'',
                '\'en\'',
                '$config[\'encryption_key\'] = \'\';',
                            ), array(
                '\'' . $allowed_language[$_POST['language_short']] . '\'',
                '\'' . $_POST['language_short'] . '\'',
                '$config[\'encryption_key\'] = \'' . $_POST['encryption_key'] . '\';',
                            ), file_get_contents($config_path)));

            redirect(base_url($_POST['admin_page'] . '/install/database'));
        }

        $this->js_css->add_js(base_url() . $this->config->item('assets_folder') . '/' . $this->config->item('components_folder') . '/ciext/js/jquery.validate.js');

        $languages = array();
        foreach ($this->config->item('allowed_language') as $k => $v) {
            $languages[] = array(
                'key'      => $k,
                'value'    => $v,
                'selected' => ($k == $this->uri->current_language) ? 'selected="selected"' : ''
            );
        }

        $items = array(
            array(
                'ln_name' => $this->lang->line('admin_page') . '<span> ' . base_url() . '</span>',
                'name'    => 'admin_page',
                'value'   => 'admin'
            ),
            array(
                'ln_name' => $this->lang->line('ln_encryption_key'),
                'name'    => 'encryption_key',
                'value'   => md5(time())
            ),
            array(
                'ln_name' => $this->lang->line('login') . ' ' . $this->lang->line('user_data'),
                'name'    => 'super_user_login',
                'value'   => 'admin'
            ),
            array(
                'ln_name' => $this->lang->line('pass') . ' ' . $this->lang->line('user_data'),
                'name'    => 'super_user_pass',
                'value'   => ''
            ),
            array(
                'ln_name' => $this->lang->line('cpass'),
                'name'    => 'super_user_cpass',
                'value'   => ''
            )
        );

        $content = array(
            'languages'   => $languages,
            'items'       => $items,
            'ln_language' => $this->lang->line('ln_language'),
            'ln_btn_next' => $this->lang->line('ln_btn_next'),
        );

        $this->show($this->parser->parse('ciext/install/template_configuration', $content, TRUE));
    }

    public function database()
    {
        $this->check_access();

        // Save database
        if (!empty($_POST['database'])) {
            $db_cnf = APPPATH . '/config/database.php';
            file_put_contents($db_cnf, str_replace(array(
                '\'localhost\'',
                '\'username\' => \'\',',
                '\'password\' => \'\',',
                '\'database\' => \'\',',
                            ), array(
                '\'' . $this->input->post('hostname') . '\'',
                '\'username\' => \'' . $this->input->post('username') . '\',',
                '\'password\' => \'' . $this->input->post('password') . '\',',
                '\'database\' => \'' . $this->input->post('database') . '\',',
                            ), file_get_contents($db_cnf)));
            $this->create_tables();
            $this->set_acl();

            // Set autoload library
            $search = '$autoload[\'libraries\'] = array();';
            $replace = '$autoload[\'libraries\'] = array(\'database\', \'session\', \'parser\', \'js_css\', \'ciext/RT_user\');';
            file_put_contents(APPPATH . '/config/autoload.php', str_replace($search, $replace, file_get_contents(APPPATH . '/config/autoload.php')));

            redirect(base_url() . $this->config->item('admin_page') . '/install/finish');
        }

        $this->js_css->add_js(base_url() . $this->config->item('assets_folder') . '/' . $this->config->item('components_folder') . '/ciext/js/jquery.validate.js');

        $items = array(
            array(
                'ln_name'     => $this->lang->line('hostname'),
                'name'        => 'hostname',
                'value'       => 'localhost',
                'placeholder' => 'localhost'
            ),
            array(
                'ln_name'     => $this->lang->line('login'),
                'name'        => 'username',
                'value'       => 'root',
                'placeholder' => 'root'
            ),
            array(
                'ln_name'     => $this->lang->line('pass'),
                'name'        => 'password',
                'value'       => '',
                'placeholder' => ''
            ),
            array(
                'ln_name'     => $this->lang->line('database'),
                'name'        => 'database',
                'value'       => '',
                'placeholder' => 'ciext'
            )
        );

        $this->show($this->parser->parse('ciext/install/template_database', array('items' => $items, 'ln_btn_next' => $this->lang->line('ln_btn_next')), TRUE));
    }

    public function finish()
    {
        // Install some modules
        $this->install_modules();

        $content = array(
            'admin_link' => base_url($this->config->item('admin_page'))
        );

        $this->show($this->parser->parse('ciext/install/template_finish', array_merge($content, $this->lang->language), TRUE));
    }

    private function check_access()
    {
        // If system installed then show 404
        if ($this->load->is_loaded('session')) {
            show_404('', FALSE);
        }
    }

    private function create_tables()
    {
        $this->load->database('default');

        // Import or create new
        $path = dirname(__DIR__) . '/data/';
        $import = $path . 'import.sql';
        if ($this->is_import()) {
            $sql = file_get_contents($import);
        } else {
            $sql = file_get_contents($path . 'install.sql');
        }

        foreach (explode(';', trim($sql)) as $table) {
            if (!empty($table)) {
                $this->db->query($table);
            }
        }
    }

    private function set_acl()
    {
        // If import then break
        if ($this->is_import()) {

            return FALSE;
        }

        $this->load->library('ciext/installer');
        $menu_img_folder = '/' . $this->config->item('assets_folder') . '/' . $this->config->item('components_folder') . '/ciext/img/dev-tool/';

        $acl = array(
            array(
                'module_acl_name'   => 'acl',
                'module_title'      => $this->lang->line('acl_title'),
                'module_actions'    => $this->lang->line('acl_actions'),
                'module_menu_items' => array(
                    array('acl/acl_user', $this->lang->language['acl_actions']['view_user'], $menu_img_folder . 'users.png', 'view_user'),
                    array('acl/acl_role', $this->lang->language['acl_actions']['view_role'], $menu_img_folder . 'role.png', 'view_role'),
                    array('acl/acl_rule', $this->lang->language['acl_actions']['edit_rule'], $menu_img_folder . 'regulations.png', 'edit_rule')
                )
            ),
            array(
                'module_acl_name'   => 'system',
                'module_title'      => $this->lang->line('system_title'),
                'module_actions'    => $this->lang->line('system_actions'),
                'module_menu_items' => array(
                    array('admin_menu/index', $this->lang->language['system_actions']['edit_amenu'], $menu_img_folder . 'admin-menu.png', 'edit_amenu'),
                    array('mconfig/manager', $this->lang->language['system_actions']['module_manager'], $menu_img_folder . 'install-del-modules.png', 'module_manager'),
                    array('configuration/index', $this->lang->language['system_actions']['system_settings'], $menu_img_folder, 'system_settings'),
                    array('configuration/language', $this->lang->language['system_actions']['language_manager'], $menu_img_folder . 'admin-menu.png', 'language_manager'),
                    array('backup/backup_db', $this->lang->language['system_actions']['backup_db'], $menu_img_folder . 'admin-menu.png', 'backup_db')
                )
            )
        );

        foreach ($acl as $v) {
            $this->installer->install($v['module_acl_name'], $v['module_title'], $v['module_actions'], $v['module_menu_items'], FALSE);
        }
    }

    private function install_modules()
    {
        // If import then break
        if ($this->is_import()) {

            return FALSE;
        }

        // Set superuser id
        $this->load->database('default');
        $this->load->library(array('session', 'ciext/RT_user'));
        $this->rt_user->id_user = -1;

        $this->load->config('ciext/install');
        $this->load->module('ciext/mconfig');

        foreach ($this->config->item('auto_installing_modules') as $v) {
            $rs = $this->mconfig->installForce($v, 'install');
            if ($rs == FALSE) {
                break;
            }
        }
    }

    protected function is_import()
    {
        return file_exists(dirname(__DIR__) . '/data/import.sql');
    }

}
