<?php

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

class chunk_l_migration extends CI_Model implements chunk_interface
{

    public function get_admin_html()
    {
        return '<div class="control-group"><div class="controls">'
                . form_checkbox('create_l_migration_file', '1', $this->post('create_l_migration_file')) . ' ' . $this->lang->line('Create migration library, from: ')
                . ' ' . form_input('l_migration_from_version', $this->post('l_migration_from_version', '0'), 'placeholder="' . $this->lang->line('Enter version from') . '"')
                . ' to: ' . form_input('l_migration_to_version', $this->post('l_migration_to_version', '1.0.0'), 'placeholder="' . $this->lang->line('Enter version to') . '"')
                . '</div></div>';
    }

    public function run()
    {
        // Create install controller
        if ($this->input->post('create_l_migration_file')) {
            $mf = $this->skeleton_model_admin->getModuleFolder();
            $sf = $this->skeleton_model_admin->getSrcFolder();

            // Create folders
            $this->skeleton_model_admin->createFolder($mf . '/config');
            $this->skeleton_model_admin->createFolder($mf . '/libraries/migrations');

            $config = $mf . '/config/upgrade.php';
            if (!file_exists($config)) {
                $this->skeleton_model_admin->createFile($config, $this->parse_file($sf . '/config/upgrade.php'));
            }

            $migration = $mf
                    . '/libraries/migrations/'
                    . ucfirst($this->input->post('moduleName')) . '_upgrade_' . $this->prapere_version($this->post('l_migration_from_version', '0'))
                    . '.php';
            $source = $this->parse_file($sf . '/libraries/migrations/upgrade_0.php');

            if (!file_exists($migration)) {
                $this->skeleton_model_admin->createFile($migration, $source);
            }

            return TRUE;
        }
    }

    protected function post($key, $default = '')
    {
        $post = $this->input->post($key);

        return !empty($post) ? $post : $default;
    }

    protected function parse_file($file = '')
    {
        $content = file_get_contents($file);
        $from = ['MODULE', 'FROM_VERSION', 'TO_VERSION', 'FILE_VERSION'];
        $to = [
            ucfirst($this->input->post('moduleName')),
            $this->post('l_migration_from_version', '0'),
            $this->post('l_migration_to_version', '1.0.0'),
            $this->prapere_version($this->post('l_migration_from_version', '0'))
        ];

        return str_replace($from, $to, $content);
    }

    protected function prapere_version($version = 0)
    {
        return str_replace(['.', ',', '/'], '_', $version);
    }

}
