<?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 iafwzdesk_handle_request()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['error' => 'Unauthorized.']);
        wp_die();
    }

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

    $iafwzdesk_accountDBInstance = new IAFWZDESK_Account_Table();
    $IAFWZDESK_Form_FieldsInstance = new IAFWZDESK_Form_Fields();
    $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();
    $session = iafwzdesk_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;
        }
        if ($filter_Criteria !== null) {
            json_decode($filter_Criteria);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $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 = $iafwzdesk_accountDBInstance->get_single_account_data($account_id);
    $accessToken = IAFWZDESK_Util::getAccessToken($account_id);

    if ($account_details) {
        $instance = new IAFWZDESK_PRODUCT($account_details, $accessToken);
        try {
            // Handle actions based on action key
            switch ($action_key) {

                case 'get_department_list':
                    $contact_list = $instance->get_desk_departments();
                    if (isset($contact_list['error'])) {
                        wp_send_json_error([
                            'error' => $contact_list['error']
                        ]);
                    } else {
                        wp_send_json_success([
                            'message' => "Zoho Desk 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_desk_departments_fields($module_api_name);
                    $form_fields = $IAFWZDESK_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 = iafwzdesk_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(
                            'iafwzdesk_setup_message',
                            'Integration saved successfully.',
                            300
                        );
                        $IAFWZDESK_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(
                            'iafwzdesk_setup_message',
                            'Integration updated successfully.',
                            300
                        );
                        $IAFWZDESK_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_iafwzdesk_handle_request', 'iafwzdesk_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-desk' && // 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-desk') // Use esc_html__() for escaping
            );
        }

        $integration_id = intval($_GET['setup_id']);
        $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();

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


// Register the AJAX action for updating integration status
add_action('wp_ajax_iafwzdesk_integration_status', 'iafwzdesk_update_integration_status');

/**
 * Handles AJAX requests for updating the integration status.
 */
function iafwzdesk_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-desk')]);
        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) {
            $IAFWZDESK_Field_MappingDBInstance = new IAFWZDESK_Field_Mapping();

            // Update the integration status in the database
            $updated = $IAFWZDESK_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 iafwzdesk_categorizeCrmFields($crm_field_list)
{
    $session = iafwzdesk_is_valid_key();
    $ignore_fields = iafwzdesk_ignoreFields();
    $result = [];

    foreach ($crm_field_list as $field) {
        if (in_array($field['apiName'], $ignore_fields, true)) {
            continue; // Skip ignored fields
        }
        // Force email field as mandatory
        if ($field['apiName'] === 'email') {
            $field['isMandatory'] = true;
        }
        if (isset($field['isCustomField']) && $field['isCustomField'] === true) {
            $field['apiName'] = "iafwzdesk_cf_" . $field['apiName'];
            $field['iafwzdesk_group'] = 'Custom Fields';
            $field['iafwzdesk_session'] = $session;
        } elseif (
            in_array($field['apiName'], iafwzdesk_getPremiumFields(), true)
        ) {
            $field['iafwzdesk_group'] = 'Premium Fields';
            $field['iafwzdesk_session'] = $session;
        } else {
            // For all other fields
            $field['iafwzdesk_group'] = 'General Fields';
            $field['iafwzdesk_session'] = true;
        }

        $result[] = $field;
    }
    //Add new fields for "Attachment"
    $new_fields = [
        [
            'apiName' => 'attachment',
            'displayLabel' => 'Attachment',
            'type' => 'file',
            'isMandatory' => false,
            'iafwzdesk_group' => 'Premium Fields',
            'iafwzdesk_session' =>  $session
        ]
    ]; 
     // Append each new field individually
    foreach ($new_fields as $new_field) {
        $result[] = $new_field;
    }
    return $result;
}

function iafwzdesk_getPremiumFields()
{
    return [
        //
        'dueDate',
        'phone',
        'priority',
        'classification',
        'channel',
        'language',
        'productId',
        'resolution',
        'assigneeId',
        'productId',
        'productId',
    ];
}
function iafwzdesk_ignoreFields()
{
    return [
        //
        'departmentId',
        'accountId',
        'entitySkills',
    ];
}

function iafwzdesk_record_action($record_action)
{
    $session = iafwzdesk_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;
}
