<?php
/**
 * AJAX Handler for Blocked IP Sync
 *
 * @package VMPFence
 * @since 2.1.0
 */

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

/**
 * AJAX handler: Sync blocked IPs from API
 */
add_action('wp_ajax_vmpfence_sync_blocked_ips', 'vmpfence_ajax_sync_blocked_ips');

function vmpfence_ajax_sync_blocked_ips() {
    // Verify nonce
    check_ajax_referer('vmpfence_sync_blocked_ips', 'nonce');
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => 'Permission denied'
        ));
    }
    
    // Use the MODEL class sync method (inserts to database, not just JSON file)
    $stats = VMPFence_Blocked_IP::sync_from_api();
    
    if (empty($stats['errors'])) {
        // Update last sync timestamp to prevent reload loop
        update_option('vmpfence_blocked_ip_last_sync', current_time('mysql'));
        
        $removed_count = isset($stats['removed']) ? $stats['removed'] : 0;
        
        if ($removed_count > 0) {
            $message = sprintf(
                'Synced %d IPs from API (%d new, %d updated, %d removed)',
                $stats['total'],
                $stats['new'],
                $stats['updated'],
                $removed_count
            );
        } else {
            $message = sprintf(
                'Synced %d IPs from API (%d new, %d updated)',
                $stats['total'],
                $stats['new'],
                $stats['updated']
            );
        }
        
        wp_send_json_success(array(
            'message' => $message,
            'stats' => $stats,
            'imported' => $stats['new'] + $stats['updated']
        ));
    } else {
        $error_message = implode(', ', $stats['errors']);
        wp_send_json_error(array(
            'message' => 'Sync failed: ' . $error_message
        ));
    }
}
