<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('integrazo_fwcrm_form_FormSubmit')) {
    class integrazo_fwcrm_form_FormSubmit
    {
        public function __construct()
        {
            // Hook for Contact Form 7 submissions
            add_action('wpcf7_mail_sent', [$this, 'process_cf7_submission']);

            // Hook for WPForms submissions
            add_action('wpforms_process_complete', [$this, 'process_wpforms_submission'], 10, 4);

            // Hook for Gravity Forms submissions
            add_action('gform_after_submission', [$this, 'process_gravityform_submission'], 10, 2);

            // Add Ninja Forms submission hook
            // add_action('ninja_forms_after_submission', [$this, 'process_ninjaforms_submission']);

            // Add the Formidable Forms submission hook
            add_action('frm_after_create_entry', [$this, 'process_formidable_submission'], 10, 2);

            // Add Everest Forms submission hook

            add_action('elementor_pro/forms/new_record', [$this, 'process_elementor_form_submission'], 10, 2);
        }
        private function create_error_response($error_code, $api_response = null)
        {
            return [
                'data' => [
                    [
                        'status' => 'error',
                        'code' => $error_code,
                        'api_response' => $api_response !== null ? $api_response : null,
                    ],
                ],
            ];
        }

        // Main processing function for form submissions
        public function process_form_submission($data, $crm_data, $field_mapping_details)
        {
            try {
                // Retrieve account details and access token
                $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
                $account_id = $field_mapping_details->account_id;
                $account_details = $integrazo_fwcrm_form_accountDBInstance->get_single_account_data($account_id);
                if ($account_details) {
                    $instance = new integrazo_fwcrm_form_API($account_details["instance_url"], $account_details["api_key"]);

                    // Perform the CRM action based on record_action setting
                    return $this->handle_crm_action($instance, $crm_data, $field_mapping_details);
                }

                return $this->create_error_response('ACCOUNT_NOT_FOUND');
            } catch (Throwable $e) {
                return $this->create_error_response('INVALID_DATA');
            }
        }

        // Function to process Contact Form 7 submissions
        public function process_cf7_submission($contact_form)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();

            try {
                // Retrieve form ID and group ID
                $form_id = $contact_form->id();
                $form_group_id = 1; // Adjust if needed

                // Get the submission instance
                $submission = WPCF7_Submission::get_instance();
                if ($submission) {
                    $session = integrazo_fwcrm_form_is_valid_key();
                    if (!$session) {
                        $integrazo_fwcrm_form_fieldMappingDBInstance->block_field_mapping();
                    }
                    // Fetch field mappings from the database
                    $field_mapping_list = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                    // Retrieve submitted form data
                    $form_data = $submission->get_posted_data();
                    $uploaded_files = $submission->uploaded_files();

                    // Include uploaded file paths in form data
                    if (!empty($uploaded_files)) {
                        foreach ($uploaded_files as $field_name => $file_path) {
                            if (isset($form_data[$field_name])) {
                                $form_data[$field_name] = $file_path;
                            }
                        }
                    }
                    // Process each field mapping
                    if (!empty($field_mapping_list)) {
                        foreach ($field_mapping_list as $field_mapping_details) {
                            if ((int)$field_mapping_details->integration_status === 1) {
                                // Map form data to CRM format
                                $crm_data = $this->map_form_data_to_crm($form_data, $field_mapping_details, "contact_form_7");
                                // Process form submission and check response
                                $response = $this->process_form_submission($form_data, $crm_data, $field_mapping_details);
                                // Log errors if needed
                                $this->check_and_add_error_log($response, $form_data, $crm_data, $field_mapping_details);
                            }
                        }
                    }
                }
            } catch (Throwable $e) {
                // Log the error for debugging
            }
        }

        // Function to process WPForms submissions
        public function process_wpforms_submission($fields, $entry, $form_data, $entry_id)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();

            try {
                // Retrieve form ID and mapping
                $form_id = $form_data['id'] ?? null;
                $form_group_id = 2; // Adjust as needed
                $session = integrazo_fwcrm_form_is_valid_key();
                if (!$session) {
                    $integrazo_fwcrm_form_fieldMappingDBInstance->block_field_mapping();
                }
                $field_mapping_list = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                // Prepare form data for CRM
                $form_data_to_map = [];
                foreach ($fields as $field) {
                    // Ensure 'id' and 'value' keys exist
                    if (isset($field['id']) && isset($field['value'])) {
                        $form_data_to_map[$field['id']] = $field['value'];
                    }
                }

                // Process each field mapping
                if (!empty($field_mapping_list)) {
                    foreach ($field_mapping_list as $field_mapping_details) {
                        if ((int) $field_mapping_details->integration_status === 1) {
                            // Map form data to CRM format
                            $crm_data = $this->map_form_data_to_crm(
                                $form_data_to_map,
                                $field_mapping_details,
                                "wpforms"
                            );

                            // Submit data to CRM and handle response
                            $response = $this->process_form_submission(
                                $form_data_to_map,
                                $crm_data,
                                $field_mapping_details
                            );

                            // Log errors if the submission fails
                            $this->check_and_add_error_log(
                                $response,
                                $form_data_to_map,
                                $crm_data,
                                $field_mapping_details
                            );
                        }
                    }
                }
            } catch (Throwable $e) {
                // Log the error for debugging purposes
            }
        }

        // Function to process Gravity Forms submissions
        public function process_gravityform_submission($entry, $form)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();

            try {
                // Retrieve form ID and mapping
                $form_id = $form['id'] ?? null;
                $form_group_id = 3; // Adjust as needed for Gravity Forms
                $session = integrazo_fwcrm_form_is_valid_key();
                if (!$session) {
                    $integrazo_fwcrm_form_fieldMappingDBInstance->block_field_mapping();
                }
                $field_mapping_list = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                // Check if mappings exist
                if (!empty($field_mapping_list)) {
                    // Prepare form data for CRM
                    $form_data = [];

                    foreach ($form['fields'] as $field) {
                        $field_id = $field->id;

                        if (!empty($field->inputs) && is_array($field->inputs)) {
                            foreach ($field->inputs as $input) {
                                $input_id = $input['id'];
                                $input_value = rgar($entry, $input_id); // Retrieve input value

                                if ($input_value !== null) {
                                    $form_data[$input_id] = $input_value;
                                }
                            }
                        } elseif ($field->type === 'fileupload') {
                            // Handle file upload fields
                            if (isset($entry[$field->id]) && !empty($entry[$field->id])) {
                                $file_path = $entry[$field->id];
                                $form_data[$field->id] = $file_path;
                            }
                        } else {
                            // Handle regular fields
                            $field_value = rgar($entry, $field_id); // Retrieve field value

                            if ($field_value !== null) {
                                $form_data[$field->id] = $field_value;
                            }
                        }
                    }

                    // Process each field mapping
                    foreach ($field_mapping_list as $field_mapping_details) {
                        if ((int) $field_mapping_details->integration_status === 1) {
                            // Map form data to CRM format
                            $crm_data = $this->map_form_data_to_crm(
                                $form_data,
                                $field_mapping_details,
                                "gravity_forms"
                            );

                            // Submit data to CRM and handle response
                            $response = $this->process_form_submission(
                                $form_data,
                                $crm_data,
                                $field_mapping_details
                            );

                            // Log errors if the submission fails
                            $this->check_and_add_error_log(
                                $response,
                                $form_data,
                                $crm_data,
                                $field_mapping_details
                            );
                        }
                    }
                }
            } catch (Throwable $e) {
                // Log the error for debugging
            }
        }

        /**
         * Process Ninja Forms submissions.
         *
         * @param array $form_data The form data from Ninja Forms.
         */
        public function process_ninjaforms_submission($form_data)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            try {
                // Debug the form data to understand its structure

                // Safely retrieve form ID
                $form_id = $form_data['form_id'] ?? null; // Use null coalescing operator to avoid warnings
                if (!$form_id) {
                    return; // Stop further processing
                }

                // Retrieve field mapping details
                $form_group_id = 4; // Group ID for Ninja Forms
                $field_mapping_details = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                if ($field_mapping_details && isset($field_mapping_details->field_mapping)) {
                    // Prepare form data for CRM
                    $prepared_form_data = [];
                    foreach ($form_data['fields'] as $field) {
                        if (isset($field['key'], $field['value'])) {
                            $prepared_form_data[$field['key']] = $field['value'];
                        }
                    }


                    // Map data and process submission
                    $crm_data = $this->map_form_data_to_crm($prepared_form_data, $field_mapping_details->field_mapping, "ninja_forms");

                    $response = $this->process_form_submission($prepared_form_data, $crm_data, $field_mapping_details);

                    // Log errors if the submission fails
                    $this->check_and_add_error_log($response, $prepared_form_data, $crm_data, $field_mapping_details->integration_id);
                }
            } catch (Throwable $e) {
                // Log the error
            }
        }
        /**
         * Process Formidable Forms submission.
         *
         * @param int $entry_id The ID of the submitted entry.
         * @param array $form The form object data.
         */
        public function process_formidable_submission($entry_id, $form_id)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            try {
                // Retrieve form object using the form ID
                $form = FrmForm::getOne($form_id);
                if (!$form) {
                    throw new Exception('Formidable form not found for ID: ' . $form_id);
                }

                // Retrieve form group ID and mapping
                $form_group_id = 5; // Adjust group ID for Formidable Forms
                $session = integrazo_fwcrm_form_is_valid_key();
                if (!$session) {
                    $integrazo_fwcrm_form_fieldMappingDBInstance->block_field_mapping();
                }
                $field_mapping_list = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                // Get entry data
                $entry_data = FrmEntry::getOne($entry_id, true);
                $form_data = [];

                if (!empty($entry_data->metas)) {
                    foreach ($entry_data->metas as $field_id => $field_value) {
                        // Get field object to fetch the field name and type
                        $field_object = FrmField::getOne($field_id);

                        if ($field_object && isset($field_object->name)) {
                            // Handle file fields
                            if ($field_object->type === 'file') {
                                if (is_array($field_value)) {
                                    foreach ($field_value as $file) {
                                        $file_path = wp_get_original_image_path($file);
                                        if ($file_path) {
                                            $form_data[$field_id][] = $file_path; // Append file path to an array
                                        }
                                    }
                                } elseif (is_string($field_value)) {
                                    $file_path = wp_get_original_image_path($field_value);
                                    if ($file_path) {
                                        $form_data[$field_id] = $file_path; // Assign single file path
                                    }
                                }
                            }
                            // Handle non-file fields
                            else {
                                if (is_array($field_value) && array_keys($field_value) !== range(0, count($field_value) - 1)) {
                                    foreach ($field_value as $key => $value) {
                                        $form_data[$field_id . "_" . $key] = $value; // Use key for array items
                                    }
                                } else {
                                    $form_data[$field_id] = $field_value; // Assign single value
                                }
                            }
                        }
                    }
                }

                // Process each field mapping
                if (!empty($field_mapping_list)) {
                    foreach ($field_mapping_list as $field_mapping_details) {
                        if ((int) $field_mapping_details->integration_status === 1) {
                            // Map form data to CRM format
                            $crm_data = $this->map_form_data_to_crm(
                                $form_data,
                                $field_mapping_details,
                                "formidable_forms"
                            );

                            // Submit data to CRM and handle response
                            $response = $this->process_form_submission(
                                $form_data,
                                $crm_data,
                                $field_mapping_details
                            );

                            // Log errors if the submission fails
                            $this->check_and_add_error_log(
                                $response,
                                $form_data,
                                $crm_data,
                                $field_mapping_details
                            );
                        }
                    }
                }
            } catch (Throwable $e) {
                // Log the error for debugging purposes
            }
        }

        /**
         * Process Everest Forms submissions.
         *
         * @param int $form_id The ID of the submitted form.
         */
        public function process_everestforms_submission($form_data, $form_data_with_id)
        {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            try {
                // Retrieve field mapping details
                $form_group_id = 6; // Group ID for Everest Forms
                $form_id = $form_data_with_id['id'];
                $session = integrazo_fwcrm_form_is_valid_key();
                if (!$session) {
                    $integrazo_fwcrm_form_fieldMappingDBInstance->block_field_mapping();
                }
                $field_mapping_details = $integrazo_fwcrm_form_fieldMappingDBInstance->get_mapping_by_id($form_id, $form_group_id);

                if ($field_mapping_details && isset($field_mapping_details->field_mapping)) {
                    // Retrieve submission data
                    $prepared_form_data = $form_data_with_id['form_fields'];

                    // Map data and process submission
                    $crm_data = $this->map_form_data_to_crm($prepared_form_data, $field_mapping_details, "everest_forms");

                    $response = $this->process_form_submission($prepared_form_data, $crm_data, $field_mapping_details);

                    // Log errors if the submission fails
                    $this->check_and_add_error_log($response, $prepared_form_data, $crm_data, $field_mapping_details);
                }
            } catch (Throwable $e) {
                // Log the error for debugging
            }
        }

        /**
         * Process Elementor form submissions.
         *
         * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $record The form submission record.
         * @param \ElementorPro\Modules\Forms\Classes\Form $handler The form handler.
         */
        public function process_elementor_form_submission($record, $handler)
        {
            $integrazo_fwcrm_form_Field_MappingDBInstance = new integrazo_fwcrm_form_FieldMapping();

            try {
                // --- Build combined form ID: {postId}_{widgetId}
                $form_widget_id = (string) $record->get_form_settings('id');
                $form_post_id   = (int) $record->get_form_settings('form_post_id');
                if ($form_post_id <= 0 || $form_widget_id === '') {
                    return;
                }
                $form_id       = $form_post_id . '_' . $form_widget_id;
                $form_group_id = 7; // Elementor Forms group
                // --- License/session check
                $session = integrazo_fwcrm_form_is_valid_key();
                if (! $session) {
                    // If session invalid, block and stop further processing
                    $integrazo_fwcrm_form_Field_MappingDBInstance->block_field_mapping();
                }

                // --- Get mapping rows for this form
                $field_mapping_list = $integrazo_fwcrm_form_Field_MappingDBInstance->get_mapping_by_id($form_id, $form_group_id);
                // Global Widget fallback
                if (empty($field_mapping_list)) {
                    $field_mapping_list = $integrazo_fwcrm_form_Field_MappingDBInstance->get_mapping_by_post_id_prefix($form_post_id, $form_group_id);
                }
                if (empty($field_mapping_list)) {
                    return; // nothing to do
                }

                // --- Read form fields and submitted values
                $form_data = [];

                // Definitions from form settings (builder-time)
                $form_fields = $record->get_form_settings('form_fields');
                $form_fields = is_array($form_fields) ? $form_fields : [];

                // Build map: custom_id => _id (to normalize submitted keys)
                $custom_id_map = [];
                foreach ($form_fields as $field_def) {
                    if (is_array($field_def) && isset($field_def['custom_id'], $field_def['_id'])) {
                        $custom_id_map[(string) $field_def['custom_id']] = (string) $field_def['_id'];
                    }
                }

                // Submitted runtime values
                $raw_fields = $record->get('fields'); // ElementorPro\Forms\Record stores submitted fields here
                $raw_fields = is_array($raw_fields) ? $raw_fields : [];
                foreach ($raw_fields as $id => $field) {
                    if (! is_array($field)) {
                        continue;
                    }

                    $value = $field['value'] ?? '';
                    $type  = $field['type']  ?? '';

                    // Normalize key to builder _id if we have custom_id
                    $field_key = isset($custom_id_map[$id]) ? $custom_id_map[$id] : (string) $id;

                    if ($type === 'upload') {
                        // Elementor may give array or CSV; normalize to array of paths
                        if (is_array($value)) {
                            $paths = array_map('strval', $value);
                        } else {
                            $paths = array_map('trim', explode(',', (string) $value));
                            $paths = array_filter($paths, static function ($p) {
                                return $p !== '';
                            });
                        }
                        $form_data[$field_key] = array_values($paths);
                    } else {
                        // Scalar value as string
                        if (is_array($value)) {
                            // For checkbox/multi-select, implode safely
                            $form_data[$field_key] = implode(', ', array_map('strval', $value));
                        } else {
                            $form_data[$field_key] = (string) $value;
                        }
                    }
                }

                // --- Process each active mapping
                foreach ($field_mapping_list as $field_mapping_details) {
                    if ((int) $field_mapping_details->integration_status !== 1) {
                        continue;
                    }

                    // Build CRM payload and send
                    $crm_data = $this->map_form_data_to_crm($form_data, $field_mapping_details, 'elementor_forms');

                    $response = $this->process_form_submission($form_data, $crm_data, $field_mapping_details);
                    // Log errors if any
                    $this->check_and_add_error_log($response, $form_data, $crm_data, $field_mapping_details);
                }
            } catch (Throwable $e) {
                // Optional debug:
                return;
            }
        }


        // Include other existing methods here (e.g., process_form_submission, check_and_add_error_log, etc.)

        // Error logging function
        private function check_and_add_error_log($response, $form_data, $crm_data, $field_mapping_details)
        {
            $integrazo_fwcrm_form_errorLogDBInstance = new integrazo_fwcrm_form_ErrorLog();
            $integrazo_fwcrm_form_api_Instance = new integrazo_fwcrm_form_API();

            // Retrieve the module action
            $module_name = $field_mapping_details->module_name ?? '';
            $module_action = $integrazo_fwcrm_form_api_Instance->getModuleAction($module_name);

            // Check if the response contains the expected module action and ID
            if (!isset($response[$module_action]) || !isset($response[$module_action]['id'])) {
                $code = $response['code'] ?? 'API_RESPONSE_ISSUE';
                $crm_record_id = $response[$module_action]['id'] ?? '';

                // Add error log to the database
                $integrazo_fwcrm_form_errorLogDBInstance->add_error_log(
                    $field_mapping_details->integration_id,
                    $code,
                    $form_data,
                    $crm_data,
                    $response,
                    0, // Retry count is set to 0
                    $crm_record_id
                );
            }
        }


        // Map form data to CRM structure based on field mappings
        private function map_form_data_to_crm($data, $field_mapping, $form_type)
        {
            $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();

            $field_mapping_raw = $field_mapping->field_mapping;
            $field_mapping_json = json_decode($field_mapping_raw, true);
            $crm_data = [];
            try {
                $account_details = $integrazo_fwcrm_form_accountDBInstance->get_single_account_data($field_mapping->account_id);
                $instance = new integrazo_fwcrm_form_API($account_details["instance_url"], $account_details["api_key"]);

                // Check if any data_type is dropdown or multi_select_dropdown
                $requires_module_fields = false;
                foreach ($field_mapping_json as $mapping_info) {
                    if (isset($mapping_info['data_type']) && in_array($mapping_info['data_type'], ['dropdown', 'multi_select_dropdown'], true)) {
                        $requires_module_fields = true;
                        break;
                    }
                }

                // Call get_module_fields only if required
                if ($requires_module_fields) {
                    $field_response = $instance->get_module_fields($field_mapping->module_name);
                }
                foreach ($field_mapping_json as $crm_key => $mapping_info) {
                    if ($crm_key === "attachment") {
                        try {
                            $final_attachment_path_list = [];
                            if (is_array($mapping_info)) {
                                foreach ($mapping_info as $attach_field_name) {
                                    $file_path = $data[$attach_field_name] ?? null;

                                    if ($file_path !== null) {
                                        if (is_array($file_path)) {
                                            $final_attachment_path_list = array_merge($final_attachment_path_list, $file_path);
                                        } elseif (is_string($file_path)) {
                                            $final_attachment_path_list[] = $file_path;
                                        }
                                    }
                                }

                                if (!empty($final_attachment_path_list)) {
                                    $crm_data[$crm_key] = $final_attachment_path_list;
                                }
                            }
                        } catch (Throwable $e) {
                            // Log attachment processing error if necessary
                        }
                        continue;
                    }

                    $field_type = $mapping_info['field_type'] ?? null;
                    $field_value = $mapping_info['field_value'] ?? null;
                    $data_type = $mapping_info['data_type'] ?? null;

                    $value = null;

                    if ($field_type === 'form field') {
                        if (str_contains($field_value, "integrazo_fwcrm_form_")) {
                            $value = $this->systemFieldsValue($field_value);
                        } else {
                            $value = $data[$field_value] ?? null;
                        }
                    } elseif ($field_type === 'custom field') {
                        $value = $field_value;
                    }

                    if ($value !== null) {
                        switch ($data_type) {
                            case 'dropdown':
                                try {
                                    if (strpos($crm_key, "cf_") === false) {
                                        foreach ($field_response["fields"] as $field) {
                                            if (!empty($field['choices'])) {
                                                foreach ($field['choices'] as $choice) {
                                                    if ($choice["value"] === $value) {
                                                        $crm_data[$crm_key] = $choice["id"];
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        $crm_data[$crm_key] = $value;
                                    }
                                } catch (Throwable $e) {
                                    // Log dropdown processing error if necessary
                                }
                                break;

                            case 'multi_select_dropdown':
                                try {
                                    if (strpos($crm_key, "cf_") === false) {
                                        $final_multi_select_Value = [];
                                        foreach ($field_response["fields"] as $field) {
                                            if (!empty($field['choices'])) {
                                                foreach ($field['choices'] as $choice) {
                                                    if (is_string($value)) {
                                                        $splitValues = explode(",", $value);
                                                        foreach ($splitValues as $splitValue) {
                                                            if (trim($choice["value"]) === trim($splitValue)) {
                                                                $final_multi_select_Value[] = $choice["id"];
                                                            }
                                                        }
                                                    } elseif (is_array($value)) {
                                                        foreach ($value as $splitValue) {
                                                            if ($choice["value"] === $splitValue) {
                                                                $final_multi_select_Value[] = $choice["id"];
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        $crm_data[$crm_key] = implode(';', $final_multi_select_Value);
                                    } else {
                                        $crm_data[$crm_key] = is_array($value) ? implode(';', $value) : $value;
                                    }
                                } catch (Throwable $e) {
                                    // Log multi-select processing error if necessary
                                }
                                break;

                            case 'checkbox':
                                try {
                                    $crm_data[$crm_key] = (bool) in_array(strtolower((string)$value), ['yes', 'on', 'true', '1'], true);
                                } catch (Throwable $e) {
                                    // Log checkbox processing error if necessary
                                }
                                break;

                            default:
                                try {
                                    $crm_data[$crm_key] = is_array($value) ? implode(', ', $value) : (string)$value;
                                } catch (Throwable $e) {
                                    // Log default processing error if necessary
                                }
                                break;
                        }
                    }
                }

                $custom_fields = [];
                foreach ($crm_data as $key => $value) {
                    if (strpos($key, 'cf_') === 0) {
                        $custom_fields[$key] = $value;
                        unset($crm_data[$key]);
                    } elseif ($key === 'sales_accounts') {
                        unset($crm_data[$key]);
                        $account_id = $instance->get_account_id($value);

                        if (is_numeric($account_id) && $account_id > 0) {
                            $crm_data["sales_accounts"] = [["id" => $account_id, "is_primary" => true]];
                        } else {
                            $crm_data["sales_account"] = ["name" => sanitize_text_field($value)];
                        }
                    }
                }

                if (!empty($custom_fields)) {
                    $crm_data['custom_field'] = $custom_fields;
                }
                return $crm_data;
            } catch (Throwable $e) {
                // Log main processing error if necessary
                return $crm_data;
            }
        }




        private function handle_crm_action($fw_crm_instance, $crm_data, $field_mapping_details)
        {
            try {
                $module_name = $field_mapping_details->module_name;
                $record_action = $field_mapping_details->record_action;
                $response = null;
                // Handle attachments
                $attachment_path_list = $crm_data["attachment"] ?? null;
                if (!empty($attachment_path_list)) {
                    unset($crm_data["attachment"]);
                }
                // Process record actions
                if ($record_action === "add_ignore_existing") {
                    $response = $fw_crm_instance->add_module_record($module_name, $crm_data);
                } else {
                    $response = $fw_crm_instance->upsert_module_record($module_name, $crm_data);
                }
                // Check if $response is null
                if ($response === null) {
                    return $this->create_error_response('API_RESPONSE_EMPTY');
                }

                // Retrieve module action for the provided module name
                $module_action = $fw_crm_instance->getModuleAction($module_name);
                // Log the module action for debugging
                if (!is_array($response)) {
                    return $this->create_error_response('API_RESPONSE_ISSUE', $response);
                }
                // Check if the response is an array and contains the expected structure
                if (!isset($response[$module_action]['id'])) {
                    return $this->create_error_response('API_RESPONSE_ISSUE', $response);
                }

                $crm_record_id = $response[$module_action]['id'] ?? null;
                if (!$crm_record_id) {
                    return $this->create_error_response('API_RESPONSE_ISSUE', $response);
                }
                // Handle attachments
                if (!empty($attachment_path_list)) {
                    foreach ($attachment_path_list as $file_path) {
                        $temp =  $fw_crm_instance->attach_file_to_fw($file_path, $crm_record_id, $module_name);
                    }
                }

                return $response;
            } catch (Throwable $e) {
                return $this->create_error_response('INVALID_DATA');
            }
        }
        private function systemFieldsValue($field_value)
        {
            try {
                // Retrieve the referrer URL
                $page_url = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : null;

                // Parse the query parameters from the referrer URL, if available
                $query_params = [];
                if ($page_url) {
                    $url_components = wp_parse_url($page_url);
                    parse_str($url_components['query'] ?? '', $query_params);
                }

                switch ($field_value) {
                    case 'integrazo_fwcrm_form_entry_added_time':
                        return gmdate('Y-m-d H:i:s'); // Current date and time
                    case 'integrazo_fwcrm_form_utm_source':
                        return sanitize_text_field($query_params['utm_source'] ?? null); // Retrieve and sanitize UTM source
                    case 'integrazo_fwcrm_form_utm_medium':
                        return sanitize_text_field($query_params['utm_medium'] ?? null); // Retrieve and sanitize UTM medium
                    case 'integrazo_fwcrm_form_utm_campaign':
                        return sanitize_text_field($query_params['utm_campaign'] ?? null); // Retrieve and sanitize UTM campaign
                    case 'integrazo_fwcrm_form_utm_term':
                        return sanitize_text_field($query_params['utm_term'] ?? null); // Retrieve and sanitize UTM term
                    case 'integrazo_fwcrm_form_utm_content':
                        return sanitize_text_field($query_params['utm_content'] ?? null); // Retrieve and sanitize UTM content
                    case 'integrazo_fwcrm_form_page_url':
                        return esc_url($page_url); // Return the sanitized referrer URL
                    case 'integrazo_fwcrm_form_city':
                        return $this->get_user_location()['city']; // Get city from user location
                    case 'integrazo_fwcrm_form_state':
                        return $this->get_user_location()['state']; // Get state from user location
                    case 'integrazo_fwcrm_form_country':
                        return $this->get_user_location()['country']; // Get country from user location
                    default:
                        return null; // Return null for unrecognized keys
                }
            } catch (Throwable $e) {
                // Log the error for debugging
                return null; // Return null on error
            }
        }

        private function get_user_location()
        {
            try {
                // Retrieve the user's IP address from various headers
                if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                    $ip = filter_var(wp_unslash($_SERVER['HTTP_CLIENT_IP']), FILTER_VALIDATE_IP);
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    // Sanitize the input before further processing
                    $forwarded_for = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
                    // Split the sanitized string into an array
                    $ip_list = array_map('sanitize_text_field', explode(',', $forwarded_for));
                    // Validate and use the first valid IP
                    $ip = isset($ip_list[0]) ? filter_var(trim($ip_list[0]), FILTER_VALIDATE_IP) : false;
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
                    $ip = filter_var(wp_unslash($_SERVER['HTTP_X_FORWARDED']), FILTER_VALIDATE_IP);
                } elseif (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
                    $ip = filter_var(wp_unslash($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']), FILTER_VALIDATE_IP);
                } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
                    $ip = filter_var(wp_unslash($_SERVER['HTTP_FORWARDED_FOR']), FILTER_VALIDATE_IP);
                } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
                    $ip = filter_var(wp_unslash($_SERVER['HTTP_FORWARDED']), FILTER_VALIDATE_IP);
                } else {
                    $ip = filter_var(wp_unslash($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'), FILTER_VALIDATE_IP); // Fallback to REMOTE_ADDR
                }

                // Sanitize the IP address
                $ip = sanitize_text_field($ip);

                // Handle localhost or dummy IPs
                if ($ip === '127.0.0.1' || $ip === '::1' || $ip === '0.0.0.0') {
                    $ip = '8.8.8.8'; // Use a public IP for testing
                }

                // Validate the IP address
                if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                    return [
                        'city' => null,
                        'state' => null,
                        'country' => null,
                    ];
                }

                // Attempt to get location data via WordPress hooks
                $geo_data = apply_filters('get_user_location_data', [], $ip);

                // If no data is returned, fallback to an external API
                if (empty($geo_data) || !is_array($geo_data)) {
                    $url = "http://ip-api.com/json/$ip";
                    $response = wp_remote_get($url);

                    if (!is_wp_error($response)) {
                        $data = json_decode(wp_remote_retrieve_body($response), true);
                        if ($data && $data['status'] === 'success') {
                            $geo_data = [
                                'city' => $data['city'] ?? null,
                                'state' => $data['regionName'] ?? null,
                                'country' => $data['country'] ?? null,
                            ];
                        }
                    }
                }

                // Return the geolocation data
                return [
                    'city' => sanitize_text_field($geo_data['city'] ?? null),
                    'state' => sanitize_text_field($geo_data['state'] ?? null),
                    'country' => sanitize_text_field($geo_data['country'] ?? null),
                ];
            } catch (Throwable $e) {
                // Return empty values on any failure
                return [
                    'city' => null,
                    'state' => null,
                    'country' => null,
                ];
            }
        }
    }
    $integrazo_fwcrm_form_formSubmit = new integrazo_fwcrm_form_FormSubmit();
}
