<?php

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

/**
 * Form for module MODULE
 *
 * @author CIEXT skeleton
 */
class NAME_form
{

    protected $fields = [];
    protected $error_delimeter_open = '<span class="error">';
    protected $error_delimeter_close = '</span>';
    protected $ci;
    protected $error_messages = [];
    protected $values = [];

    public function __construct()
    {
        $this->ci = & get_instance();
        
        // Set fields
        $this->fields = [
            [
                'field' => 'id',
                'label' => $this->ci->lang->line('Id'),
                'rules' => 'intval'
            ],
            [
                'field' => 'email',
                'label' => $this->ci->lang->line('Email'),
                'rules' => 'trim|xss_clean|prep_for_form|required|valid_email|min_length[4]'
            ],
        ];
        
        $this->ci->load->library('form_validation');
        $this->ci->form_validation->set_error_delimiters($this->error_delimeter_open, $this->error_delimeter_close);
        // Set rules
        $this->ci->form_validation->set_rules($this->fields);
    }

    /**
     * Validate
     * @return boolean
     */
    public function is_valid()
    {
        // Custom check
        $valid = true;
//        if ($this->ci->input->post('full_name') == 'test') {
//            $this->set_error_message('full_name', 'some error');
//            $valid = false;
//        }

        return ($this->ci->form_validation->run() && $valid);
    }

    /**
     * Get value by key or all values
     * @param string $key
     * @return mixed
     */
    public function get_value($key = '')
    {
        if (empty($this->values) && $this->is_valid()) {
            foreach ($this->fields as $field) {
                $this->values[$field['field']] = $this->ci->input->post($field['field']);
            }
        }
        
        // Return all values if empty key
        if (empty($key)) {
            return $this->values;
        }

        return isset($this->values[$key]) ? $this->values[$key] : null;
    }

    /**
     * Get error message
     * @param string $key
     * @return string
     */
    public function get_error_message($key = '')
    {
        $form_error = $this->ci->form_validation->error($key);
        if (!empty($form_error)) {

            return $form_error;
        }

        return !empty($this->error_messages[$key]) ? $this->error_messages[$key] : '';
    }

    /**
     * Set error message
     * @param string $key
     * @param string $message
     * @return self
     */
    public function set_error_message($key, $message = '')
    {
        $this->error_messages[$key] = $this->error_delimeter_open . $message . $this->error_delimeter_close;
        return $this;
    }

}
