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

class Parser_rtform_row
{
    protected $cache = [];

    public function parse($form_code, $form_field)
    {
        $ci = get_instance();
        $ci->load->helper('form');

        $rule = $this->get_rule($form_code, $form_field);
        if (empty($rule)) {

            return '';
        }

        $data = [
            'type'  => 'text',
            'name'  => $form_field,
            'id'    => 'rtform_' . $form_code . '_' . $form_field,
            'value' => $ci->load->library('rtform/parser/parser_form_set_value')->parse($form_field),
        ];

        if (in_array('required', $rule['rules'])) {
            $data['required'] = 'required';
        }

        if (in_array('valid_email', $rule['rules'])) {
            $data['type'] = 'email';
        }

        return $this->render($data, $rule);
    }

    public function load_library($form_code)
    {
        if (empty($this->cache[$form_code])) {
            $ci = get_instance();
            $form = $ci->db->select('form_class')->where('code', $form_code)->get('rtform')->row_array();
            $this->cache[$form_code] = $ci->load->library($form['form_class']);
        }

        return $this->cache[$form_code];
    }

    protected function get_rule($form_code, $form_field)
    {
        foreach ($this->load_library($form_code)->get_rules() as $item) {
            if ($item['field'] == $form_field) {

                return $item;
            }
        }

        return null;
    }

    protected function render($data, $rule)
    {
        $str = '<div class="form_group">';

        if (!empty($rule['label'])) {
            $str .= '<label for="' . $data['id'] . '">' . $rule['label'];
            if (in_array('required', $rule['rules'])) {
                $str .= ' *';
            }
            $str .= '</label>';
        }

        return $str . form_input($data) . form_error($data['name']) . '</div>';
    }
}