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

/**
 * Handles AJAX requests for integration setup and field mapping.
 */
function integrazo_fwcrm_form_handle_request()
{
    // Verify nonce for security
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'field_mapping_nonce')) {
        wp_send_json_error(['error' => 'Security check failed: Invalid or expired nonce. Please refresh the page and try again.']);
        wp_die();
    }

    $integrazo_fwcrm_form_accountDBInstance = new integrazo_fwcrm_form_Account_Table();
    $integrazo_fwcrm_form_formFieldsInstance = new integrazo_fwcrm_form_FormFields();
    $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
    try {
        // Retrieve and sanitize data from AJAX request
        $integration_name = isset($_POST['integration_name']) ? sanitize_text_field(wp_unslash($_POST['integration_name'])) : null;
        $form_value = isset($_POST['form_value']) ? sanitize_text_field(wp_unslash($_POST['form_value'])) : null;
        $account_id = isset($_POST['account_id']) ? sanitize_text_field(wp_unslash($_POST['account_id'])) : null;

        $module_api_name = isset($_POST['module_api_name']) ? sanitize_text_field(wp_unslash($_POST['module_api_name'])) : null;
        $field_mapping = isset($_POST['field_mapping']) ? sanitize_text_field(wp_unslash($_POST['field_mapping'])) : null;
        if ($field_mapping === '') {
            $field_mapping = null;
        }

        $record_action = isset($_POST['record_action']) ? sanitize_text_field(wp_unslash($_POST['record_action'])) : null;
        $integration_id = isset($_POST['setup_id']) ? sanitize_text_field(wp_unslash($_POST['setup_id'])) : null;
        if ($integration_id === '') {
            $integration_id = null;
        }

        $action_key = isset($_POST['action_key']) ? sanitize_text_field(wp_unslash($_POST['action_key'])) : null;
        // Parse the $form_value to extract form group ID and form ID
        $form_group_id = 0;
        $form_id = 0;

        if (!empty($form_value) && strpos($form_value, '_') !== false) {
            $form_parts = explode('_', $form_value, 2); // Limit the explode to 2 parts for safety
            $form_group_id = isset($form_parts[0]) ? intval($form_parts[0]) : 0;
            $form_id = isset($form_parts[1]) ? (string)$form_parts[1] : '';
        }
    } catch (Throwable $e) {
        wp_send_json_error(['error' => $e->getMessage()]);
        wp_die();
    }



    // Retrieve account details and access token
    $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"]);


        try {
            // Handle actions based on action key
            switch ($action_key) {
                case 'get_field':
                    $crm_field_list = $instance->get_module_fields($module_api_name);
                    $form_fields = $integrazo_fwcrm_form_formFieldsInstance->getFormFields($form_group_id, $form_id);
                    if (isset($crm_field_list['error'])) {
                        wp_send_json_error($crm_field_list);
                        wp_die();
                    } else {
                        // Assuming $crm_field_list is fetched from $instance->get_module_fields($module_api_name)
                        $crm_field_list = integrazo_fwcrm_form_categorizeCrmFields($crm_field_list);
                        wp_send_json_success([
                            'message' => "Module fields retrieved successfully",
                            'crm_fields' => $crm_field_list,
                            'form_fields' => $form_fields
                        ]);
                    }
                    break;

                case 'save_mapping':

                    // Create or update mapping based on integration ID
                    if (is_null($integration_id)) {
                        // Message 1: Integration saved successfully
                        set_transient(
                            'integrazo_fwcrm_form_setup_message',
                            'Integration saved successfully.',
                            300
                        );
                        $integrazo_fwcrm_form_fieldMappingDBInstance->create_mapping($integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping);
                    } else {
                        // Message 2: Integration updated successfully
                        set_transient(
                            'integrazo_fwcrm_form_setup_message',
                            'Integration updated successfully.',
                            300
                        );
                        $integrazo_fwcrm_form_fieldMappingDBInstance->update_mapping($integration_id, $integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping);
                    }

                    wp_send_json_success([
                        'message' => 'Mapping saved successfully'
                    ]);
                    break;

                default:
                    wp_send_json_error(['error' => 'Invalid action key']);
            }
        } catch (Throwable $e) {
            wp_send_json_error(['error' => $e->getMessage()]);
            wp_die();
        }
    } else {
        wp_send_json_error(['error' => 'Account details are not found.']);
        wp_die();
    }

    wp_die();
}

// Register the AJAX action for logged-in users
add_action('wp_ajax_integrazo_fwcrm_form_handle_request', 'integrazo_fwcrm_form_handle_request');

// Hook into admin_init for specific URL handling
add_action('admin_init', function () {
    // Check if the URL parameters are correct and specific to your plugin
    if (
        isset($_GET['page'], $_GET['action'], $_GET['setup_id'], $_GET['_wpnonce']) && // Include the nonce parameter
        $_GET['page'] === 'crm-integration-freshworks-any-form' && // Ensure the plugin's page parameter is correct
        $_GET['action'] === 'delete' // Ensure the action parameter is 'delete'
    ) {
        // Verify the nonce
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'delete_setup_nonce')) {
            wp_die(
                esc_html__('Unauthorized request. Please try again.', 'crm-integration-freshworks-any-form') // Use esc_html__() for escaping
            );
        }

        $integration_id = intval($_GET['setup_id']);
        $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
        if ($integration_id && isset($integrazo_fwcrm_form_fieldMappingDBInstance)) {
            // Perform the deletion using the delete_mapping function
            $integrazo_fwcrm_form_fieldMappingDBInstance->delete_mapping($integration_id);
            set_transient(
                'integrazo_fwcrm_form_setup_message',
                'Integration deleted successfully.',
                300
            );
            // Redirect to the specified page after deletion
            wp_safe_redirect(admin_url('admin.php?page=crm-integration-freshworks-any-form&tab=setup'));
            exit;
        }
    }
});


// Register the AJAX action for updating integration status
add_action('wp_ajax_integrazo_fwcrm_form_integration_status', 'integrazo_fwcrm_form_update_integration_status');

/**
 * Handles AJAX requests for updating the integration status.
 */
function integrazo_fwcrm_form_update_integration_status()
{
    // Verify nonce for security
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'field_mapping_nonce')) {
        wp_send_json_error(['message' => esc_html__('Security check failed', 'crm-integration-freshworks-any-form')]);
        wp_die();
    }

    try {
        // Sanitize incoming data
        $integration_id = isset($_POST['integration_id']) ? intval($_POST['integration_id']) : null;
        $integration_status = isset($_POST['integration_status']) ? sanitize_text_field(wp_unslash($_POST['integration_status'])) : null;

        if ($integration_id !== null) {
            $integrazo_fwcrm_form_fieldMappingDBInstance = new integrazo_fwcrm_form_FieldMapping();
            // Update the integration status in the database
            $updated = $integrazo_fwcrm_form_fieldMappingDBInstance->update_integration_status($integration_id, filter_var($integration_status, FILTER_VALIDATE_BOOLEAN));

            if ($updated) {
                wp_send_json_success(['message' => 'Integration status updated successfully']);
            } else {
                wp_send_json_error(['message' => 'Failed to update integration status']);
            }
        } else {
            wp_send_json_error(['message' => 'Invalid integration ID']);
        }

        wp_die();
    } catch (Throwable $e) {
        wp_send_json_error(['error' => $e->getMessage()]);
        wp_die();
    }
}

function integrazo_fwcrm_form_categorizeCrmFields($crm_field_list)
{
    $session = integrazo_fwcrm_form_is_valid_key();
    // Iterate through existing fields and categorize them
    foreach ($crm_field_list["fields"] as $index => &$field) {
        if ($field['name'] === "tags") {
            unset($crm_field_list['fields'][$index]);
        }
        // Set system mandatory for specific fields
        $field['system_mandatory'] = ($field['name'] === "emails" || $field['name'] === "name");

        // Check if the field is a custom field
        if (isset($field['name']) && strpos($field['name'], "cf_") === 0) {
            $field['integrazo_fwcrm_form_session'] = $session;
            $field['integrazo_fwcrm_form_group'] = 'Custom Fields';
        } elseif (in_array($field['name'], integrazo_fwcrm_form_getPremiumFields(), true)) {
            // Check if the field name matches specified premium field values
            $field['integrazo_fwcrm_form_session'] = $session;
            $field['integrazo_fwcrm_form_group'] = 'Premium Fields';
        } else {
            // For all other fields
            $field['integrazo_fwcrm_form_session'] = true;
            $field['integrazo_fwcrm_form_group'] = 'General Fields';
        }
    }

    // Add new fields for "Tag" and "Attachment"
    $new_fields = [
        [
            'name' => 'tags',
            'label' => 'Tags',
            'type' => 'tag',
            'system_mandatory' => false,
            'integrazo_fwcrm_form_group' => 'Premium Fields',
            'integrazo_fwcrm_form_session' => $session
        ],
        [
            'name' => 'attachment',
            'label' => 'Attachment',
            'type' => 'file',
            'system_mandatory' => false,
            'integrazo_fwcrm_form_group' => 'Premium Fields',
            'integrazo_fwcrm_form_session' => $session
        ]
    ];

    // Append each new field individually
    $crm_field_list['fields'] = array_merge($crm_field_list['fields'], $new_fields);

    return $crm_field_list;
}


function integrazo_fwcrm_form_getPremiumFields()
{
    return [
        'mobile_number',
        'work_number',
        'country',
        'lifecycle_stage_id',
        'contact_status_id',
        'lead_source_id',
        'subscription_status',
        'phone',
        'business_type_id',
        'website'
    ];
}
