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

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

/**
 * AJAX handler: Search blocked IPs
 */
add_action('wp_ajax_vmpfence_search_blocked_ips', 'vmpfence_ajax_search_blocked_ips');

function vmpfence_ajax_search_blocked_ips() {
    // Verify nonce
    check_ajax_referer('vmpfence_search_blocked_ips', 'nonce');
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => 'Permission denied'
        ));
        return; // Stop execution
    }
    
    // Get search parameters
    $search_term = isset($_POST['search_term']) ? sanitize_text_field($_POST['search_term']) : '';
    $active_only = isset($_POST['active_only']) ? (bool) $_POST['active_only'] : true;
    $source = isset($_POST['source']) && $_POST['source'] !== '' ? sanitize_text_field($_POST['source']) : null;
    $limit = isset($_POST['limit']) ? intval($_POST['limit']) : 100;
    
    // Validate search term
    if (empty($search_term) || strlen($search_term) < 2) {
        wp_send_json_error(array(
            'message' => 'Search term must be at least 2 characters'
        ));
        return; // Stop execution after error
    }
    
    // Perform search using model
    $results = VMPFence_Blocked_IP::search_blocked_ips($search_term, $active_only, $source, $limit);
    
    if (empty($results['results'])) {
        wp_send_json_success(array(
            'blocked_ips' => array(),
            'total_count' => 0,
            'showing_count' => 0,
            'message' => 'No blocked IPs found matching your search'
        ));
        return; // Stop execution after sending response
    }
    
    // Format results for display
    $formatted_ips = array();
    foreach ($results['results'] as $blocked) {
        // Format blocked_at date
        if (is_numeric($blocked['blocked_at'])) {
            $blocked_at_display = date('M j, Y H:i', $blocked['blocked_at']);
        } else {
            $timestamp = strtotime($blocked['blocked_at']);
            $blocked_at_display = $timestamp ? date('M j, Y H:i', $timestamp) : 'N/A';
        }
        
        // Determine block type
        $ip = $blocked['ip_address'];
        $block_type_label = 'IP Address';
        if (strlen($ip) == 2 && ctype_alpha($ip) && $ip === strtoupper($ip)) {
            $block_type_label = 'Country';
        } else if (strpos($ip, '*') !== false || strpos($ip, '?') !== false || strpos($ip, '[') !== false) {
            $block_type_label = 'Custom Pattern';
        }
        
        // Format expiry
        $is_permanent = ($blocked['blocked_until'] == 0);
        $is_expired = !$is_permanent && ($blocked['blocked_until'] < time());
        $is_active = (int)$blocked['is_active'] === 1;
        
        if (!$is_active) {
            $expires_display = 'Unblocked';
        } else if ($is_permanent) {
            $expires_display = 'Permanent';
        } else if ($is_expired) {
            $expires_display = 'Expired';
        } else {
            $expires_display = date('M j, Y H:i', $blocked['blocked_until']);
        }
        
        $formatted_ips[] = array(
            'ip_address' => $blocked['ip_address'],
            'block_type' => $block_type_label,
            'reason' => $blocked['reason'],
            'blocked_at' => $blocked_at_display,
            'expires' => $expires_display,
            'source' => strtoupper($blocked['source']),
            'is_active' => $is_active,
            'unblock_nonce' => wp_create_nonce('vmpfence_unblock_ip_' . $blocked['ip_address']),
            'delete_nonce' => wp_create_nonce('vmpfence_delete_ip_' . $blocked['ip_address'])
        );
    }
    
    wp_send_json_success(array(
        'blocked_ips' => $formatted_ips,
        'total_count' => $results['total_count'],
        'showing_count' => $results['showing_count'],
        'search_term' => $search_term
    ));
}
