<?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 iafwzcai_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();
    }

    $iafwzcai_accountDBInstance = new IAFWZCAI_Account_Table();
    $IAFWZCAI_Form_FieldsInstance = new IAFWZCAI_Form_Fields();
    $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();
    $session = iafwzcai_is_valid_key();

    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 = "add_ignore_existing";

        $filter_Criteria = isset($_POST['filter_Criteria']) ? sanitize_text_field(wp_unslash($_POST['filter_Criteria'])) : null;
        if ($filter_Criteria === '') {
            $filter_Criteria = 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 = $iafwzcai_accountDBInstance->get_single_account_data($account_id);
    $accessToken = IAFWZCAI_Util::getAccessToken($account_id);

    if ($account_details) {
        $instance = new IAFWZCAI_PRODUCT($account_details, $accessToken);
        try {
            // Handle actions based on action key
            switch ($action_key) {
                case 'get_mailchimp_list';
                    $contact_list = $instance->get_campaign_lists();
                    if (isset($contact_list['error'])) {
                        wp_send_json_error([
                            'error' => $contact_list['error']
                        ]);
                    } else {
                        wp_send_json_success([
                            'message' => "Zoho Campaigns lists retrieved successfully",
                            'contact_list' => $contact_list // Corrected variable name
                        ]);
                    }
                    break;
                case 'get_field':
                    // $crm_field_list = $instance->get_module_fields($module_api_name);
                    $crm_field_list = $instance->get_all_fields();
                    $form_fields = $IAFWZCAI_Form_FieldsInstance->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 = iafwzcai_categorizeCrmFields($crm_field_list);

                        wp_send_json_success([
                            'message' => "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(
                            'iafwzcai_setup_message',
                            'Integration saved successfully.',
                            300
                        );
                        $IAFWZCAI_Field_MappingDBInstance->create_mapping($integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping, $filter_Criteria);
                    } else {
                        // Message 2: Integration updated successfully
                        set_transient(
                            'iafwzcai_setup_message',
                            'Integration updated successfully.',
                            300
                        );
                        $IAFWZCAI_Field_MappingDBInstance->update_mapping($integration_id, $integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping, $filter_Criteria);
                    }

                    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_iafwzcai_handle_request', 'iafwzcai_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'] === 'integrate-with-zoho-campaigns' && // 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.', 'integrate-with-zoho-campaigns') // Use esc_html__() for escaping
            );
        }

        $integration_id = intval($_GET['setup_id']);
        $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();

        if ($integration_id && isset($IAFWZCAI_Field_MappingDBInstance)) {
            // Perform the deletion using the delete_mapping function
            $IAFWZCAI_Field_MappingDBInstance->delete_mapping($integration_id);
            set_transient(
                'iafwzcai_setup_message',
                'Integration deleted successfully.',
                300
            );
            // Redirect to the specified page after deletion
            wp_safe_redirect(admin_url('admin.php?page=integrate-with-zoho-campaigns&tab=setup'));
            exit;
        }
    }
});


// Register the AJAX action for updating integration status
add_action('wp_ajax_iafwzcai_integration_status', 'iafwzcai_update_integration_status');

/**
 * Handles AJAX requests for updating the integration status.
 */
function iafwzcai_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', 'integrate-with-zoho-campaigns')]);
        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) {
            $IAFWZCAI_Field_MappingDBInstance = new IAFWZCAI_Field_Mapping();

            // Update the integration status in the database
            $updated = $IAFWZCAI_Field_MappingDBInstance->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 iafwzcai_categorizeCrmFields($crm_field_list)
{
    $session = iafwzcai_is_valid_key();
    foreach ($crm_field_list as &$field) {
        if (isset($field['TYPE']) && $field['TYPE'] === 'custom') {
            $field['FIELD_NAME'] = "iafwzcai_cf_" . $field['FIELD_NAME'];
            $field['iafwzcai_group'] = 'Custom Fields';
            $field['iafwzcai_session'] = $session;
        } elseif (
            in_array($field['FIELD_NAME'], iafwzcai_getPremiumFields(), true)
        ) {
            $field['iafwzcai_group'] = 'Premium Fields';
            $field['iafwzcai_session'] = $session;
        } else {
            // For all other fields
            $field['iafwzcai_group'] = 'General Fields';
            $field['iafwzcai_session'] = true;
        }
    }

    return $crm_field_list;
}
function iafwzcai_getPremiumFields()
{
    return [
        //
        'companyname',
        'phone',
        'mobile',
        'city',
        'state',
        'zipcode',
        'country',
        'website',
        'lead_source',
        'firstname',
        'lastname'
    ];
}

function iafwzcai_record_action($record_action)
{
    $session = iafwzcai_is_valid_key();
    $session_record_actions = [
        'skip_if_exists',
        'add_or_update',
        'update_only',
    ];

    // Check if the session is invalid and the action is in the array
    if (!$session && in_array($record_action, $session_record_actions, true)) {
        return "add_ignore_existing";
    }

    // Optionally, return null or another default value if conditions aren't met
    return $record_action;
}
