<?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,
            ];
        }

        $recaptcha_key = $ci->load->library('ciext/configurator')->set_resource('system')->item('recaptcha_site_key');

        // 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()
                && (empty($recaptcha_key) || $ci->load->library('recaptcha/recaptcha')->is_valid_token())
            ) {
                $ci->load->model('rtform/rtform_request_tmodel');
                $ci->rtform_request_tmodel->add_data($form['id_rtform'], $form_class->get_value());

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

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

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

        if (is_string($multipart)) {
            $multipart = strtolower($multipart) == 'true';
        }

        $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() . (!empty($recaptcha_key) ? $ci->load->library('recaptcha/recaptcha')->token_input() : '');
    }

}