<?php

namespace PWH_DCFH\App\Frontend\Request;

if (!defined('ABSPATH')) exit;
if (!class_exists('PWH_DCFH_Post_Request')) {
    class PWH_DCFH_Post_Request
    {
        public $contact_form_num = 0;

        public $contact_form_raw_fields = [];

        public $contact_form_processed_fields = [];

        public $contact_form_fields;

        private $contact_email;

        public $is_email_found = null;

        public $files;

        public $referer_url;

        /**
         * Class Constructor
         *
         * @param bool $processed_contact_form
         *
         * @since 1.0.0
         */
        public function __construct($processed_contact_form = true)
        {
            global $et_pb_contact_form_num;
            $this->contact_form_num = $et_pb_contact_form_num;
            if ($processed_contact_form) {
                $this->processed_contact_form_entries();
            }
            pwh_dcfh_email_merge_tags_handler()::fixed_tags_values();
        }

        /**
         * Retrieves The Form Endcoded Data
         * @return array
         * @since 1.0.0
         */
        public function get_contact_form_raw_fields()
        {
            return $this->contact_form_raw_fields;
        }

        /**
         * Set The Form Dedcoded Data
         *
         * @param array $contact_form_processed_fields
         *
         * @since 1.0.0
         */
        public function set_contact_form_processed_fields(array $contact_form_processed_fields)
        {
            $this->contact_form_processed_fields = $contact_form_processed_fields;
        }

        /**
         * Retrieves The Form Dedcoded Data
         * @return array
         * @since 1.0.0
         */
        public function get_contact_form_processed_fields()
        {
            return $this->contact_form_processed_fields;
        }

        /**
         * Retrieves The Form Fields
         * @return mixed
         * @since 1.0.0
         */
        public function get_contact_form_fields()
        {
            return $this->contact_form_fields;
        }

        /**
         * Check is Contact Form Processed
         * @return bool
         * @since 1.0.0
         */
        public function is_contact_form_processed()
        {
            $is_nonce_verified = isset($_POST['_wpnonce-et-pb-contact-form-submitted-'.$this->contact_form_num]) && wp_verify_nonce(sanitize_text_field($_POST['_wpnonce-et-pb-contact-form-submitted-'.$this->contact_form_num]),
                    'et-pb-contact-form-submit');
            if ($is_nonce_verified) {
                if (isset($_POST['et_pb_contactform_submit_'.$this->contact_form_num]) && 'et_contact_proccess' === sanitize_text_field($_POST['et_pb_contactform_submit_'.$this->contact_form_num])) {
                    return true;
                }
                if (isset($_POST['pwh_dcfh_et_pb_contactform_submit_'.$this->contact_form_num]) && 'et_contact_proccess' === sanitize_text_field($_POST['pwh_dcfh_et_pb_contactform_submit_'.$this->contact_form_num])) {
                    return true;
                }
            }

            return false;
        }

        /**
         * Is Confirmation Enable
         * @return bool
         */
        public function is_confirmation_email_enabled()
        {
            global $et_pb_contact_form_num;

            return isset($_POST['et_pb_contact_confirmation_'.$et_pb_contact_form_num]) && sanitize_text_field($_POST['et_pb_contact_confirmation_'.$et_pb_contact_form_num]); // phpcs:ignore WordPress.Security.NonceVerification
        }

        /**
         * Is Honeypot Filled
         * @return bool
         */
        public function is_honeypot_filled()
        {
            global $et_pb_contact_form_num;
            if (isset($_POST['et_pb_contact_hp_field_'.$et_pb_contact_form_num]) && 'on' === sanitize_text_field($_POST['et_pb_contact_hp_field_'.$et_pb_contact_form_num])) { // phpcs:ignore WordPress.Security.NonceVerification
                return true;
            }

            return false;
        }

        /**
         * Get Referer URL
         * @return string
         * @since 1.1
         */
        public function get_referer_url()
        {
            global $et_pb_contact_form_num;

            return isset($_POST['et_pb_contact_field_referer_url_'.$et_pb_contact_form_num]) ? sanitize_text_field($_POST['et_pb_contact_field_referer_url_'.$et_pb_contact_form_num]) : ''; // phpcs:ignore WordPress.Security.NonceVerification
        }

        /**
         * Retrieves The Contact Email
         * @return mixed
         * @since 1.0.0
         */
        public function get_contact_email()
        {
            return $this->contact_email;
        }

        /**
         * Set Contact Email
         *
         * @param $email
         *
         * @since 1.0.0
         */
        public function set_contact_email($email)
        {
            if (!empty($email)) {
                $this->contact_email = $email;
            }
        }

        /**
         * Process Form Entries
         * @since 1.0.0
         */
        protected function processed_contact_form_entries()
        {
            $is_nonce_verified = isset($_POST['_wpnonce-et-pb-contact-form-submitted-'.$this->contact_form_num]) && wp_verify_nonce(sanitize_text_field($_POST['_wpnonce-et-pb-contact-form-submitted-'.$this->contact_form_num]),
                    'et-pb-contact-form-submit');
            if ($is_nonce_verified) {
                $contact_form_num = $this->contact_form_num;
                $current_form_fields = isset($_POST["et_pb_contact_email_fields_$contact_form_num"]) ? sanitize_text_field($_POST["et_pb_contact_email_fields_$contact_form_num"]) : null;
                $hidden_form_fields = isset($_POST["et_pb_contact_email_hidden_fields_$contact_form_num"]) ? sanitize_text_field($_POST["et_pb_contact_email_hidden_fields_$contact_form_num"]) : null;
                if (!empty($current_form_fields)) {
                    $fields_data_array = json_decode(str_replace('\\', '', $current_form_fields), true);
                    $fields_data_array = null === $fields_data_array ? [] : $fields_data_array;
                    if (!empty($fields_data_array) && is_array($fields_data_array)) {
                        $hidden_fields_data_array = [];
                        if (!empty($hidden_form_fields)) {
                            $hidden_fields_data_array = json_decode(str_replace('\\', '', $hidden_form_fields), true);
                            if (!empty($hidden_fields_data_array) && is_array($hidden_fields_data_array)) {
                                foreach ($hidden_fields_data_array as $hidden_field) {
                                    $fields_data_array[] = [
                                        'field_id' => 'et_pb_contact_'.$hidden_field.'_'.$contact_form_num,
                                        'original_id' => $hidden_field,
                                        'field_type' => 'input',
                                        'field_label' => $hidden_field
                                    ];
                                }
                            }
                        }
                        $all_fields = '';
                        $confirmation_request = PWH_DCFH_Confirmation_Email_Request::instance();
                        $confirmation_email_field_id = $confirmation_request->confirmation_email_field_id;
                        $contact_email = null;
                        $post_repository = PWH_DCFH_Post_Repository::instance();
                        list($y, $m) = pwh_dcfh_file_helpers()::get_subdir();
                        // Save Query Parameters To Database
                        if ($post_repository->save_queryparams_to_db) {
                            $query_params = $this->get_query_params();
                            $fields_data_array = wp_parse_args($query_params, $fields_data_array);
                            pwh_dcfh_db()::update_contact_form_query_params($post_repository->get_contact_form_id(), $query_params);
                        }
                        foreach ($fields_data_array as $index => $value) {
                            // $field_id = $value['original_id'];
                            $field_id = pwh_dcfh_helpers()::sanitize_key($value['original_id']);
                            $field_type = $value['field_type'];
                            $field_label = $value['field_label'];
                            $field_value = isset($_REQUEST[$value['field_id']]) ? wp_unslash(sanitize_text_field($_REQUEST[$value['field_id']])) : null;
                            if (in_array($field_id, $hidden_fields_data_array) && isset($_REQUEST["et_pb_contact_{$field_id}_$contact_form_num"])) {
                                $field_value = $_REQUEST["et_pb_contact_{$field_id}_$contact_form_num"]; // phpcs:ignore
                            }
                            if ('et_pb_html_field' !== $field_value) {
                                if ('text' === $field_type) {
                                    $field_value = sanitize_textarea_field($field_value);
                                } elseif ('email' === $field_type) {
                                    $field_value = sanitize_email($field_value);
                                } elseif (isset($_REQUEST[$value['field_id'].'_is_file'])) {
                                    $field_type = 'file';
                                    $this->files[$field_id] = $field_value;
                                } else {
                                    $field_value = sanitize_text_field($field_value);
                                }
                                // If input type is file and save to database true save files
                                if ('file' === $field_type && $post_repository->save_files_to_db) {
                                    $this->contact_form_processed_fields[] = [
                                        'id' => $field_id,
                                        'label' => $field_label,
                                        'value' => $field_value,
                                        'type' => $field_type,
                                        'subdir' => "$y/$m"];
                                } // If input type is not file and save to database false save
                                elseif ('file' !== $field_type) {

                                    $this->contact_form_processed_fields[] = [
                                        'id' => $field_id,
                                        'label' => $field_label,
                                        'value' => $field_value,
                                        'type' => $field_type
                                    ];
                                    if (empty($contact_email)) {
                                        if (empty($confirmation_email_field_id)) {
                                            if ('email' === $field_type) {
                                                $contact_email = sanitize_email($field_value);
                                            } elseif (is_email($field_value)) {
                                                $contact_email = sanitize_email($field_value);
                                            }
                                        } elseif (strtolower($confirmation_email_field_id) === $field_id && is_email($field_value)) {
                                            $contact_email = sanitize_email($field_value);
                                        }
                                    }
                                }
                                $all_fields .= $field_id.',';
                            }
                        }
                        $this->contact_email = $contact_email;
                        $this->contact_form_raw_fields = $fields_data_array;
                        $this->contact_form_fields = substr($all_fields, 0, -1);
                        $confirmation_request->get_post_request()->set_contact_email($contact_email);
                        $confirmation_request->get_post_request()->set_contact_form_processed_fields($this->contact_form_processed_fields);
                    }
                }
            }
        }

        /**
         * Get Attachments From Temp Directory
         * @return array
         * @since 1.0.0
         */
        public function get_attachments_from_tmp_dir()
        {
            $attachments = [];
            $tmp_files = $this->files;
            if (!empty($tmp_files)) {
                foreach ($tmp_files as $tmp_file) {
                    $files = explode(',', $tmp_file);
                    if (!empty($files) && is_array($files)) {
                        $upload_temp_dir = pwh_dcfh_file_helpers()::get_temp_upload_dir();
                        foreach ($files as $file) {
                            $file_temp_dir = path_join($upload_temp_dir, $file);
                            if (et_()->WPFS()->is_file($file_temp_dir) && et_()->WPFS()->exists($file_temp_dir)) {
                                $attachments[] = $file_temp_dir;
                            }
                        }
                    }
                }
            }

            return $attachments;
        }

        /**
         * Move Attachments To Directory
         * @return array
         * @since 1.0.0
         */
        public function move_attachments_dir()
        {
            $attachments = [];
            $tmp_files = $this->files;
            if (!empty($tmp_files)) {
                $upload_temp_dir = pwh_dcfh_file_helpers()::get_temp_upload_dir();
                $post_repository = PWH_DCFH_Post_Repository::instance();
                foreach ($tmp_files as $tmp_file) {
                    $files = explode(',', $tmp_file);
                    if (!empty($files) && is_array($files)) {
                        foreach ($files as $file) {
                            $upload_dir = pwh_dcfh_file_helpers()::upload_files_to_dir($post_repository->contact_form_id, $file);
                            $file_temp_dir = path_join($upload_temp_dir, $file);
                            if (et_()->WPFS()->is_file($file_temp_dir) && et_()->WPFS()->exists($file_temp_dir)) {
                                if (copy($file_temp_dir, $upload_dir['basedir'])) {
                                    $attachments[] = $upload_dir['basedir'];
                                }
                            }
                        }
                    }
                }
            }

            return $attachments;
        }

        /**
         * Get Query Parameters
         * @return array
         * @since 1.5
         */
        public function get_query_params()
        {
            $query_string = isset($_SERVER['QUERY_STRING']) ? sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING'])) : null;
            $data = [];
            if (!empty($query_string)) {
                $query_params = explode('&', $query_string);
                foreach ($query_params as $query_param) {
                    $item = explode('=', $query_param);
                    if (isset($item[0]) && $item[1]) {
                        $id = pwh_dcfh_helpers()::sanitize_key($item[0]);
                        $label = pwh_dcfh_helpers()::sanitize_string($id);
                        $value = urldecode($item[1]);
                        $data[] = [
                            'field_id' => $id,
                            'original_id' => $id,
                            'id' => $id,
                            'field_label' => $label,
                            'label' => $label,
                            'value' => $value,
                            'type' => 'query',
                            'field_type' => 'query',
                        ];
                    }
                }
            }

            return $data;
        }
    }
}