<?php

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

class Rtform_default_form extends \Ciext\Form\AbstractForm
{
    protected $rules = [];

    public function get_rules()
    {
        return $this->rules;
    }

    public function load_fields($form_code): self
    {
        if (empty($this->rules)) {
            $ci = get_instance();
            $form = $ci->db->select('fields')->where('code', $form_code)->get('rtform')->row_array();
            if (!empty($form['fields'])) {
                foreach (array_chunk(json_decode(htmlspecialchars_decode($form['fields']), true), 4) as $field) {
                    if (empty($field[0])) {
                        continue;
                    }
                    $this->set_rule($field[0], $field[2], explode('|', trim('trim|' . $field[3], '|')), $field[1]);
                }
                $ci->form_validation->set_rules($this->get_rules());
            }
        }

        return $this;
    }

    public function set_rule($field, $label, $rules, $type = 'input'): self
    {
        $this->rules[] = [
            'field' => $field,
            'label' => $label,
            'rules' => $rules,
            'type'  => $type,
        ];

        return $this;
    }
}
