<?php
/**
 * Block Countries AJAX Handler
 *
 * Handles AJAX requests to block multiple countries at once.
 *
 * @package VMPFence
 * @since 2.2.0
 * @since 2.2.5 -- Added Enhanced Audit Log integration for block country action
 */

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

/**
 * AJAX Handler: Block Countries
 *
 * @return void
 */
function vmpfence_ajax_block_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);
    }

    // Validate input
    if (empty($_POST['countries']) || !is_array($_POST['countries'])) {
        wp_send_json_error([
            'message' => 'No countries provided'
        ], 400);
    }

    $countries = array_map('sanitize_text_field', $_POST['countries']);
    $block_login = isset($_POST['block_login']) ? (int) $_POST['block_login'] : 0;
    $block_site = isset($_POST['block_site']) ? (int) $_POST['block_site'] : 0;
    $reason = isset($_POST['reason']) ? sanitize_textarea_field($_POST['reason']) : '';

    // Validate at least one block type is selected
    if ($block_login === 0 && $block_site === 0) {
        wp_send_json_error([
            'message' => 'Please select at least one blocking type (Login or Entire Site)'
        ], 400);
    }

    // Validate country codes (ISO 3166-1 alpha-2)
    $valid_countries = [];
    foreach ($countries as $code) {
        $code = strtoupper($code);
        if (preg_match('/^[A-Z]{2}$/', $code)) {
            $valid_countries[] = $code;
        }
    }

    if (empty($valid_countries)) {
        wp_send_json_error([
            'message' => 'No valid country codes provided'
        ], 400);
    }

    // Load countries data for name lookup
    $countries_file = VMPFENCE_PLUGIN_DIR . 'admin/data/countries.json';
    $countries_data = [];
    
    if (file_exists($countries_file)) {
        $json_content = file_get_contents($countries_file);
        $countries_array = json_decode($json_content, true);
        
        if (is_array($countries_array)) {
            foreach ($countries_array as $country) {
                if (isset($country['code'], $country['name'])) {
                    $countries_data[$country['code']] = $country['name'];
                }
            }
        }
    }

    // Block countries
    $success_count = 0;
    $already_blocked = [];
    $errors = [];

    foreach ($valid_countries as $code) {
        // Check if already blocked
        if (VMPFence_Blocked_Country::is_country_blocked($code)) {
            $already_blocked[] = $code;
            continue;
        }

        // Get country name
        $country_name = isset($countries_data[$code]) ? $countries_data[$code] : $code;

        // Add to database
        $result = VMPFence_Blocked_Country::add_blocked_country(
            $code,
            $country_name,
            $reason,         // Position 3: reason
            $block_login,    // Position 4: block_login
            $block_site,     // Position 5: block_site
            0                // Position 6: blocked_until (permanent)
        );

        if ($result) {
            $success_count++;
            
            // Log the action
            if (class_exists('VMPFence_Secure_Logger')) {
                VMPFence_Secure_Logger::log(
                    'security',
                    sprintf('Country blocked: %s (%s) - Login: %s, Site: %s',
                        $country_name,
                        $code,
                        $block_login ? 'Yes' : 'No',
                        $block_site ? 'Yes' : 'No'
                    ),
                    'country_blocked',
                    [
                        'country_code' => $code,
                        'country_name' => $country_name,
                        'block_login' => $block_login,
                        'block_site' => $block_site,
                        'reason' => $reason
                    ]
                );
            }

            // Fire audit log hook
            do_action('vmpfence_country_blocked', $code);
        } else {
            $errors[] = $code;
        }
    }

    // Prepare response
    $response = [
        'blocked' => $success_count,
        'total' => count($valid_countries)
    ];

    if (!empty($already_blocked)) {
        $response['already_blocked'] = count($already_blocked);
        $response['already_blocked_codes'] = $already_blocked;
    }

    if (!empty($errors)) {
        $response['errors'] = $errors;
    }

    // Clear the country blocker cache so new countries are detected immediately
    if ($success_count > 0) {
        delete_transient('vmpfence_has_blocked_countries');
        
        // Also clear the blocked country model cache if it exists
        if (class_exists('VMPFence_Blocked_Country') && method_exists('VMPFence_Blocked_Country', 'clear_cache')) {
            VMPFence_Blocked_Country::clear_cache();
        }
    }

    // Generate message
    if ($success_count > 0) {
        $message = sprintf(
            _n(
                '%d country blocked successfully',
                '%d countries blocked successfully',
                $success_count,
                'vmpfence-security'
            ),
            $success_count
        );

        if (!empty($already_blocked)) {
            $message .= sprintf(
                ' (%d already blocked)',
                count($already_blocked)
            );
        }

        wp_send_json_success([
            'message' => $message,
            'data' => $response
        ]);
    } elseif (!empty($already_blocked)) {
        wp_send_json_error([
            'message' => 'All selected countries are already blocked',
            'data' => $response
        ], 400);
    } else {
        wp_send_json_error([
            'message' => 'Failed to block countries',
            'data' => $response
        ], 500);
    }
}

// Register AJAX handlers
add_action('wp_ajax_vmpfence_block_countries', 'vmpfence_ajax_block_countries');
