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

/**
 * Handles AJAX requests for AI settings.
 */
function iafwzcai_ai_settings_request()
{
    // Verify nonce for security
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'iafwzcai_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-campaigns')]);
        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-campaigns')]);
            wp_die();
        }

        // Handle actions based on action key
        switch ($action_key) {
            case 'Spam_Detection':
                update_option("iafwzcai_spam_detection_keywords", $keyword);
                update_option("iafwzcai_spam_detection_handling", $action_type);
                break;
            case 'Email_Detection':
                update_option("iafwzcai_email_detection_keywords", $keyword);
                update_option("iafwzcai_email_detection_handling", $action_type);
                break;
            case 'Email_Validation':
                update_option("iafwzcai_email_validation_keywords", $keyword);
                update_option("iafwzcai_email_validation_handling", $action_type);
                break;
            default:
                wp_send_json_error(['error' => __('Invalid action key.', 'integrate-with-zoho-campaigns')]);
                wp_die();
        }

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

    wp_die();
}

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