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

/**
 * Handles AJAX requests for AI settings.
 */
function iafwzdesk_ai_settings_request()
{
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['error' => __('Unauthorized.', 'integrate-with-zoho-desk')]);
        wp_die();
    }

    // Verify nonce for security
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'iafwzdesk_ai_settings_nonce')) {
        wp_send_json_error(['error' => __('Security check failed: Invalid or expired nonce. Please refresh the page and try again.', 'integrate-with-zoho-desk')]);
        wp_die();
    }

    try {
        // Retrieve and sanitize data from AJAX request
        $keyword = isset($_POST['keyword']) ? sanitize_text_field(wp_unslash($_POST['keyword'])) : '';
        $action_type = isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : '';
        $action_key = isset($_POST['action_key']) ? sanitize_text_field(wp_unslash($_POST['action_key'])) : '';

        if (empty($action_key)) {
            wp_send_json_error(['error' => __('Action key is required.', 'integrate-with-zoho-desk')]);
            wp_die();
        }

        // Handle actions based on action key
        switch ($action_key) {
            case 'Spam_Detection':
                update_option("iafwzdesk_spam_detection_keywords", $keyword);
                update_option("iafwzdesk_spam_detection_handling", $action_type);
                break;
            case 'Email_Detection':
                update_option("iafwzdesk_email_detection_keywords", $keyword);
                update_option("iafwzdesk_email_detection_handling", $action_type);
                break;
            case 'Email_Validation':
                update_option("iafwzdesk_email_validation_keywords", $keyword);
                update_option("iafwzdesk_email_validation_handling", $action_type);
                break;
            default:
                wp_send_json_error(['error' => __('Invalid action key.', 'integrate-with-zoho-desk')]);
                wp_die();
        }

        wp_send_json_success([
            'message' => __('Settings saved successfully.', 'integrate-with-zoho-desk'),
            'keyword' => $keyword,
            'action_type' => $action_type
        ]);
    } catch (Throwable $e) {
        wp_send_json_error(['error' => __('An unexpected error occurred: ', 'integrate-with-zoho-desk') . $e->getMessage()]);
    }

    wp_die();
}

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