<?php
/**
 * VMPFence Top IPs AJAX Handler
 * 
 * Handles AJAX requests for Top IPs Blocked chart
 * 
 * @package VMPFence
 * @since 2.1.0
 */

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

class VMPFence_Top_IPs_Ajax {
    
    /**
     * Constructor - Register AJAX actions
     */
    public function __construct() {
        add_action('wp_ajax_vmpfence_get_top_blocked_ips', array($this, 'get_top_blocked_ips'));
    }
    
    /**
     * Get top blocked IPs for specified period
     * 
     * AJAX handler for fetching most blocked IP addresses
     * 
     * @since 2.1.0
     * @return void
     */
    public function get_top_blocked_ips() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'vmpfence_top_ips_nonce')) {
            wp_send_json_error(array(
                'message' => 'Security check failed'
            ));
            return;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => 'Insufficient permissions'
            ));
            return;
        }
        
        // Get and validate period parameter
        $period = isset($_POST['period']) ? sanitize_text_field($_POST['period']) : '24h';
        
        // Validate period value
        $valid_periods = array('24h', '7d', '30d');
        if (!in_array($period, $valid_periods, true)) {
            $period = '24h'; // Default fallback
        }
        
        // Check if WAF Log class exists
        if (!class_exists('VMPFence_WAF_Log')) {
            wp_send_json_error(array(
                'message' => 'WAF Log class not available'
            ));
            return;
        }
        
        try {
            // Get top blocked IPs from database
            $top_ips = VMPFence_WAF_Log::get_top_blocked_ips($period, 10);
            
            // Return success with data
            wp_send_json_success(array(
                'ips' => $top_ips,
                'period' => $period,
                'count' => count($top_ips)
            ));
            
        } catch (Exception $e) {
            // Log error and return failure
            // error_log('VMPFence Top IPs Error: ' . $e->getMessage());
            
            wp_send_json_error(array(
                'message' => 'Failed to retrieve blocked IPs data'
            ));
        }
    }
}

// Initialize the AJAX handler
new VMPFence_Top_IPs_Ajax();
