<?php

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

class chunk_l_form extends CI_Model implements chunk_interface
{

    public function get_admin_html()
    {
        return '<div class="control-group"><div class="controls">'
                . form_checkbox('create_l_form', '1', $this->post('create_l_form')) . ' ' . $this->lang->line('Create form library')
                . ' ' . form_input('l_form_name', $this->post('l_form_name'), 'placeholder="' . $this->lang->line('Enter file name') . '"')
                . '</div></div>';
    }

    public function run()
    {
        // Create install controller
        if ($this->input->post('create_l_form')) {
            $mf = $this->skeleton_model_admin->getModuleFolder();
            $sf = $this->skeleton_model_admin->getSrcFolder();
            $folder = $mf . '/libraries';
            $name = ucfirst(str_replace('_form', '', $this->post('l_form_name', $this->post('moduleName'))));
            $file = $folder . '/' . $name . '_form.php';

            if (file_exists($file)) {
                return true;
            }

            $this->skeleton_model_admin->createFolder($folder);
            $this->skeleton_model_admin->createFile($file, $this->parse_file($sf . '/libraries/form.php', [
                        'MODULE' => $name,
                        'NAME'   => $name
            ]));

            return TRUE;
        }

        return false;
    }

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

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

    protected function parse_file($file = '', $data = [])
    {
        $content = file_get_contents($file);

        return str_replace(array_keys($data), array_values($data), $content);
    }

}
