<?php

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

class Parser_rtform_open
{

    public function parse($form_code, $form_attributes = '', $multipart = false, $hash_time_point = 3)
    {
        $ci = get_instance();
        $ci->load->model('rtform/rtform_tmodel');
        $ci->load->library('form_hash')->set_time_point((int)$hash_time_point);
        $form = $ci->rtform_tmodel->fetch_by_code($form_code);

        if (empty($form)) {
            show_error('Form with code "' . $form_code . '" not found');
        }

        $id = 'rtform_' . $form_code;
        if (empty($form_attributes)) {
            $form_attributes = [
                'id' => $id,
            ];
        }

        // Process form
        if ($ci->input->post('rtform_id') && $ci->input->post('rtform_id') == $form['id_rtform']) {
            $form_class = $ci->load->library($form['form_class']);
            if ($form_class->is_valid() && $ci->form_hash->check_form_hash()) {
                $ci->load->model('rtform/rtform_request_tmodel');
                $ci->rtform_request_tmodel->add([
                    'id_rtform' => $form['id_rtform'],
                    'date'      => date('Y-m-d H:i:s'),
                    'data'      => json_encode($form_class->get_value()),
                ]);

                // Set message
                $ci->load->library('rtform/parser/parser_rtform_message')->set_message($form['success_message']);
            }
        }

        $ci->load->helper('form');

        $url = $ci->uri->uri_string() . '#' . $id;
        $hidden = ['rtform_id' => $form['id_rtform']];

        $form_open = $multipart ? form_open_multipart($url, $form_attributes, $hidden) : form_open($url, $form_attributes, $hidden);

        return $form_open . $ci->form_hash->set_form_hash();
    }

}