<?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('iafwzc_FormSubmit')) {
    class iafwzc_FormSubmit
    {
        // Add this
        private $module_priority = [
            'Accounts'            => 1,
            'Leads'               => 2,
            'Vendors'             => 3,
            'Campaigns'           => 4,
            'Price_Books'         => 5,
            'Products'            => 6,
            'Contacts'            => 7,
            'Pipelines'           => 8,
            'Deals'               => 9,
            'Cases'               => 10,
            'Solutions'           => 11,
            'Quotes'              => 12,
            'Sales_Orders'        => 13,
            'Purchase_Orders'     => 14,
            'Invoices'            => 15,
            'Associated_Products' => 16,
            'Activities'          => 17,
            'Tasks'               => 18,
            'Events'              => 19,
            'Calls'               => 20,
            'Projects'            => 21,
            'Notes'               => 22,
            'Attachments'         => 23,
        ];
        private function sort_by_module_priority($field_mapping_list)
        {
            usort($field_mapping_list, function ($a, $b) {
                $priority_a = $this->module_priority[$a->module_name] ?? 99;
                $priority_b = $this->module_priority[$b->module_name] ?? 99;
                return $priority_a - $priority_b;
            });
            return $field_mapping_list;
        }
        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 the Formidable Forms submission hook
            add_action('frm_after_create_entry', [$this, 'process_formidable_submission'], 10, 2);

            // Hook for Elementor Pro form submissions
            add_action('elementor_pro/forms/new_record', [$this, 'process_elementor_form_submission'], 10, 2);
        }

        // Main processing function for form submissions
        public function process_form_submission($data, $crm_data, $field_mapping_details)
        {
            try {
                // Retrieve account details and access token
                $iafwzc_accountDBInstance = new IAFWZC_Account_Table();
                $iafwzc_zohoCRMInstance = new IAFWZC_Zoho_CRM();
                $iafwzc_zohoBiginInstance = new IAFWZC_Zoho_Bigin();
                $account_id = $field_mapping_details->account_id;
                $account_details = $iafwzc_accountDBInstance->get_single_account_data($account_id);
                $accessToken = IAFWZC_Zoho_Util::getAccessToken($account_id);

                if ($account_details) {
                    $service_name = $account_details["service_name"];
                    if ($service_name === "zoho_bigin") {
                        $iafwzc_zohoBiginInstance = new IAFWZC_Zoho_Bigin($account_details, $accessToken);
                        $instance = $iafwzc_zohoBiginInstance; // Set instance to Bigin
                    } else {
                        $iafwzc_zohoCRMInstance = new IAFWZC_Zoho_CRM($account_details, $accessToken);
                        $instance = $iafwzc_zohoCRMInstance; // Set instance to CRM
                    }

                    // 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('UNEXPECTED_ERROR');
            }
        }
        private function create_error_response($error_code)
        {
            return [
                'data' => [
                    [
                        'status' => 'error',
                        'code' => $error_code,
                    ],
                ],
            ];
        }
        // Function to process Contact Form 7 submissions
        public function process_cf7_submission($contact_form)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

            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 = iafwzc_is_valid_key();
                    if (!$session) {
                        $IAFWZC_Field_MappingDBInstance->block_field_mapping();
                    }
                    // Fetch field mappings from the database
                    $field_mapping_list = $IAFWZC_Field_MappingDBInstance->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)) {

                        $field_mapping_list = $this->sort_by_module_priority($field_mapping_list); // ← add

                        foreach ($field_mapping_list as $field_mapping_details) {
                            if ((int)$field_mapping_details->integration_status === 1) {

                                $filter_criteria = $this->filter_criteria($form_data, $field_mapping_details->filter_criteria);
                                if ($filter_criteria === 1) {
                                    // Map form data to CRM format
                                    $crm_data = $this->map_form_data_to_crm($form_data, $field_mapping_details);
                                    // 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)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            try {
                // Retrieve form ID and mapping
                $form_id = $form_data['id'] ?? null;
                $form_group_id = 2; // Adjust as needed
                $session = iafwzc_is_valid_key();
                if (!$session) {
                    $IAFWZC_Field_MappingDBInstance->block_field_mapping();
                }
                $field_mapping_list = $IAFWZC_Field_MappingDBInstance->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)) {

                    $field_mapping_list = $this->sort_by_module_priority($field_mapping_list);

                    foreach ($field_mapping_list as $field_mapping_details) {
                        if ((int) $field_mapping_details->integration_status === 1) {
                            $filter_criteria = $this->filter_criteria($form_data_to_map, $field_mapping_details->filter_criteria);
                            if ($filter_criteria === 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)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

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

                // Check if mappings exist
                if (!empty($field_mapping_list)) {

                    $field_mapping_list = $this->sort_by_module_priority($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) {
                            $filter_criteria = $this->filter_criteria($form_data, $field_mapping_details->filter_criteria);
                            if ($filter_criteria === 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 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)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
            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 = iafwzc_is_valid_key();
                if (!$session) {
                    $IAFWZC_Field_MappingDBInstance->block_field_mapping();
                }
                $field_mapping_list = $IAFWZC_Field_MappingDBInstance->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)) {

                    $field_mapping_list = $this->sort_by_module_priority($field_mapping_list);
                    foreach ($field_mapping_list as $field_mapping_details) {
                        if ((int) $field_mapping_details->integration_status === 1) {
                            $filter_criteria = $this->filter_criteria($form_data, $field_mapping_details->filter_criteria);
                            if ($filter_criteria === 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 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)
        {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

            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 = iafwzc_is_valid_key();
                if (! $session) {
                    // If session invalid, block and stop further processing
                    $IAFWZC_Field_MappingDBInstance->block_field_mapping();
                }

                // --- Get mapping rows for this form
                $field_mapping_list = $IAFWZC_Field_MappingDBInstance->get_mapping_by_id($form_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;
                        }
                    }
                }
                $field_mapping_list = $this->sort_by_module_priority($field_mapping_list);
                // --- Process each active mapping
                foreach ($field_mapping_list as $field_mapping_details) {
                    if ((int) $field_mapping_details->integration_status !== 1) {
                        continue;
                    }

                    $filter_ok = $this->filter_criteria($form_data, $field_mapping_details->filter_criteria);
                    if ((int) $filter_ok !== 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:
                // error_log( 'process_elementor_form_submission error: ' . $e->getMessage() );
                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)
        {
            $IAFWZC_Error_LogDBInstance = new IAFWZC_Error_Log();

            if (isset($response['data'][0]['status']) && $response['data'][0]['status'] === 'error') {
                $error_details = $response['data'][0];
                $code = $error_details['code'] ?? '';
                $crm_record_id = $error_details['details']['id'] ?? null;

                $IAFWZC_Error_LogDBInstance->add_error_log(
                    $field_mapping_details->integration_id,
                    $code,
                    $form_data,
                    $crm_data,
                    $response,
                    $retry_count = 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 = null)
        {
            $crm_data = [];
            try {
                $field_mapping_raw = $field_mapping->field_mapping;
                $field_mapping_json = json_decode($field_mapping_raw, true);
                //
                foreach ($field_mapping_json as $crm_key => $mapping_info) {
                    if ($crm_key === "attachment") {
                        try {
                            $final_attachment_path_list = [];
                            if (is_array($mapping_info)) {
                                // Loop through $mapping_info to process each attachment field name
                                foreach ($mapping_info as $attach_field_name) {
                                    // Get the value from $data, default to null if not set
                                    $file_path = $data[$attach_field_name] ?? null;

                                    if ($file_path !== null) {
                                        if (is_array($file_path)) {
                                            // If it's an array, merge all values into the final list
                                            foreach ($file_path as $file) {
                                                $final_attachment_path_list[] = $file;
                                            }
                                        } elseif (is_string($file_path)) {
                                            // If it's a string, directly add to the final list
                                            $final_attachment_path_list[] = $file_path;
                                        }
                                    }
                                }

                                // Assign valid attachment paths to CRM data if any exist
                                if (!empty($final_attachment_path_list)) {
                                    $crm_data[$crm_key] = $final_attachment_path_list;
                                }
                            }
                        } catch (Throwable $e) {
                            // Log
                        }
                        continue;
                    } elseif ($crm_key === "Record_Image") {
                        $field_type = $mapping_info['field_type'];
                        $field_value = $mapping_info['field_value'];
                        try {
                            $file_path = $data[$field_value] ?? null;

                            // Check if the file path is not null
                            if ($file_path !== null) {
                                if (is_array($file_path)) {
                                    // If it's an array, get the 0th index
                                    $crm_data[$crm_key] = $file_path[0] ?? null;
                                } else {
                                    // If it's a string, assign it directly
                                    $crm_data[$crm_key] = $file_path;
                                }
                            }
                        } catch (Throwable $e) {
                            // Log
                        }
                        continue;
                    }
                    $crm_key = str_replace("iafwzc_cf_", "", $crm_key);
                    $field_type = $mapping_info['field_type'];
                    $field_value = $mapping_info['field_value'];
                    $data_type = $mapping_info['data_type'];

                    $value = null;
                    if ($data_type === "fileupload") {
                        try {
                            $file_path = $data[$field_value] ?? null;

                            // Check if the file path is not null
                            if ($file_path !== null) {
                                unset($crm_data[$crm_key]); // Remove the original key

                                // Handle array or string file paths
                                if (is_array($file_path)) {
                                    // If it's an array, assign the first file path with the modified key
                                    $crm_data[$crm_key . "//fileupload"] = $file_path[0] ?? null;
                                } else {
                                    // If it's a string, assign it directly with the modified key
                                    $crm_data[$crm_key . "//fileupload"] = $file_path;
                                }
                            }
                        } catch (Throwable $e) {
                            // Log
                        }
                        continue;
                    }
                    // Handle form field mappings
                    if ($field_type === 'form field') {
                        if (str_contains($field_value, "iafwzc_")) {
                            $value = $this->systemFieldsValue($field_value);
                        } else {
                            $value = $data[$field_value];
                        }
                    } elseif ($field_type === 'custom field') {
                        $value = $field_value; // Assign custom field value
                        // Match all placeholders like ${field_name}.
                        preg_match_all('/\${(.*?)}/', $value, $matches);

                        if (! empty($matches[1])) {
                            // Loop through each placeholder found in the template.
                            foreach ($matches[1] as $field_name) {
                                // Check if the form field value exists.
                                if (isset($data[$field_name])) {
                                    // Replace the placeholder with the actual value.
                                    $value = str_replace('${' . $field_name . '}', $data[$field_name], $value);
                                }
                            }
                        }
                    }
                    // Process value based on data type
                    if ($value) {
                        switch ($data_type) {
                            case 'boolean':
                                try {
                                    // Normalize boolean values
                                    $crm_data[$crm_key] = (bool) in_array(strtolower($value), ['yes', 'on', 'true', '1', 1], true);
                                } catch (Throwable $e) {
                                    // Log
                                }
                                break;
                            case 'multiselectpicklist':
                                try {
                                    if (is_string($value)) {
                                        // Check if the string is JSON-encoded
                                        $decoded_value = json_decode($value, true);
                                        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_value)) {
                                            // JSON array: ["One","Two"]
                                            $crm_data[$crm_key] = array_map('trim', $decoded_value);
                                        } else {
                                            // Not JSON, handle as delimited string or single string
                                            $delimiter = null;
                                            if (strpos($value, ',') !== false) {
                                                $delimiter = ','; // Comma-separated
                                            } elseif (strpos($value, ':') !== false) {
                                                $delimiter = ':'; // Colon-separated
                                            }

                                            if ($delimiter) {
                                                $crm_data[$crm_key] = array_map('trim', explode($delimiter, $value));
                                            } else {
                                                // Single string, convert to an array
                                                $crm_data[$crm_key] = [trim($value)];
                                            }
                                        }
                                    } elseif (is_array($value)) {
                                        // Already an array: ["One", "Two"]
                                        $crm_data[$crm_key] = array_map('trim', $value);
                                    }
                                } catch (Throwable $e) {
                                    // Log
                                }
                                break;

                            default:
                                try {
                                    // Default case: check if it's an array or another type
                                    if (is_array($value)) {
                                        // If it's an array, assign it as is
                                        $crm_data[$crm_key] = implode(', ', $value);
                                    } else {
                                        // If not an array, convert to string
                                        $crm_data[$crm_key] = (string) $value;
                                    }
                                } catch (Throwable $e) {
                                    // Log
                                }
                                break;
                        }
                    }
                }

                // Log the final payload for debugging
                return $crm_data;
            } catch (Throwable $e) {
                return $crm_data;
            }
        }

        private function handle_crm_action($zoho_crm_instance, $crm_data, $field_mapping_details)
        {
            try {
                $module_name = $field_mapping_details->module_name;
                if (strpos($module_name, 'iafwzc_cm_') === 0) {
                    $module_name = substr($module_name, strlen('iafwzc_cm_'));
                }
                $record_action = $field_mapping_details->record_action;
                $response = null;
                // Handle profile image
                $tag = $crm_data["tag"] ?? null;

                if ($tag !== null) {
                    unset($crm_data["tag"]);
                }
                // Handle profile image
                $profile_file_path = $crm_data["Record_Image"] ?? null;
                if ($profile_file_path !== null) {
                    unset($crm_data["Record_Image"]);
                }

                // Handle attachments
                $attachment_path_list = $crm_data["attachment"] ?? null;
                if (!empty($attachment_path_list)) {
                    unset($crm_data["attachment"]);
                }

                // Handle custom file uploads
                $file_upload_list = [];
                foreach ($crm_data as $key => $value) {
                    if (str_ends_with($key, '//fileupload')) {
                        $file_upload_list[$key] = $value;
                        unset($crm_data[$key]);
                    }
                }

                // Process record actions
                if ($record_action === "add_ignore_existing") {
                    $response = $zoho_crm_instance->add_module_record($module_name, $crm_data);
                } else {
                    $primary_key_value = $crm_data[$field_mapping_details->primary_key] ?? null;
                    $existing_records = $zoho_crm_instance->search_records_by_field($module_name, $field_mapping_details->primary_key, $primary_key_value);

                    if (
                        is_array($existing_records) && isset($existing_records['data'][0])
                        && (isset($existing_records['data'][0]['id']))
                    ) {
                        $record_id = $existing_records['data'][0]['id'] ?? null;
                        switch ($record_action) {
                            case "add_or_update":
                            case "update_only":
                                $response = $zoho_crm_instance->update_module_record($module_name, $record_id, $crm_data);
                                break;
                            case "add_tag_if_duplicate":
                                $response = $zoho_crm_instance->add_module_record($module_name, $crm_data);
                                if (isset($response['data'][0]['status']) && $response['data'][0]['status'] === 'success') {
                                    $crm_record_id = $response['data'][0]['details']['id'] ?? null;
                                    if ($crm_record_id) {
                                        $zoho_crm_instance->add_record_tag($module_name, $crm_record_id, "duplicate");
                                    }
                                }
                                break;
                        }
                    } else {
                        // Handle cases where no existing record is found
                        if (in_array($record_action, ["skip_if_exists", "add_or_update", "add_tag_if_duplicate"])) {
                            $response = $zoho_crm_instance->add_module_record($module_name, $crm_data);
                        }
                    }
                }

                // if ($response === null) {
                //     return $zoho_crm_instance->create_error_response('UNEXPECTED_ERROR');
                // }

                // Check for a successful response
                if (!isset($response['data'][0]['status']) || $response['data'][0]['status'] !== 'success') {
                    return $response;
                }

                $crm_record_id = $response['data'][0]['details']['id'] ?? null;
                if (!$crm_record_id) {
                    return $response;
                }
                if (!empty($tag)) {
                    $zoho_crm_instance->add_record_tag($module_name, $crm_record_id, $tag);
                }
                // Add a note if required
                if ((int)$field_mapping_details->need_note === 1) {
                    $zoho_crm_instance->add_note_to_record($module_name, $crm_record_id, $field_mapping_details->note);
                }
                // Handle attachments
                if (!empty($attachment_path_list)) {
                    foreach ($attachment_path_list as $file_path) {
                        $temp = $zoho_crm_instance->upload_attachment($module_name, $crm_record_id, $file_path);
                    }
                }

                // Handle profile image
                if (!empty($profile_file_path)) {
                    $temp = $zoho_crm_instance->upload_record_image($module_name, $crm_record_id, $profile_file_path);
                }

                // Handle custom file uploads
                if (!empty($file_upload_list)) {
                    foreach ($file_upload_list as $field_name => $file_name) {
                        $file_upload_field_api_name = explode('//', $field_name)[0];
                        if (!empty($file_name)) {
                            $temp = $zoho_crm_instance->upload_and_map_file($module_name, $crm_record_id, $file_upload_field_api_name, $file_name);
                        }
                    }
                }

                return $response;
            } catch (Throwable $e) {
                return $zoho_crm_instance->create_error_response('UNEXPECTED_ERROR');
            }
        }
        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 'iafwzc_entry_added_time':
                        return gmdate('Y-m-d H:i:s'); // Current date and time
                    case 'iafwzc_utm_source':
                        return sanitize_text_field($query_params['utm_source'] ?? null); // Retrieve and sanitize UTM source
                    case 'iafwzc_utm_medium':
                        return sanitize_text_field($query_params['utm_medium'] ?? null); // Retrieve and sanitize UTM medium
                    case 'iafwzc_utm_campaign':
                        return sanitize_text_field($query_params['utm_campaign'] ?? null); // Retrieve and sanitize UTM campaign
                    case 'iafwzc_utm_term':
                        return sanitize_text_field($query_params['utm_term'] ?? null); // Retrieve and sanitize UTM term
                    case 'iafwzc_utm_content':
                        return sanitize_text_field($query_params['utm_content'] ?? null); // Retrieve and sanitize UTM content
                    case 'iafwzc_page_url':
                        return esc_url($page_url); // Return the sanitized referrer URL
                    case 'iafwzc_city':
                        return $this->get_user_location()['city']; // Get city from user location
                    case 'iafwzc_state':
                        return $this->get_user_location()['state']; // Get state from user location
                    case 'iafwzc_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('iafwzc_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,
                ];
            }
        }
        public function filter_criteria($form_data, $conditions_raw)
        {
            if (!isset($conditions_raw) || empty($conditions_raw)) {
                return 1; // No conditions to evaluate
            }
            // Decode conditions JSON into an array
            $conditions = json_decode($conditions_raw, true);

            $and_list = []; // To store AND groups
            $or_list = []; // To store OR groups
            $current_and_group = []; // Temporary AND group

            // Step 1: Group conditions into AND and OR lists
            foreach ($conditions as $condition) {
                $logic = $condition['logic'] ?? null;

                // Add condition to the current AND group
                $current_and_group[] = $condition;

                // Finalize the current group if logic is OR or null
                if ($logic === 'OR' || $logic === null) {
                    // Add the current AND group to the OR list
                    $or_list[] = $current_and_group;
                    $current_and_group = []; // Reset for the next group
                }
            }
            // Ensure any remaining conditions are added as a group
            if (!empty($current_and_group)) {
                $or_list[] = $current_and_group;
            }

            // Step 2: Evaluate AND groups within each OR group
            $or_results = []; // Store the results of OR groups

            foreach ($or_list as $and_group) {
                $and_result = true; // Initialize for AND evaluation

                foreach ($and_group as $condition) {
                    $field = $condition['field'] ?? null;
                    $cond = $condition['condition'] ?? null;
                    $value = $condition['value'] ?? null;

                    // If the field is missing in form data, treat as false
                    if (!isset($form_data[$field])) {
                        $current_result = false;
                    } else {
                        $form_value = $form_data[$field];
                        // Evaluate the condition
                        switch ($cond) {
                            case 'contains':
                                $current_result = strpos($form_value, $value) !== false;
                                break;

                            case 'not_contains':
                                $current_result = strpos($form_value, $value) === false;
                                break;

                            case 'starts_with':
                                $current_result = strpos($form_value, $value) === 0;
                                break;

                            case 'ends_with':
                                $current_result = substr($form_value, -strlen($value)) === $value;
                                break;

                            case 'equals':
                                // Handle type-insensitive comparison
                                if (is_numeric($form_value) && is_numeric($value)) {
                                    $current_result = (float)$form_value == (float)$value; // Compare as numbers
                                } else {
                                    $current_result = $form_value == $value; // Loose comparison
                                }
                                break;

                            case 'not_equals':
                                // Handle type-insensitive comparison
                                if (is_numeric($form_value) && is_numeric($value)) {
                                    $current_result = (float)$form_value != (float)$value; // Compare as numbers
                                } else {
                                    $current_result = $form_value != $value; // Loose comparison
                                }
                                break;

                            case 'greater_than':
                                // Check if inputs are numeric, convert strings to numbers if necessary
                                if (is_numeric($form_value) && is_numeric($value)) {
                                    $current_result = (float)$form_value > (float)$value;
                                } else {
                                    $current_result = false; // Invalid comparison for non-numeric values
                                }
                                break;

                            case 'less_than':
                                // Check if inputs are numeric, convert strings to numbers if necessary
                                if (is_numeric($form_value) && is_numeric($value)) {
                                    $current_result = (float)$form_value < (float)$value;
                                } else {
                                    $current_result = false; // Invalid comparison for non-numeric values
                                }
                                break;

                            case 'is_empty':
                                $current_result = empty($form_value) && $form_value !== '0'; // Consider empty but not the string "0"
                                break;

                            case 'is_not_empty':
                                $current_result = !empty($form_value) || $form_value === '0'; // Consider non-empty including the string "0"
                                break;

                            default:
                                $current_result = false; // Unsupported condition
                                break;
                        }
                    }

                    // Combine results within the AND group
                    $and_result = $and_result && $current_result;

                    // If any condition fails, short-circuit the AND group
                    if (!$and_result) {
                        break;
                    }
                }

                // Store the result of this AND group in the OR results
                $or_results[] = $and_result;
            }

            // Step 3: Combine all OR group results
            $final_result = false;
            foreach ($or_results as $result) {
                $final_result = $final_result || $result;

                // If any OR group passes, short-circuit the evaluation
                if ($final_result) {
                    break;
                }
            }

            return $final_result ? 1 : 0;
        }
    }
    $iafwzc_formSubmit = new iafwzc_FormSubmit();
}
