<?php
/**
 * VMPFence Top Countries AJAX Handler
 * 
 * Handles AJAX requests for Top Countries by Attacks chart
 * 
 * @package VMPFence
 * @since 2.2.0
 */

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

class VMPFence_Top_Countries_Ajax {
    
    /**
     * Constructor - Register AJAX actions
     */
    public function __construct() {
        add_action('wp_ajax_vmpfence_get_top_countries', array($this, 'get_top_countries'));
    }
    
    /**
     * Get top attacking countries for specified period
     * 
     * AJAX handler for fetching most attacked-from countries
     * 
     * @since 2.2.0
     * @return void
     */
    public function get_top_countries() {
        // Verify nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'vmpfence_top_countries_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']) : '7d';
        
        // Validate period value
        $valid_periods = array('24h', '7d', '30d');
        if (!in_array($period, $valid_periods, true)) {
            $period = '7d'; // Default fallback
        }
        
        // Check if Blocked Country class exists
        if (!class_exists('VMPFence_Blocked_Country')) {
            wp_send_json_error(array(
                'message' => 'Blocked Country class not available'
            ));
            return;
        }
        
        try {
            // Get top attacking countries from database
            $top_countries = VMPFence_Blocked_Country::get_top_attacking_countries($period, 10);
            
            // Return success with data
            wp_send_json_success(array(
                'countries' => $top_countries,
                'period' => $period,
                'count' => count($top_countries)
            ));
            
        } catch (Exception $e) {
            // Log error and return failure
            if (class_exists('VMPFence_Secure_Logger')) {
                VMPFence_Secure_Logger::error('Top Countries Error: ' . $e->getMessage());
            }
            
            wp_send_json_error(array(
                'message' => 'Failed to retrieve country attack data'
            ));
        }
    }
}

// Initialize the AJAX handler
new VMPFence_Top_Countries_Ajax();
