<?php
/**
 * Unblock Country AJAX Handler
 *
 * Handles AJAX requests to unblock a single country.
 *
 * @package VMPFence
 * @since 2.2.0
 * @since 2.2.5 -- Added Enhanced Audit Log integration for unblock country action
 */

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

/**
 * AJAX Handler: Unblock Country
 *
 * @return void
 */
function vmpfence_ajax_unblock_country() {
    // 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);
    }

    // Validate input
    if (empty($_POST['country_code'])) {
        wp_send_json_error([
            'message' => 'Country code not provided'
        ], 400);
    }

    $country_code = strtoupper(sanitize_text_field($_POST['country_code']));

    // Validate country code format (ISO 3166-1 alpha-2)
    if (!preg_match('/^[A-Z]{2}$/', $country_code)) {
        wp_send_json_error([
            'message' => 'Invalid country code format'
        ], 400);
    }

    // Check if country is actually blocked
    if (!VMPFence_Blocked_Country::is_country_blocked($country_code)) {
        wp_send_json_error([
            'message' => 'Country is not blocked'
        ], 404);
    }

    // Get country details before deletion (for logging)
    $country = VMPFence_Blocked_Country::get_country($country_code);

    // Unblock the country
    $result = VMPFence_Blocked_Country::unblock_country($country_code);

    if ($result) {
        // Clear blocked country cache
        VMPFence_Blocked_Country::clear_cache();
        
        // Clear GeoIP cache for all IPs (critical: prevents stale cache showing old block status)
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_geoip_%'");
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_vmpfence_geoip_%'");

        // Log the action
        if (class_exists('VMPFence_Secure_Logger') && $country) {
            VMPFence_Secure_Logger::log(
                'security',
                sprintf('Country unblocked: %s (%s)', 
                    $country['country_name'] ?? $country_code,
                    $country_code
                ),
                'country_unblocked',
                [
                    'country_code' => $country_code,
                    'country_name' => $country['country_name'] ?? '',
                    'previous_block_count' => $country['block_count'] ?? 0,
                    'blocked_at' => $country['blocked_at'] ?? null,
                    'unblocked_by' => wp_get_current_user()->user_login
                ]
            );
        }

        // Fire audit log hook
        do_action('vmpfence_country_unblocked', $country_code);

        wp_send_json_success([
            'message' => sprintf(
                '%s (%s) has been unblocked successfully',
                $country['country_name'] ?? $country_code,
                $country_code
            ),
            'country_code' => $country_code
        ]);
    } else {
        wp_send_json_error([
            'message' => 'Failed to unblock country. Please try again.'
        ], 500);
    }
}

// Register AJAX handler
add_action('wp_ajax_vmpfence_unblock_country', 'vmpfence_ajax_unblock_country');
