<?php
/**
 * Get Blocked Countries AJAX Handler
 *
 * Handles AJAX requests to retrieve the list of blocked countries.
 *
 * @package VMPFence
 * @since 2.2.0
 */

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

/**
 * AJAX Handler: Get Blocked Countries
 *
 * @return void
 */
function vmpfence_ajax_get_blocked_countries() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'vmpfence_nonce')) {
        wp_send_json_error([
            'message' => 'Security verification failed'
        ], 403);
    }

    // Check user permissions
    if (!current_user_can('manage_options')) {
        wp_send_json_error([
            'message' => 'Insufficient permissions'
        ], 403);
    }

    // Get pagination parameters
    $page = isset($_POST['page']) ? max(1, (int) $_POST['page']) : 1;
    $per_page = isset($_POST['per_page']) ? max(1, min(100, (int) $_POST['per_page'])) : 50;
    $offset = ($page - 1) * $per_page;

    // Get countries from database
    $countries = VMPFence_Blocked_Country::get_blocked_countries([
        'limit' => $per_page,
        'offset' => $offset,
        'orderby' => 'blocked_at',
        'order' => 'DESC',
        'active_only' => true
    ]);

    // Get total count
    $total = VMPFence_Blocked_Country::get_blocked_count(true);

    // Load country flags from JSON
    $countries_file = VMPFENCE_PLUGIN_DIR . 'admin/data/countries.json';
    $flags_map = [];
    
    if (file_exists($countries_file)) {
        $json_content = file_get_contents($countries_file);
        $countries_data = json_decode($json_content, true);
        
        if (is_array($countries_data)) {
            foreach ($countries_data as $country) {
                if (isset($country['code'], $country['flag'])) {
                    $flags_map[$country['code']] = $country['flag'];
                }
            }
        }
    }

    // Add flag emojis to countries
    foreach ($countries as &$country) {
        $code = $country['country_code'];
        $country['flag'] = isset($flags_map[$code]) ? $flags_map[$code] : '🏴';
        
        // Ensure block_login and block_site are integers
        $country['block_login'] = (int) $country['block_login'];
        $country['block_site'] = (int) $country['block_site'];
        
        // Convert timestamps to integers
        $country['blocked_at'] = is_numeric($country['blocked_at']) 
            ? (int) $country['blocked_at'] 
            : strtotime($country['blocked_at']);
            
        if (isset($country['last_blocked_at'])) {
            $country['last_blocked_at'] = is_numeric($country['last_blocked_at'])
                ? (int) $country['last_blocked_at']
                : strtotime($country['last_blocked_at']);
        }
    }

    // Calculate pagination data
    $total_pages = ceil($total / $per_page);

    wp_send_json_success([
        'countries' => $countries,
        'pagination' => [
            'current_page' => $page,
            'per_page' => $per_page,
            'total' => $total,
            'total_pages' => $total_pages,
            'has_next' => $page < $total_pages,
            'has_prev' => $page > 1
        ]
    ]);
}

// Register AJAX handler
add_action('wp_ajax_vmpfence_get_blocked_countries', 'vmpfence_ajax_get_blocked_countries');
