<?php
/**
 * Tools AJAX Handler
 *
 * @package VMPFence
 * @subpackage Tools
 * @since 2.1.0
 * @since 2.2.0 Load Diagnostic controller
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Load the controller
require_once plugin_dir_path(dirname(__FILE__)) . 'controllers/class-live-traffic-controller.php';

// Load diagnostic controller
require_once plugin_dir_path(dirname(__FILE__)) . 'controllers/class-diagnostic-controller.php';

// Initialize the controller
VMPFence_Live_Traffic_Controller::init();

// Initialize diagnostic controller
$diagnostic_controller = new VMPFence_Tools_Diagnostic_Controller();
$diagnostic_controller->register_ajax_actions();

/**
 * AJAX Handler: Mark visitor as human via JavaScript beacon
 *
 * @since 2.1.0
 */
function vmpfence_ajax_mark_human_visitor() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_beacon')) {
        wp_send_json_error(array('message' => 'Invalid nonce'));
        return;
    }

    // Get IP and user agent from request
    $ip = VMPFence_Utils::get_real_ip();
    $ua = sanitize_text_field($_SERVER['HTTP_USER_AGENT'] ?? '');

    // Validate IP
    if (empty($ip)) {
        wp_send_json_error(array('message' => 'Invalid IP'));
        return;
    }

    // Use visitor classifier to cache as human
    if (class_exists('VMPFence_Visitor_Classifier')) {
        // Cache for 1 hour (3600 seconds)
        VMPFence_Visitor_Classifier::cache_classification($ip, 'human', 3600);
        
        wp_send_json_success(array(
            'message' => 'Visitor marked as human',
            'ip' => $ip
        ));
    } else {
        wp_send_json_error(array('message' => 'Classifier not available'));
    }
}

// Register AJAX handlers (both logged in and logged out)
add_action('wp_ajax_vmpfence_mark_human_visitor', 'vmpfence_ajax_mark_human_visitor');
add_action('wp_ajax_nopriv_vmpfence_mark_human_visitor', 'vmpfence_ajax_mark_human_visitor');

/**
 * AJAX Handler: WHOIS Lookup
 *
 * @since 2.1.0
 */
function vmpfence_ajax_whois_lookup() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_tools_nonce')) {
        wp_send_json_error(array('message' => __('Security check failed.', 'vmpfence-security')));
        return;
    }

    // Check user permissions
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => __('Permission denied.', 'vmpfence-security')));
        return;
    }

    // Get and validate input
    $input = isset($_POST['input']) ? sanitize_text_field($_POST['input']) : '';

    if (empty($input)) {
        wp_send_json_error(array('message' => __('No IP address or domain provided.', 'vmpfence-security')));
        return;
    }

    // Perform lookup
    $result = VMPFence_Whois_Lookup::lookup($input);

    // Check for errors
    if (is_wp_error($result)) {
        wp_send_json_error(array('message' => $result->get_error_message()));
        return;
    }

    // Return success with data (merge result directly to avoid double-nesting)
    wp_send_json_success(array_merge(
        $result,
        array('message' => __('Lookup completed successfully.', 'vmpfence-security'))
    ));
}

// Register WHOIS AJAX handler (admin only)
add_action('wp_ajax_vmpfence_whois_lookup', 'vmpfence_ajax_whois_lookup');

