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

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['error' => 'Insufficient permissions.']);
        wp_die();
    }

    $iafwzc_accountDBInstance = new IAFWZC_Account_Table();
    $iafwzc_zohoCRMInstance = new IAFWZC_Zoho_CRM();
    $iafwzc_zohoBiginInstance = new IAFWZC_Zoho_Bigin();
    $IAFWZC_Form_FieldsInstance = new IAFWZC_Form_Fields();
    $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();
    $session = iafwzc_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 = isset($_POST['record_action']) ? sanitize_text_field(wp_unslash($_POST['record_action'])) : null;
        $record_action = iafwzc_record_action($record_action);
        $primary_key = isset($_POST['primary_key']) ? sanitize_text_field(wp_unslash($_POST['primary_key'])) : null;
        if ($primary_key === '' || $record_action === "add_ignore_existing") {
            $primary_key = null;
        }
        $note_sts = isset($_POST['note_sts']) ? sanitize_text_field(wp_unslash($_POST['note_sts'])) : null;
        if ($note_sts === '') {
            $note_sts = null;
        }
        $note_content = isset($_POST['note_content']) ? sanitize_text_field(wp_unslash($_POST['note_content'])) : null;
        if ($note_content === '') {
            $note_content = null;
        }
        $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 = $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") {
            $instance = new IAFWZC_Zoho_Bigin($account_details, $accessToken);
        } else {
            $instance = new IAFWZC_Zoho_CRM($account_details, $accessToken);
        }

        try {
            // Handle actions based on action key
            switch ($action_key) {
                /*case 'get_module':

                    $module_list = $instance->get_modules();

                    if (isset($module_list['error'])) {
                        wp_send_json_error($module_list);
                        wp_die();
                    } else {

                        $filtered_modules = array_filter($module_list, function ($module) use ($session) {
                            return in_array($module['api_name'], iafwzc_module_list())
                                || ($module['generated_type'] === 'custom' && $session === true);
                        });

                        // Reindex the array to maintain sequential keys if necessary
                        $filtered_modules = array_values($filtered_modules);

                        wp_send_json_success([
                            'message' => "Modules retrieved successfully",
                            'modules' => $filtered_modules
                        ]);
                    }
                    break;*/
                case 'get_module':
                    $module_list = $instance->get_modules();

                    if (isset($module_list['error'])) {
                        wp_send_json_error($module_list);
                        wp_die();
                    } else {
                        $module_list = array_map(function ($module) use ($session) {
                            $module['iafwzc_session'] = $session;
                            if ($module['generated_type'] === 'custom') {
                                $module['api_name'] = 'iafwzc_cm_' . $module['api_name'];
                            }
                            return $module;
                        }, $module_list);

                        wp_send_json_success([
                            'message' => "Modules retrieved successfully",
                            'modules' => array_values($module_list)
                        ]);
                    }
                    break;

                case 'get_field':
                    // Strip custom module prefix if present
                    if (strpos($module_api_name, 'iafwzc_cm_') === 0) {
                        $module_api_name = substr($module_api_name, strlen('iafwzc_cm_'));
                    }
                    $crm_field_list = $instance->get_module_fields($module_api_name);

                    $form_fields = $IAFWZC_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 = iafwzc_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(
                            'iafwzc_setup_message',
                            'Integration saved successfully.',
                            300
                        );
                        $IAFWZC_Field_MappingDBInstance->create_mapping($integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping, $primary_key, $note_sts, $note_content, $filter_Criteria);
                    } else {
                        // Message 2: Integration updated successfully
                        set_transient(
                            'iafwzc_setup_message',
                            'Integration updated successfully.',
                            300
                        );
                        $IAFWZC_Field_MappingDBInstance->update_mapping($integration_id, $integration_name, $form_group_id, $form_id, $account_id, $module_api_name, $record_action, $field_mapping, $primary_key, $note_sts, $note_content, $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_iafwzc_handle_request', 'iafwzc_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-any-form-with-zoho-crm' && // Ensure the plugin's page parameter is correct
        $_GET['action'] === 'delete' // Ensure the action parameter is 'delete'
    ) {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'integrate-any-form-with-zoho-crm'));
        }

        // 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-any-form-with-zoho-crm') // Use esc_html__() for escaping
            );
        }

        $integration_id = intval($_GET['setup_id']);
        $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

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


// Register the AJAX action for updating integration status
add_action('wp_ajax_iafwzc_integration_status', 'iafwzc_update_integration_status');

/**
 * Handles AJAX requests for updating the integration status.
 */
function iafwzc_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-any-form-with-zoho-crm')]);
        wp_die();
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => esc_html__('Insufficient permissions.', 'integrate-any-form-with-zoho-crm')]);
        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) {
            $IAFWZC_Field_MappingDBInstance = new IAFWZC_Field_Mapping();

            // Update the integration status in the database
            $updated = $IAFWZC_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 iafwzc_categorizeCrmFields($crm_field_list)
{
    $session = iafwzc_is_valid_key();
    $count = 1;
    // Iterate through existing fields and categorize them
    foreach ($crm_field_list["fields"] as &$field) {
        // Check if the field is a custom field
        if (isset($field['custom_field']) && $field['custom_field'] === true) {
            // if (!$session) {
            //     $field['api_name'] = strval($count);
            // }
            // $field['iafwzc_is_premium'] = true;
            $field['api_name'] = "iafwzc_cf_" . $field['api_name'];
            $field['iafwzc_group'] = 'Custom Fields';
            $field['iafwzc_session'] = $session;
        } elseif (
            in_array($field['api_name'], iafwzc_getPremiumFields(), true)
        ) {
            // Check if 'api_name' matches specified values
            // if (!$session) {
            //     $field['api_name'] = strval($count);
            // }
            // $field['iafwzc_is_premium'] = true;
            $field['iafwzc_group'] = 'Premium Fields';
            $field['iafwzc_session'] = $session;
        } else {
            // For all other fields
            // $field['iafwzc_is_premium'] = false;
            $field['iafwzc_group'] = 'General Fields';
            $field['iafwzc_session'] = true;
        }
        // allowedValues for info icon
        if (isset($field['pick_list_values']) && is_array($field['pick_list_values']) && !empty($field['pick_list_values'])) {
            $field['allowedValues'] = array_map(function ($item) {
                return ['value' => isset($item['actual_value']) ? $item['actual_value'] : ''];
            }, $field['pick_list_values']);
        } else {
            $field['allowedValues'] = [];
        }
        $count++; // Proper increment
    }

    // Add new fields for "Tag" and "Attachment"
    $new_fields = [
        [
            'api_name' => 'tag',
            'display_label' => 'Tag',
            'data_type' => 'tag',
            'system_mandatory' => false,
            'field_read_only' => false,
            'view_type' => ['edit' => true],
            // 'iafwzc_is_premium' => true,
            'iafwzc_group' => 'Premium Fields',
            'iafwzc_session' =>  $session
        ],
        [
            'api_name' => 'attachment',
            'display_label' => 'Attachment',
            'data_type' => 'file',
            'system_mandatory' => false,
            'field_read_only' => false,
            'view_type' => ['edit' => true],
            // 'iafwzc_is_premium' => true,
            'iafwzc_group' => 'Premium Fields',
            'iafwzc_session' =>  $session
        ]
    ];

    // Append each new field individually
    foreach ($new_fields as $new_field) {
        $crm_field_list['fields'][] = $new_field;
    }

    return $crm_field_list;
}
function iafwzc_getPremiumFields()
{
    return [
        'Account_Name',
        'Account_Type',
        'Amount',
        'Asst_Phone',
        'Billing_Country',
        'Billing_State',
        'Campaign_Source',
        'Company',
        'Country',
        'Description',
        'Email_Opt_Out',
        'Enrich_Status__s',
        'Home_Phone',
        'Industry',
        'Lead_Source',
        'Lead_Status',
        'Mailing_City',
        'Mailing_Country',
        'Mailing_State',
        'Mobile',
        'Other_City',
        'Other_Country',
        'Other_Phone',
        'Other_State',
        'Phone',
        'Priority',
        'Reason_For_Loss__s',
        'Record_Image',
        'Referrer',
        'Shipping_Country',
        'Shipping_State',
        'State',
        'Status',
        'Type',
        'Unsubscribed_Mode',
        'Vendor_Name',
        'Visitor_Score',
        'Website',
    ];
}
function iafwzc_record_action($record_action)
{
    $session = iafwzc_is_valid_key();
    $session_record_actions = [
        'skip_if_exists',
        'add_or_update',
        'update_only',
        'add_tag_if_duplicate'
    ];

    // 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;
}
function iafwzc_module_list()
{
    return ['Leads', 'Contacts', 'Accounts'];
}
