<?php

namespace Ciext\Form;

abstract class AbstractForm
{

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

    /**
     * @return array rules for CI_Form_validation
     */
    abstract public function get_rules();
    

    public function __construct()
    {
        $this->ci = & get_instance();
        $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->get_rules());
    }

    /**
     * Validate
     * @return boolean
     */
    public function is_valid()
    {
        return $this->ci->form_validation->run();
    }

    /**
     * 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->get_rules() 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;
    }

}
