<?php
/**
 * Blocked IPs Admin View
 *
 * @package VMPFence
 * @since 2.1.0
 * @since 2.2.0 - Added country blocking tab and custom pattern blocking
 * @since 2.2.2 - Improved UI design
 * @since 2.2.5 - Added Enhanced Audit Log integration for manual IP block action
 */

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

// Get license tier for restrictions (use centralized getter)
$license_tier = VMPFence_License::get_license_type();
$is_premium = ($license_tier === 'premium');

// Check for prefill_ip parameter (from Whois Lookup or Live Traffic)
$prefill_ip = isset($_GET['prefill_ip']) ? sanitize_text_field($_GET['prefill_ip']) : '';

// Validate source parameter against whitelist (security: prevent XSS and ensure valid sources)
$allowed_sources = array('whois', 'live-traffic', 'recent-traffic');
$prefill_source = isset($_GET['source']) ? sanitize_text_field($_GET['source']) : '';
$prefill_source = in_array($prefill_source, $allowed_sources, true) ? $prefill_source : '';

// Check if sync is needed (for display purposes only - actual sync happens via AJAX)
$last_sync = get_option('vmpfence_blocked_ip_last_sync');
$last_sync_time = !empty($last_sync) ? strtotime($last_sync) : 0;
$sync_needed = false;

// Sync if:
// 1. Never synced before OR
// 2. Last sync was more than 5 minutes ago
if (empty($last_sync) || $last_sync_time === 0) {
    $sync_needed = true;
} else {
    $minutes_since_sync = (time() - $last_sync_time) / 60;
    if ($minutes_since_sync > 5) {
        $sync_needed = true;
    }
}

// Enqueue toast notification system (must load FIRST for other scripts to use it)
wp_enqueue_style('vmpfence-toast-notifications', plugins_url('assets/css/toast-notifications.css', dirname(__FILE__)), array(), '1.0.3');
wp_enqueue_script('vmpfence-toast-notifications', plugins_url('assets/js/toast-notifications.js', dirname(__FILE__)), array('jquery'), '1.0.3', true);

// Enqueue Premium Upgrade Button Handler (required for "UPGRADE TO PREMIUM" buttons)
wp_enqueue_script('vmpfence-premium-upgrade', plugins_url('assets/js/premium-upgrade.js', dirname(__FILE__)), array('jquery'), VMPFENCE_VERSION, true);

// Enqueue Country Selector (for country blocking tab) - depends on toast notifications
wp_enqueue_style('vmpfence-country-selector', plugins_url('assets/css/country-selector.css', dirname(__FILE__)), array(), VMPFENCE_VERSION);
wp_enqueue_script('vmpfence-country-selector', plugins_url('assets/js/country-selector.js', dirname(__FILE__)), array('jquery', 'vmpfence-toast-notifications'), VMPFENCE_VERSION, true);

// Localize script to pass nonce to JavaScript
wp_localize_script('vmpfence-toast-notifications', 'vmpfence_blocked_ips_ajax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'sync_nonce' => wp_create_nonce('vmpfence_sync_blocked_ips'),
    'search_nonce' => wp_create_nonce('vmpfence_search_blocked_ips')
));

// Localize country selector script
wp_localize_script('vmpfence-country-selector', 'vmpfence_ajax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('vmpfence_nonce'),
    'plugin_url' => VMPFENCE_PLUGIN_URL
));

// Enqueue firewall.js for custom pattern handlers
wp_enqueue_script('vmpfence-firewall', plugins_url('assets/js/firewall.js', dirname(__FILE__)), array('jquery', 'vmpfence-toast-notifications'), VMPFENCE_VERSION, true);

// Localize firewall script for custom patterns
wp_localize_script('vmpfence-firewall', 'vmpfencePatternAjax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('vmpfence_nonce')
));

// Get statistics
$stats = VMPFence_Blocked_IP::get_stats();

// Get blocked IPs with filters
// Default to active only (true) unless explicitly set to 0 in URL
$filter_active = !isset($_GET['active_only']) || $_GET['active_only'] !== '0';
// Handle source filter: if not set or empty string, show all sources (null)
$filter_source = null; // Default to all sources
if (isset($_GET['source']) && $_GET['source'] !== '') {
    $filter_source = sanitize_text_field($_GET['source']);
}

// Check if Real-Time IP Blocklist is enabled
$realtime_blocklist_enabled = (bool) VMPFence_Config::get('realtime_ip_blocklist_enabled', 1);

// DEBUG: Log filter values for troubleshooting
// error_log('VMP Blocked IPs Filter - active_only param: ' . (isset($_GET['active_only']) ? $_GET['active_only'] : 'not set'));
// error_log('VMP Blocked IPs Filter - $filter_active: ' . ($filter_active ? 'true' : 'false'));
// error_log('VMP Blocked IPs Filter - $filter_source: ' . ($filter_source ? $filter_source : 'null'));

// Pagination setup
$per_page = 50;
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get total count for pagination
$total_blocked = VMPFence_Blocked_IP::get_blocked_count($filter_active, $filter_source);
$total_pages = ceil($total_blocked / $per_page);

// Get paginated results
$blocked_ips = VMPFence_Blocked_IP::get_blocked_ips($filter_active, $filter_source, $per_page, $offset);

// Handle manual IP block (if form submitted)
if (isset($_POST['vmpfence_block_ip_submit']) && check_admin_referer('vmpfence_block_ip_manual')) {
    $ip = trim(sanitize_text_field($_POST['ip_address']));
    $reason = sanitize_textarea_field($_POST['reason']);
    $duration = intval($_POST['duration']);
    
    $duration_minutes = 0; // Permanent by default
    if ($duration > 0) {
        $duration_minutes = $duration;
    }
    
    // Normalize IP for consistent checking (same logic as add_blocked_ip)
    $normalized_ip = $ip;
    $cidr_suffix = '';
    
    if (strpos($ip, '/') !== false) {
        // CIDR notation - extract base IP
        list($base_ip, $cidr) = explode('/', $ip, 2);
        $normalized_ip = $base_ip;
        $cidr_suffix = '/' . $cidr;
    }
    
    // Normalize IPv6 format (2001:0db8::1 -> 2001:db8::1)
    $ip_binary = @inet_pton($normalized_ip);
    if ($ip_binary !== false) {
        $compressed_ip = @inet_ntop($ip_binary);
        if ($compressed_ip !== false) {
            $normalized_ip = $compressed_ip . $cidr_suffix;
        } else {
            $normalized_ip = $ip; // Fallback to original
        }
    } else {
        $normalized_ip = $ip; // Fallback to original
    }
    
    // Check if IP already exists and is active (prevent duplicate blocking)
    $existing_block = VMPFence_Blocked_IP::get_blocked_ip_details($normalized_ip);
    
    if ($existing_block && $existing_block['is_active'] == 1) {
        // Check if block is expired
        $is_expired = ($existing_block['blocked_until'] > 0 && $existing_block['blocked_until'] <= time());
        
        if (!$is_expired) {
            // IP is already blocked and still active - prevent duplicate
            $manual_block_error = true;
            
            // Safely get source and reason with fallbacks
            $block_source = !empty($existing_block['source']) ? ucfirst($existing_block['source']) : 'Unknown';
            $block_reason = !empty($existing_block['reason']) ? esc_html($existing_block['reason']) : 'No reason provided';
            
            // Build message without sprintf to avoid issues with % characters in reason
            $manual_block_message = 'This IP is already blocked (Source: ' . $block_source . ', Reason: ' . $block_reason . '). To modify the block, please unblock it first and create a new block.';
            $result = false;
        } else {
            // Block expired, allow re-blocking
            $result = VMPFence_Blocked_IP::add_blocked_ip($ip, $reason, $duration_minutes, 'local');
        }
    } else {
        // IP not blocked or inactive - proceed with blocking
        $result = VMPFence_Blocked_IP::add_blocked_ip($ip, $reason, $duration_minutes, 'local');
    }
    
    if ($result) {
        // Refresh the list with pagination
        $total_blocked = VMPFence_Blocked_IP::get_blocked_count($filter_active, $filter_source);
        $total_pages = ceil($total_blocked / $per_page);
        $blocked_ips = VMPFence_Blocked_IP::get_blocked_ips($filter_active, $filter_source, $per_page, $offset);
        $stats = VMPFence_Blocked_IP::get_stats();
        
        // Fire audit log hook for manual IP block
        do_action('vmpfence_ip_blocked', $ip, $reason, 'manual');

        // Set success flag for toast notification
        $manual_block_success = true;
        $manual_block_message = 'IP address blocked successfully.';
    } else if (!isset($manual_block_error)) {
        // Only set generic error if duplicate check didn't already set specific error
        $manual_block_error = true;
        $manual_block_message = 'Failed to block IP address. Please check the IP format.';
    }
}
?>

<!-- Toast Notification Container -->
<?php require_once plugin_dir_path(__FILE__) . 'partials/toast-notification-container.php'; ?>

<!-- Blocked IPs Content (no wrap div - handled by parent) -->
<div style="margin-top: 20px; max-width: 1300px;">
    
    <!-- Blocking Options Card -->
    <div class="vmpfence-blocking-options-card">
        
            <div class="vmpfence-blocking-options-left" id="vmpfence-blocking-options-left" style="padding-right: 100px;"><a href="<?php echo esc_url(admin_url('admin.php?page=vmpfence-firewall&tab=blocking&view=blocking-options')); ?>" class="vmpfence-blocking-options-card-link">
                <svg viewBox="0 0 100.11 100.11" class="vmpfence-gear-icon" width="36" height="36" fill="#646970">
                    <title>options</title>
                    <path d="M99.59,41.42a2.06,2.06,0,0,0-1.37-.82L86.3,38.78a39.34,39.34,0,0,0-2.67-6.39q1.17-1.63,3.52-4.6t3.32-4.33A2.52,2.52,0,0,0,91,22a2.1,2.1,0,0,0-.46-1.43Q88.18,17.2,79.78,9.45a2.52,2.52,0,0,0-1.63-.65a2.12,2.12,0,0,0-1.57.59l-9.25,7a40.09,40.09,0,0,0-5.87-2.41L59.64,2a1.92,1.92,0,0,0-.75-1.4A2.46,2.46,0,0,0,57.29,0H42.82a2.19,2.19,0,0,0-2.34,1.82,106,106,0,0,0-1.89,12.12,37.62,37.62,0,0,0-5.93,2.48l-9-7A2.78,2.78,0,0,0,22,8.8q-1.44,0-6.16,4.66a64.88,64.88,0,0,0-6.42,7A2.75,2.75,0,0,0,8.8,22a2.44,2.44,0,0,0,.65,1.56q4.37,5.28,7,9a32.38,32.38,0,0,0-2.54,6L1.76,40.34a2,2,0,0,0-1.24.85A2.5,2.5,0,0,0,0,42.69V57.16a2.44,2.44,0,0,0,.52,1.53,2,2,0,0,0,1.37.82l11.93,1.76a31.91,31.91,0,0,0,2.67,6.45Q15.31,69.35,13,72.31T9.65,76.65a2.54,2.54,0,0,0-.07,3q2.54,3.52,10.75,11a2.25,2.25,0,0,0,1.63.71,2.35,2.35,0,0,0,1.63-.59l9.19-7a40.54,40.54,0,0,0,5.87,2.41l1.82,12a1.92,1.92,0,0,0,.75,1.4,2.45,2.45,0,0,0,1.6.55H57.29a2.2,2.2,0,0,0,2.35-1.82,107.41,107.41,0,0,0,1.89-12.12,37.19,37.19,0,0,0,5.93-2.48l9,7a3.18,3.18,0,0,0,1.69.59q1.43,0,6.13-4.62a65.86,65.86,0,0,0,6.45-7a2.16,2.16,0,0,0,.59-1.5a2.51,2.51,0,0,0-.65-1.63q-4.69-5.74-7-9a41.57,41.57,0,0,0,2.54-5.93l12.06-1.82a2,2,0,0,0,1.3-.85,2.52,2.52,0,0,0,.52-1.5V43a2.46,2.46,0,0,0-.52-1.53ZM61.85,61.86a16.08,16.08,0,0,1-11.8,4.89A16.69,16.69,0,0,1,33.37,50.06,16.69,16.69,0,0,1,50.06,33.37,16.69,16.69,0,0,1,66.74,50.06a16.08,16.08,0,0,1-4.89,11.8Zm0,0"></path>
                </svg>
                <div>
                    <h3 class="vmpfence-options-title">Blocking Options</h3>
                    <p class="vmpfence-options-desc">Manage global blocking options.</p>
                </div></a>
            </div>
        
        <?php if (!$is_premium): ?>
        <div class="vmpfence-blocking-options-right">
            <div class="vmpfence-upgrade-box">
                <p class="vmpfence-upgrade-text"><span style="font-size: 16px; font-weight: 600;">Upgrade to Premium</span></br>Enable country blocking by upgrading to Premium.</p>
                <div class="vmpfence-upgrade-buttons">
                    <button class="vmpfence-btn-upgrade">UPGRADE TO PREMIUM</button>
                    <button class="vmpfence-btn-learn-more">LEARN MORE</button>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Create a Blocking Rule -->
    <div class="vmpfence-blocking-rule-card">
        <h2 class="vmpfence-section-title">Create a Blocking Rule</h2>
        
        <!-- Block Type Tabs -->
        <div class="vmpfence-block-tabs" id="vmpfence-block-tabs">
            <div class="vmpfence-tab-label">Block Type</div>
            <button type="button" class="vmpfence-tab active" data-tab="ip-address">IP Address</button>
            <button type="button" class="vmpfence-tab" data-tab="country">Country</button>
            <button type="button" class="vmpfence-tab" data-tab="custom-pattern">Custom Pattern</button>
        </div>
        
        <!-- Tab Content: IP Address -->
        <div id="tab-ip-address" class="vmpfence-tab-content" style="display: block;">
            <form method="post" class="vmpfence-blocking-form">
                <?php wp_nonce_field('vmpfence_block_ip_manual'); ?>
                
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label for="ip_address" class="vmpfence-form-label">IP Address to Block</label>
                        <input type="text" id="ip_address" name="ip_address" class="vmpfence-form-input" 
                               placeholder="IPv4 (192.168.1.1) or IPv6 (2001:db8::1)" 
                               value="<?php echo esc_attr($prefill_ip); ?>" required>
                        <p class="description" style="margin-top: 8px; color: #646970; font-size: 13px;">
                            Supports both IPv4 and IPv6 addresses with optional CIDR notation (e.g., 192.168.1.0/24 or 2001:db8::/32)
                        </p>
                    </div>
                </div>
                
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label for="reason" class="vmpfence-form-label">Block Reason<span style="color: #dc3545;">*</span></label>
                        <textarea id="reason" name="reason" class="vmpfence-form-input" rows="3" 
                                  placeholder="Enter a reason" required></textarea>
                    </div>
                </div>
                
                <!-- Hidden Duration Field (keep functionality) -->
                <input type="hidden" name="duration" value="0">
                
                <div class="vmpfence-form-actions" style="margin-top: 24px;">
                    <button type="button" class="vmpfence-btn-secondary vmpfence-cancel-tab">
                        CANCEL
                    </button>
                    <button type="submit" name="vmpfence_block_ip_submit" class="vmpfence-btn-primary">
                        BLOCK THIS IP ADDRESS
                    </button>
                </div>
            </form>
        </div>
        
        <!-- Tab Content: Country Blocking -->
        <div id="tab-country" class="vmpfence-tab-content" style="display: none;">
            <?php if (!$is_premium): ?>
            <!-- Premium Required Banner -->
            <div class="vmpfence-info-banner" style="background: #fef3c7; border-color: #f59e0b;">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2">
                    <circle cx="12" cy="12" r="10"></circle>
                    <path d="M12 6v6l4 2"></path>
                </svg>
                <span><strong>Premium Feature:</strong> Country blocking is available in VMPFence Premium. <a href="#" class="vmpfence-upgrade-premium">Upgrade now</a></span>
            </div>
            <?php endif; ?>
            
            <form id="vmpfence-block-countries-form" class="vmpfence-blocking-form-country">
                
                <!-- What to Block Section -->
                <div class="vmpfence-blocking-row">
                    <div class="vmpfence-blocking-label">
                        What to Block
                    </div>
                    <div class="vmpfence-blocking-field">
                        <div class="vmpfence-checkbox-inline-group">
                            <label class="vmpfence-checkbox-inline">
                                <input type="checkbox" name="block_login" id="vmpfence-block-login" checked <?php echo !$is_premium ? 'disabled' : ''; ?>>
                                <span class="vmpfence-checkbox-box"></span>
                                <span class="vmpfence-checkbox-text">Login Form</span>
                            </label>
                            <label class="vmpfence-checkbox-inline">
                                <input type="checkbox" name="block_site" id="vmpfence-block-site" <?php echo !$is_premium ? 'disabled' : ''; ?>>
                                <span class="vmpfence-checkbox-box"></span>
                                <span class="vmpfence-checkbox-text">Block access to the rest of the site</span>
                            </label>
                        </div>
                        
                        <!-- Google Ads Warning -->
                        <div class="vmpfence-google-ads-warning">
                            <p><em>If you use Google Ads, blocking countries from accessing the entire site is not recommended. <a href="#" onclick="return false;">Learn More</a></em></p>
                        </div>
                    </div>
                </div>

                <!-- Countries to Block Section -->
                <div class="vmpfence-blocking-row">
                    <div class="vmpfence-blocking-label">
                        Countries to Block
                    </div>
                    <div class="vmpfence-blocking-field">
                        <!-- Selected Countries Tags Container -->
                        <div id="vmpfence-selected-countries" class="vmpfence-selected-countries"></div>
                        
                        <!-- Country Selector -->
                        <div id="vmpfence-country-selector" class="vmpfence-country-selector">
                            <input type="text" 
                                   id="vmpfence-country-search" 
                                   class="vmpfence-country-search" 
                                   placeholder="Search countries (e.g., 'Canada', 'CA')..."
                                   <?php echo !$is_premium ? 'disabled' : ''; ?>>
                            <div id="vmpfence-country-list" class="vmpfence-country-list">
                                <div id="vmpfence-country-options"></div>
                            </div>
                        </div>
                        
                        <!-- Hidden Input for Form Submission -->
                        <input type="hidden" id="vmpfence-countries-input" name="countries" value="">
                    </div>
                </div>
                
                <!-- Block Reason -->
                <div class="vmpfence-blocking-row">
                    <div class="vmpfence-blocking-label">
                        Reason (Optional)
                    </div>
                    <div class="vmpfence-blocking-field">
                        <textarea id="vmpfence-block-reason" 
                                  class="vmpfence-form-input" 
                                  rows="3" 
                                  placeholder="Enter an optional reason for blocking these countries..."
                                  <?php echo !$is_premium ? 'disabled' : ''; ?>></textarea>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="vmpfence-blocking-row">
                    <div class="vmpfence-blocking-label"></div>
                    <div class="vmpfence-blocking-field">
                        <div class="vmpfence-blocking-actions">
                            <button type="button" class="vmpfence-btn-cancel vmpfence-cancel-tab">CANCEL</button>
                            <button type="submit" class="vmpfence-btn-block-countries" <?php echo !$is_premium ? 'disabled' : ''; ?>>BLOCK SELECTED COUNTRIES</button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Tab Content: Custom Pattern (Multi-Field Form) -->
        <div id="tab-custom-pattern" class="vmpfence-tab-content" style="display: none;">
            <form id="vmpfence-custom-pattern-form" class="vmpfence-blocking-form">
                <p class="description" style="margin-bottom: 20px; font-size: 13px;">
                    Block traffic based on multiple pattern types. Fill in one or more fields below - all filled patterns will be blocked together.
                </p>
                
                <!-- IP Address Range -->
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label class="vmpfence-form-label">IP Address or Range</label>
                        <input type="text" id="pattern-ip-range" class="vmpfence-form-input pattern-field" 
                               placeholder="192.168.1.0/24 or 192.168.0.120-192.168.0.169">
                        <small class="vmpfence-form-help" style="display: block; margin-top: 5px; color: #646970;">
                            CIDR: 192.168.1.0/24 (entire subnet) or Range: 192.168.0.120-192.168.0.169 (specific IPs)
                        </small>
                    </div>
                </div>
                
                <!-- Hostname Pattern -->
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label class="vmpfence-form-label">Hostname Pattern</label>
                        <input type="text" id="pattern-hostname" class="vmpfence-form-input pattern-field" 
                               placeholder="*.amazonaws.com">
                        <small class="vmpfence-form-help" style="display: block; margin-top: 5px; color: #646970;">
                            Use * as wildcard. Example: *.amazonaws.com blocks all AWS hostnames
                        </small>
                    </div>
                </div>
                
                <!-- Browser User Agent -->
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label class="vmpfence-form-label">Browser User Agent Pattern</label>
                        <input type="text" id="pattern-user-agent" class="vmpfence-form-input pattern-field" 
                               placeholder="*badbot*">
                        <small class="vmpfence-form-help" style="display: block; margin-top: 5px; color: #646970;">
                            Use * as wildcard. Example: *badbot* blocks any user agent containing "badbot"
                        </small>
                    </div>
                </div>
                
                <!-- Referrer -->
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label class="vmpfence-form-label">Referrer Pattern</label>
                        <input type="text" id="pattern-referrer" class="vmpfence-form-input pattern-field" 
                               placeholder="*spam-site.com*">
                        <small class="vmpfence-form-help" style="display: block; margin-top: 5px; color: #646970;">
                            Use * as wildcard. Example: *spam-site.com* blocks traffic from spam-site.com
                        </small>
                    </div>
                </div>
                
                <!-- Reason (Required) -->
                <div class="vmpfence-form-grid">
                    <div class="vmpfence-form-field">
                        <label class="vmpfence-form-label">Reason for Blocking<span style="color: #dc3545;">*</span></label>
                        <textarea id="pattern-reason" class="vmpfence-form-input" rows="3" 
                                  placeholder="Why are you blocking these patterns?" required></textarea>
                        <small class="vmpfence-form-help" style="display: block; margin-top: 5px; color: #646970;">
                            This reason will apply to all patterns you enter above
                        </small>
                    </div>
                </div>
                
                <div class="vmpfence-form-actions" style="margin-top: 24px;">
                    <button type="button" class="vmpfence-btn-secondary vmpfence-cancel-tab">
                        CANCEL
                    </button>
                    <button type="submit" class="vmpfence-btn-primary">
                        BLOCK PATTERN
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Custom Patterns Table (separate from tab content, shown/hidden by JS) -->
    <div class="vmpfence-blocked-ips-table-card" id="vmpfence-custom-patterns-table-section" style="display: none;">
        <div class="vmpfence-table-header">
            <h2 class="vmpfence-section-title">Active Custom Patterns <span id="vmpfence-patterns-count" style="color: #646970; font-weight: 400; font-size: 14px;">(Loading...)</span></h2>
        </div>
        
        <!-- Table Controls -->
        <div class="vmpfence-table-controls">
            <div class="vmpfence-table-controls-left">
                <div class="vmpfence-search-box">
                    <input type="text" id="vmpfence-patterns-search" class="vmpfence-search-input" 
                           placeholder="🔍 Search by pattern, type, or reason...">
                </div>
            </div>
            
            <div class="vmpfence-table-controls-right">
                <label class="vmpfence-filter-checkbox">
                    <input type="checkbox" id="vmpfence-filter-active-patterns" checked>
                    <span>Active Only</span>
                </label>
                
                <div class="vmpfence-source-filters">
                    <button type="button" class="vmpfence-source-filter vmpfence-pattern-type-filter active" data-type="">All Types</button>
                    <button type="button" class="vmpfence-source-filter vmpfence-pattern-type-filter" data-type="hostname">Hostname</button>
                    <button type="button" class="vmpfence-source-filter vmpfence-pattern-type-filter" data-type="user_agent">User Agent</button>
                    <button type="button" class="vmpfence-source-filter vmpfence-pattern-type-filter" data-type="referrer">Referrer</button>
                    <button type="button" class="vmpfence-source-filter vmpfence-pattern-type-filter" data-type="ip_range">IP Range</button>
                </div>
            </div>
        </div>
        
        <table class="wp-list-table widefat fixed striped vmpfence-blocked-table" id="vmpfence-custom-patterns-table">
            <thead>
                <tr>
                    <th style="width: 140px;">Pattern Type</th>
                    <th style="min-width: 200px;">Pattern Value</th>
                    <th>Reason</th>
                    <th style="width: 140px;">Created At</th>
                    <th style="width: 80px; white-space: nowrap;">Matches</th>
                    <th style="width: 85px;">Status</th>
                    <th style="width: 110px;">Actions</th>
                </tr>
            </thead>
            <tbody id="vmpfence-patterns-tbody">
                <tr>
                    <td colspan="7" style="text-align: center; padding: 40px;">
                        <div class="vmpfence-spinner"></div>
                        <div style="margin-top: 10px; color: #646970;">Loading patterns...</div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Current Blocked IPs -->
    <div class="vmpfence-blocked-ips-table-card" id="vmpfence-ip-table-section">
        <div class="vmpfence-table-header">
            <h2 class="vmpfence-section-title"> Current Blocked IPs (Showing <?php echo count($blocked_ips); ?> of <?php echo number_format($total_blocked); ?>)</h2>
        </div>
        
        <!-- Table Controls -->
        <div class="vmpfence-table-controls">
            <div class="vmpfence-table-controls-left">
                <div class="vmpfence-search-box">
                    <input type="text" id="vmpfence-ip-search" class="vmpfence-search-input" 
                           placeholder=" Search by IP address or reason...">
                </div>
            </div>
            
            <div class="vmpfence-table-controls-right">
                <label class="vmpfence-filter-checkbox">
                    <input type="checkbox" id="vmpfence-filter-active" <?php checked($filter_active); ?>>
                    <span>Active</span>
                </label>
                
                <div class="vmpfence-source-filters">
                    <button type="button" class="vmpfence-source-filter <?php echo ($filter_source === null || $filter_source === '') ? 'active' : ''; ?>" 
                            data-source="">All Sources</button>
                    <button type="button" class="vmpfence-source-filter <?php echo $filter_source === 'local' ? 'active' : ''; ?>" 
                            data-source="local">Local</button>
                    <button type="button" class="vmpfence-source-filter <?php echo $filter_source === 'api' ? 'active' : ''; ?>" 
                            data-source="api">API</button>
                </div>
            </div>
        </div>
        
        <!-- Hidden data for toast notification on page load -->
        <div id="vmpfence-sync-data" style="display: none;" 
             data-blocklist-enabled="<?php echo $realtime_blocklist_enabled ? '1' : '0'; ?>"
             data-sync-needed="<?php echo $sync_needed ? '1' : '0'; ?>"
             data-last-sync-time="<?php echo $last_sync_time; ?>"
             data-last-sync-text="<?php echo $last_sync_time > 0 ? human_time_diff($last_sync_time, current_time('timestamp')) : ''; ?>">
        </div>
        
        <?php if (empty($blocked_ips)): ?>
        <div class="vmpfence-empty-state">
            <p>No blocked IPs found. Use the form above to block an IP manually, or sync from API.</p>
        </div>
        <?php else: ?>
        <table class="wp-list-table widefat fixed striped vmpfence-blocked-table">
            <thead>
                <tr>
                    <th style="min-width: 200px; max-width: 280px;">IP Address</th>
                    <th style="width: 120px;">Block Type</th>
                    <th>Reason</th>
                    <th style="width: 140px;">Blocked At</th>
                    <th style="width: 140px;">Expires</th>
                    <th style="width: 85px;">Source</th>
                    <!-- <th style="width: 80px;">Blocks</th> -->
                    <th style="width: 110px;">Actions</th>
                </tr>
            </thead>
            <tbody id="vmpfence-blocked-tbody">
                <?php foreach ($blocked_ips as $blocked): 
                    // blocked_until is Unix timestamp (INT): 0 = permanent, >0 = expiry timestamp
                    $is_permanent = ($blocked['blocked_until'] == 0);
                    $is_expired = !$is_permanent && ($blocked['blocked_until'] < time());
                    $is_active = (int)$blocked['is_active'] === 1;
                    $source_badge_color = $blocked['source'] === 'local' ? '#28A745' : ($blocked['source'] === 'api' ? '#F5A623' : '#191970');
                    
                    // Format blocked_at date properly
                    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';
                    }
                ?>
                <tr>
                    <td style="word-break: break-all; max-width: 280px;"><code style="font-weight: 600; color: #191970;"><?php echo esc_html($blocked['ip_address']); ?></code></td>
                    <td>
                        <?php
                        // Infer block type from IP format
                        $ip = $blocked['ip_address'];
                        $block_type_label = 'IP Address'; // Default
                        
                        // Check if it's a country code (2 letter uppercase)
                        if (strlen($ip) == 2 && ctype_alpha($ip) && $ip === strtoupper($ip)) {
                            $block_type_label = 'Country';
                        }
                        // Check if it's a custom pattern (contains wildcards or regex)
                        else if (strpos($ip, '*') !== false || strpos($ip, '?') !== false || strpos($ip, '[') !== false) {
                            $block_type_label = 'Custom Pattern';
                        }
                        // Otherwise it's an IP address (single IP or CIDR)
                        ?>
                        <span style="background: #F8F9FA; color: #191970; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600; font-family: 'Inter', sans-serif;">
                            <?php echo esc_html($block_type_label); ?>
                        </span>
                    </td>
                    <td style="color: #50575e;"><?php echo esc_html($blocked['reason']); ?></td>
                    <td style="color: #646970; font-size: 13px;"><?php echo esc_html($blocked_at_display); ?></td>
                    <td>
                        <?php if (!$is_active): ?>
                            <span style="color: #646970; font-weight: 500;">Unblocked</span>
                        <?php elseif ($is_permanent): ?>
                            <strong style="color: #191970; font-weight: 600;">Permanent</strong>
                        <?php elseif ($is_expired): ?>
                            <span style="color: #F5A623; font-weight: 500;">Expired</span>
                        <?php else: ?>
                            <span style="color: #191970; font-size: 13px;"><?php echo esc_html(date('M j, Y H:i', $blocked['blocked_until'])); ?></span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <span style="background: <?php echo $source_badge_color; ?>; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; font-family: 'Inter', sans-serif;">
                            <?php echo strtoupper(esc_html($blocked['source'])); ?>
                        </span>
                    </td>
                    <!-- <td style="text-align: center; font-weight: 600; color: #191970;"><?php echo intval($blocked['block_count']); ?></td> -->
                    <td>
                        <?php if ($is_active && !$is_expired): ?>
                            <button type="button" class="button button-small vmpfence-unblock-ip" 
                                    data-ip="<?php echo esc_attr($blocked['ip_address']); ?>"
                                    data-nonce="<?php echo wp_create_nonce('vmpfence_unblock_ip_' . $blocked['ip_address']); ?>"
                                    style="background: #191970; color: white; border: none; border-radius: 8px; padding: 6px 12px; font-weight: 600; font-size: 12px; font-family: 'Inter', sans-serif;">
                                Unblock
                            </button>
                        <?php else: ?>
                            <button type="button" class="button button-small button-link-delete vmpfence-delete-ip" 
                                    data-ip="<?php echo esc_attr($blocked['ip_address']); ?>"
                                    data-nonce="<?php echo wp_create_nonce('vmpfence_delete_ip_' . $blocked['ip_address']); ?>"
                                    style="background: #dc3545; color: white; border: none; border-radius: 8px; padding: 6px 12px; font-weight: 600; font-size: 12px; font-family: 'Inter', sans-serif;">
                                Delete
                            </button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="tablenav bottom" style="margin: 20px 0; padding: 16px 20px;">
            <div class="tablenav-pages">
                <span class="displaying-num">
                    <?php printf('%s items', number_format_i18n($total_blocked)); ?>
                </span>
                <?php
                $current_url = remove_query_arg('paged');
                $pagination_args = array(
                    'base' => add_query_arg('paged', '%#%', $current_url),
                    'format' => '',
                    'prev_text' => '&laquo; Previous',
                    'next_text' => 'Next &raquo;',
                    'total' => $total_pages,
                    'current' => $current_page
                );
                echo paginate_links($pagination_args);
                ?>
            </div>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
    
    <!-- Blocked Countries Table (Phase 5) -->
    <div class="vmpfence-blocked-countries-section" id="vmpfence-country-table-section" style="display: none;">
        <div class="vmpfence-countries-header">
            <h2 class="vmpfence-countries-title">Current Blocked Countries <span id="vmpfence-countries-count" class="vmpfence-count-badge">(Loading...)</span></h2>
            
            <div class="vmpfence-countries-controls">
                <div class="vmpfence-countries-search-wrapper">
                    <input type="text" 
                           id="vmpfence-countries-search" 
                           class="vmpfence-countries-search" 
                           placeholder="Search by country or reason...">
                </div>
                
                <div class="vmpfence-countries-filters">
                    <button class="vmpfence-filter-btn vmpfence-filter-active" data-filter="all">
                        <span class="vmpfence-filter-check">✓</span> All Types
                    </button>
                    <button class="vmpfence-filter-btn" data-filter="login">
                        Login Only
                    </button>
                    <button class="vmpfence-filter-btn" data-filter="site">
                        Full Site
                    </button>
                </div>
            </div>
        </div>
        
        <table class="vmpfence-blocked-countries-table">
            <thead>
                <tr>
                    <th style="width: 60px;">FLAG</th>
                    <th style="width: 150px;">COUNTRY</th>
                    <th style="width: 120px;">BLOCK TYPE</th>
                    <th style="min-width: 200px;">REASON</th>
                    <th style="width: 140px;">BLOCKED AT</th>
                    <th style="width: 120px;">EXPIRES</th>
                    <th style="width: 100px;">SOURCE</th>
                    <th style="width: 120px;">ACTIONS</th>
                </tr>
            </thead>
            <tbody id="vmpfence-blocked-countries-body">
                <tr>
                    <td colspan="8" style="text-align:center;padding:40px;">
                        <div class="vmpfence-spinner"></div>
                        <div>Loading...</div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');

/* Apply Inter font globally to this page */
.vmpfence-admin-wrap,
.vmpfence-admin-wrap * {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

/* Blocking Options Card */
.vmpfence-blocking-options-card {
    background: #fff;
    border: 1px solid rgba(0,0,0,0.1);
    /* border-radius: 12px; */
    /* padding: 20px 24px; */
    margin: 20px 0;
    max-width: 1300px;
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 32px;
    align-items: center;
    transition: all 0.2s ease;
}

/* .vmpfence-blocking-options-card:hover {
    border-color: #191970;
    box-shadow: 0 4px 12px rgba(25, 25, 112, 0.1);
} */

.vmpfence-blocking-options-card-link {
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 16px;
    /* border: 1px solid rgba(0,0,0,0.1); */
    padding: 20px 24px;
    transition: all 0.2s ease;
}

.vmpfence-blocking-options-card-link:hover {
    opacity: 0.9;
}

.vmpfence-blocking-options-card-link:hover .vmpfence-gear-icon {
    fill: #191970;
    transition: fill 0.2s ease;
}

.vmpfence-gear-icon {
    flex-shrink: 0;
}

.vmpfence-options-title {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #191970;
    font-family: 'Inter', sans-serif;
}

.vmpfence-options-desc {
    margin: 4px 0 0 0;
    font-size: 14px;
    color: #646970;
    font-family: 'Inter', sans-serif;
}

.vmpfence-blocking-options-right {
    display: flex;
    /* flex-direction: row; */
    gap: 12px;
    align-items: flex-start;
    border-left: 1px solid rgba(0,0,0,0.1);
    padding: 20px 24px;
    
}

.vmpfence-upgrade-box {
    background: #FFF;
    /* border: 1px solid #F5A623; */
    border-radius: 8px;
    /* padding: 12px 16px; */
    display: flex;
    align-items: center;
    flex-direction: row;
    gap: 260px;
}

.vmpfence-upgrade-text {
    margin: 0;
    font-size: 14px !important;
    color: #000 !important;
    font-family: 'Inter', sans-serif;
    max-width: 200px;
}

.vmpfence-upgrade-title {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #191970;
    font-family: 'Inter', sans-serif;
}

.vmpfence-upgrade-text {
    margin: 0;
    font-size: 12px;
    color: #000;
    font-size: 14px !important;
    font-family: 'Inter', sans-serif;
}

.vmpfence-upgrade-buttons {
    display: flex;
    gap: 8px;
}

.vmpfence-btn-upgrade {
    background: linear-gradient(135deg, #2A2669 0%, #20409A 100%);
    color: #FFFFFF;
    border: none;
    border-radius: 6px;
    padding: 8px 16px;
    font-size: 13px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    cursor: pointer;
    transition: all 0.2s;
    white-space: nowrap;
}

.vmpfence-btn-upgrade:hover {
    background: linear-gradient(135deg, #1f1d52 0%, #193679 100%);
    transform: translateY(-1px);
}

.vmpfence-btn-learn-more {
    background: #FFFFFF;
    color: #007AFF;
    border: 1px solid #007AFF;
    border-radius: 6px;
    padding: 8px 16px;
    font-size: 13px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    cursor: not-allowed;
    transition: all 0.2s;
    white-space: nowrap;
    pointer-events: auto;
    opacity: 0.6;
}

.vmpfence-btn-learn-more:hover {
    /* Disabled - no hover effect */
}

/* Blocking Rule Card */
.vmpfence-blocking-rule-card {
    background: #FFFFFF;
    border: 1px solid rgba(0,0,0,0.1);
    /* border-radius: 12px; */
    padding: 24px;
    margin: 20px 0;
    max-width: 1300px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.vmpfence-section-title {
    margin: 0 0 24px 0;
    font-size: 18px;
    font-weight: 700;
    font-family: 'Inter', sans-serif;
    color: #191970;
    padding-bottom: 16px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
}

/* Block Type Tabs */
.vmpfence-block-tabs {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    margin-bottom: 24px;
    flex-wrap: wrap;
}

.vmpfence-tab-label {
    font-weight: 600;
    font-size: 14px;
    color: #191970;
    font-family: 'Inter', sans-serif;
    margin-right: 8px;
}

.vmpfence-tab {
    background: #FFFFFF;
    color: #191970;
    border: 1px solid #191970;
    border-radius: 6px;
    padding: 10px 20px;
    font-size: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
}

.vmpfence-tab:hover {
    background: #f0f7ff;
}

.vmpfence-tab.active {
    background: #191970;
    color: #FFFFFF;
    border-bottom: 2px solid #191970;
}

.vmpfence-tab-content {
    padding-top: 16px;
}

/* Form Styling */
.vmpfence-blocking-form {
    /* max-width: 100%; */
    max-width: 600px;
    margin: 0 auto;
}

.vmpfence-form-grid {
    margin-bottom: 20px;
}

.vmpfence-form-field {
    display: flex;
    flex-direction: column;
}

.vmpfence-form-label {
    font-weight: 600;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    color: #191970;
    margin-bottom: 8px;
}

.vmpfence-form-input {
    width: 100%;
    height: 48px;
    padding: 0 16px;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    line-height: 1.4;
    border: 1px solid rgba(0,0,0,0.1);
    border-radius: 12px;
    box-shadow: none;
    transition: all 0.2s ease;
}

.vmpfence-form-input:focus {
    border-color: #191970;
    box-shadow: 0 0 0 3px rgba(25,25,112,0.1);
    outline: none;
}

.vmpfence-form-input[type="text"],
.vmpfence-form-input[type="email"],
select.vmpfence-form-input {
    height: 48px;
}

textarea.vmpfence-form-input {
    height: auto;
    min-height: 96px;
    padding: 12px 16px;
}

.vmpfence-form-description {
    margin: 6px 0 0 0;
    font-size: 12px;
    color: #646970;
    font-style: italic;
}

.vmpfence-placeholder-notice {
    margin: 16px 0 12px 0;
    padding: 12px 16px;
    background: #f0f7ff;
    border-left: 3px solid #191970;
    border-radius: 4px;
}

.vmpfence-form-actions {
    margin-top: 24px;
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.vmpfence-btn-primary {
    background: linear-gradient(135deg, #2A2669 0%, #20409A 100%);
    color: #FFFFFF;
    border: none;
    border-radius: 12px;
    padding: 12px 24px;
    height: 48px;
    font-size: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.vmpfence-btn-primary:hover {
    background: linear-gradient(135deg, #1f1d52 0%, #193679 100%);
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    transform: translateY(-2px);
}

.vmpfence-btn-secondary {
    background: #FFFFFF;
    color: #646970;
    border: 1px solid rgba(0,0,0,0.2);
    border-radius: 12px;
    padding: 12px 24px;
    height: 48px;
    font-size: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    cursor: pointer;
    transition: all 0.2s ease;
}

.vmpfence-btn-secondary:hover {
    background: #F8F9FA;
    border-color: #191970;
}

/* Coming Soon Section */
.vmpfence-coming-soon {
    padding: 24px;
    text-align: center;
}

.vmpfence-country-map {
    margin: 24px 0;
}

/* Blocked IPs Table Card */
.vmpfence-blocked-ips-table-card {
    background: #FFFFFF;
    border: 1px solid rgba(0,0,0,0.1);
    /* border-radius: 12px; */
    margin: 20px 0;
    max-width: 1300px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.vmpfence-table-header {
    padding: 20px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
}

/* Table Controls */
.vmpfence-table-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: #F8F9FA;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    flex-wrap: wrap;
    gap: 12px;
}

.vmpfence-table-controls-left,
.vmpfence-table-controls-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

/* Search Box */
.vmpfence-search-box {
    position: relative;
}

.vmpfence-search-input {
    width: 300px;
    height: 48px;
    padding: 0 16px;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    border: 1px solid rgba(0,0,0,0.1);
    border-radius: 12px;
    transition: all 0.2s ease;
}

.vmpfence-search-input:focus {
    border-color: #191970;
    outline: none;
    box-shadow: 0 0 0 3px rgba(25,25,112,0.1);
}

/* Filter Checkbox */
.vmpfence-filter-checkbox {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    height: 48px;
    background: #FFFFFF;
    border: 1px solid #191970;
    border-radius: 12px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    color: #191970;
    transition: all 0.2s;
}

.vmpfence-filter-checkbox:has(input:checked) {
    background: #191970;
    color: #FFFFFF;
}

.vmpfence-filter-checkbox input {
    margin: 0;
    cursor: pointer;
}

/* Source Filters */
.vmpfence-source-filters {
    display: flex;
    gap: 8px;
}

.vmpfence-source-filter {
    padding: 12px 16px;
    height: 48px;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    background: #FFFFFF;
    border: 1px solid rgba(0,0,0,0.1);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    font-weight: 600;
    color: #191970;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.vmpfence-source-filter:hover {
    background: #F8F9FA;
    border-color: #191970;
}

.vmpfence-source-filter.active {
    background: #191970;
    color: #FFFFFF;
    border-color: #191970;
}

.vmpfence-source-filter.active[data-source="local"] {
    background: #28A745;
    border-color: #28A745;
}

.vmpfence-source-filter.active[data-source="api"] {
    background: #F5A623;
    border-color: #F5A623;
}

/* Sync Button */
.vmpfence-btn-sync {
    padding: 12px 16px;
    height: 48px;
    font-size: 14px;
    font-weight: 600;
    font-family: 'Inter', sans-serif;
    background: #FFFFFF;
    border: 1px solid #191970;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    color: #191970;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.vmpfence-btn-sync:hover {
    background: #191970;
    color: #FFFFFF;
    border-color: #191970;
}

.vmpfence-sync-status {
    padding: 12px 20px;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    display: none;
}

.vmpfence-sync-status:not(:empty) {
    display: block;
}

/* Empty State */
.vmpfence-empty-state {
    padding: 60px 20px;
    text-align: center;
    color: rgba(25,25,112,0.6);
    font-size: 14px;
    font-family: 'Inter', sans-serif;
}

/* Table Styling */
.vmpfence-blocked-table {
    margin: 0 !important;
    border: none !important;
    border-radius: 0 !important;
}

.vmpfence-blocked-table thead th {
    background: #F8F9FA;
    font-weight: 700;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    color: #191970;
    border-bottom: 1px solid rgba(0,0,0,0.1);
    padding: 12px 16px;
}

.vmpfence-blocked-table tbody tr {
    transition: background-color 0.2s;
}

.vmpfence-blocked-table tbody tr:hover {
    background-color: #F8F9FA;
}

.vmpfence-blocked-table tbody td {
    padding: 12px 16px;
    font-size: 14px;
    font-family: 'Inter', sans-serif;
    vertical-align: middle;
    white-space: nowrap;
}

/* Reason column - allow wrapping and set max width */
.vmpfence-blocked-table tbody td:nth-child(3),
.vmpfence-blocked-table thead th:nth-child(3) {
    white-space: normal;
    word-wrap: break-word;
    word-break: break-word;
    max-width: 300px;
    overflow-wrap: break-word;
}

.vmpfence-blocked-table tbody td:first-child,
.vmpfence-blocked-table thead th:first-child {
    white-space: nowrap;
    min-width: 150px;
}

/* Responsive */
@media (max-width: 1200px) {
    .vmpfence-blocking-options-card {
        grid-template-columns: 1fr;
        gap: 20px;
    }
    
    .vmpfence-blocking-options-right {
        padding-top: 16px;
        border-top: 1px solid rgba(0,0,0,0.1);
    }
    
    .vmpfence-form-row {
        flex-direction: column;
    }
    
    .vmpfence-table-controls {
        flex-direction: column;
        align-items: stretch;
    }
    
    .vmpfence-table-controls-left,
    .vmpfence-table-controls-right {
        width: 100%;
        justify-content: space-between;
    }
    
    .vmpfence-search-input {
        width: 100%;
    }
}

@media (max-width: 782px) {
    .vmpfence-source-filters {
        flex-wrap: wrap;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // Get current page parameter
    var currentPage = '<?php echo esc_js($_GET['page'] ?? ''); ?>';
    var currentTab = '<?php echo esc_js($_GET['tab'] ?? ''); ?>';
    
    // Show toast notification on page load based on sync status
    var $syncData = $('#vmpfence-sync-data');
    var blocklistEnabled = $syncData.data('blocklist-enabled') === 1;
    var syncNeeded = $syncData.data('sync-needed') === 1;
    var lastSyncTime = $syncData.data('last-sync-time');
    var lastSyncText = $syncData.data('last-sync-text');
    
    // Show appropriate toast based on state
    if (!blocklistEnabled) {
        // Warning: Real-Time IP Blocklist is disabled
        VMPFenceNotifications.showWarning(
            'Real-Time IP Blocklist: Disabled - Auto-sync from API is turned off. Enable it in Firewall Options.',
            8000
        );
    } else if (syncNeeded) {
        // Info: Sync in progress
        VMPFenceNotifications.showInfo(
            'Auto-Sync Enabled: Syncing API data... Local blocks shown below. Page will update automatically.',
            6000
        );
    } else if (lastSyncTime > 0) {
        // Info: Last synced X time ago
        VMPFenceNotifications.showInfo(
            'Auto-Sync Enabled: Last synced ' + lastSyncText + ' ago.',
            5000
        );
    } else {
        // Info: Never synced
        VMPFenceNotifications.showInfo(
            'Auto-Sync Enabled: Never synced. Initial sync in progress...',
            6000
        );
    }
    
    // Show manual block result toast if action was performed (with slight delay to stack properly)
    <?php if (isset($manual_block_success) && $manual_block_success): ?>
    setTimeout(function() {
        VMPFenceNotifications.showSuccess(
            '<?php echo esc_js($manual_block_message); ?>',
            4000
        );
    }, 100);
    <?php endif; ?>
    
    <?php if (isset($manual_block_error) && $manual_block_error): ?>
    setTimeout(function() {
        VMPFenceNotifications.showError(
            '<?php echo esc_js($manual_block_message); ?>',
            5000
        );
    }, 100);
    <?php endif; ?>
    
    // Background API sync (non-blocking)
    <?php if ($sync_needed): ?>
    (function() {
        // Start background sync immediately
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_sync_blocked_ips',
                nonce: vmpfence_blocked_ips_ajax.sync_nonce
            },
            success: function(response) {
                if (response.success) {
                    // Show success toast
                    VMPFenceNotifications.showSuccess(
                        'Sync Complete: ' + response.data.imported + ' blocked IPs synced from API.',
                        3000
                    );
                    
                    // Reload page after 1 second to show updated data
                    setTimeout(function() {
                        // Preserve current filters
                        var currentUrl = window.location.href;
                        window.location.href = currentUrl.split('#')[0];
                    }, 1000);
                } else {
                    // Show warning toast
                    VMPFenceNotifications.showWarning(
                        'Sync Warning: ' + (response.data || 'Unable to sync from API'),
                        5000
                    );
                }
            },
            error: function() {
                // Show error toast
                VMPFenceNotifications.showError(
                    'Sync Failed: Unable to connect to API server.',
                    6000
                );
            }
        });
    })();
    <?php endif; ?>
    
    // Tab Switching Functionality
    $('.vmpfence-tab').on('click', function() {
        var targetTab = $(this).data('tab');
        var $targetContent = $('#tab-' + targetTab);
        
        // If clicking the active tab, toggle content visibility
        if ($(this).hasClass('active') && $targetContent.is(':visible')) {
            $('.vmpfence-tab').removeClass('active');
            $targetContent.slideUp(300);
        } else {
            // Update active states
            $('.vmpfence-tab').removeClass('active');
            $(this).addClass('active');
            
            // Show/hide tab content with animation
            $('.vmpfence-tab-content').slideUp(300);
            $targetContent.slideDown(300);
        }
    });
    
    // Cancel button functionality
    $('.vmpfence-cancel-tab').on('click', function() {
        $('.vmpfence-block-tabs .vmpfence-tab').removeClass('active');
        $(this).closest('.vmpfence-tab-content').slideUp(300);
    });
    
    // Search functionality with AJAX (searches entire database)
    var searchTimeout;
    var lastSearchTerm = '';
    var isSearching = false;
    var originalHeaderText = $('.vmpfence-section-title').html(); // Store original header
    
    $('#vmpfence-ip-search').on('keyup', function() {
        var searchTerm = $(this).val().trim();
        
        // Clear previous timeout
        clearTimeout(searchTimeout);
        
        // If search is empty, reload page to show normal pagination
        if (searchTerm === '') {
            if (lastSearchTerm !== '') {
                // Restore original state
                $('.vmpfence-section-title').html(originalHeaderText);
                $('.tablenav').show();
                // Only reload if we were previously searching
                location.reload();
            }
            return;
        }
        
        // Don't search if less than 2 characters
        if (searchTerm.length < 2) {
            return;
        }
        
        // Debounce: wait 500ms after user stops typing
        searchTimeout = setTimeout(function() {
            if (searchTerm === lastSearchTerm) {
                return; // Don't search if term hasn't changed
            }
            
            lastSearchTerm = searchTerm;
            performSearch(searchTerm);
        }, 500);
    });
    
    function performSearch(searchTerm) {
        if (isSearching) return;
        
        isSearching = true;
        
        // Show loading state
        var $tbody = $('#vmpfence-blocked-tbody');
        var $tableCard = $('.vmpfence-blocked-ips-table-card');
        $tableCard.css('opacity', '0.6');
        
        // Get current filters
        var activeOnly = <?php echo $filter_active ? 'true' : 'false'; ?>;
        var currentSource = '<?php echo $filter_source ? $filter_source : ''; ?>';
        
        $.ajax({
            url: vmpfence_blocked_ips_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_search_blocked_ips',
                nonce: vmpfence_blocked_ips_ajax.search_nonce,
                search_term: searchTerm,
                active_only: activeOnly,
                source: currentSource,
                limit: 100
            },
            success: function(response) {
                isSearching = false;
                $tableCard.css('opacity', '1');
                
                if (response.success) {
                    var data = response.data;
                    
                    // Update header count
                    $('.vmpfence-section-title').html(' Current Blocked IPs (Showing ' + data.showing_count + ' of ' + data.total_count + ' matches)');
                    
                    // Clear and rebuild table
                    $tbody.empty();
                    
                    if (data.blocked_ips.length === 0) {
                        var safeSearchTerm = $('<div>').text(searchTerm).html();
                        $tbody.append('<tr><td colspan="7" style="text-align: center; padding: 40px;">No results found for \"' + safeSearchTerm + '\"</td></tr>');
                    } else {
                        $.each(data.blocked_ips, function(index, ip) {
                            var sourceBadgeColor = ip.source === 'LOCAL' ? '#28A745' : (ip.source === 'API' ? '#F5A623' : '#191970');
                            
                            // Escape IP for safe use in HTML attributes
                            var safeIpForAttr = $('<div>').text(ip.ip_address).html();
                            
                            // Use nonces from server response (properly generated with IP included in action)
                            var unblockNonce = ip.unblock_nonce;
                            var deleteNonce = ip.delete_nonce;
                            
                            var unblockBtn = (ip.is_active && ip.expires !== 'Expired') ? 
                                '<button type=\"button\" class=\"button button-small vmpfence-unblock-ip\" data-ip=\"' + safeIpForAttr + '\" data-nonce=\"' + unblockNonce + '\" style=\"background: #191970; color: white; border: none; border-radius: 8px; padding: 6px 12px; font-weight: 600; font-size: 12px;\">Unblock</button>' :
                                '<button type=\"button\" class=\"button button-small button-link-delete vmpfence-delete-ip\" data-ip=\"' + safeIpForAttr + '\" data-nonce=\"' + deleteNonce + '\" style=\"background: #dc3545; color: white; border: none; border-radius: 8px; padding: 6px 12px; font-weight: 600; font-size: 12px;\">Delete</button>';
                            
                            var row = '<tr>' +
                                '<td><code style=\"font-weight: 600; color: #191970;\">' + $('<div>').text(ip.ip_address).html() + '</code></td>' +
                                '<td><span style=\"background: #F8F9FA; color: #191970; padding: 4px 10px; border-radius: 8px; font-size: 11px; font-weight: 600;\">' + $('<div>').text(ip.block_type).html() + '</span></td>' +
                                '<td style=\"color: #50575e; word-wrap: break-word; word-break: break-word; max-width: 300px;\">' + $('<div>').text(ip.reason).html() + '</td>' +
                                '<td style=\"color: #646970; font-size: 13px;\">' + $('<div>').text(ip.blocked_at).html() + '</td>' +
                                '<td><strong style=\"color: #191970;\">' + $('<div>').text(ip.expires).html() + '</strong></td>' +
                                '<td><span style=\"background: ' + sourceBadgeColor + '; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600;\">' + $('<div>').text(ip.source).html() + '</span></td>' +
                                // '<td style=\"text-align: center; font-weight: 600; color: #191970;\">' + parseInt(ip.block_count) + '</td>' +
                                '<td>' + unblockBtn + '</td>' +
                                '</tr>';
                            
                            $tbody.append(row);
                        });
                        
                        // Re-bind click handlers for new buttons
                        bindActionButtons();
                    }
                    
                    // Hide pagination during search
                    $('.tablenav').hide();
                    
                } else {
                    VMPFenceNotifications.showError('Search failed: ' + (response.data ? response.data.message : 'Unknown error'));
                }
            },
            error: function() {
                isSearching = false;
                $tableCard.css('opacity', '1');
                VMPFenceNotifications.showError('Search failed. Please try again.');
            }
        });
    }
    
    // Function to bind action button handlers (for dynamically loaded content)
    function bindActionButtons() {
        // Unblock IP
        $('.vmpfence-unblock-ip').off('click').on('click', function() {
            var $button = $(this);
            var ip = $button.data('ip');
            var nonce = $button.data('nonce');
            
            // Escape IP for safe display
            var safeIp = $('<div>').text(ip).html();
            
            VMPFenceNotifications.showConfirmModal({
                title: 'Unblock IP Address',
                message: 'Are you sure you want to unblock ' + safeIp + '?',
                confirmText: 'Yes, Unblock',
                cancelText: 'Cancel'
            }).then(function(confirmed) {
                if (!confirmed) return;
                
                $button.prop('disabled', true).text('Unblocking...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_unblock_ip',
                        ip: ip,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            VMPFenceNotifications.showSuccess('IP address unblocked successfully');
                            $button.closest('tr').fadeOut(function() {
                                $(this).remove();
                            });
                        } else {
                            VMPFenceNotifications.showError('Failed to unblock IP: ' + response.data);
                            $button.prop('disabled', false).text('Unblock');
                        }
                    },
                    error: function() {
                        VMPFenceNotifications.showError('Failed to unblock IP');
                        $button.prop('disabled', false).text('Unblock');
                    }
                });
            });
        });
        
        // Delete IP record
        $('.vmpfence-delete-ip').off('click').on('click', function() {
            var $button = $(this);
            var ip = $button.data('ip');
            var nonce = $button.data('nonce');
            
            // Escape IP for safe display
            var safeIp = $('<div>').text(ip).html();
            
            VMPFenceNotifications.showConfirmModal({
                title: 'Delete IP Record',
                message: 'Permanently delete ' + safeIp + ' from database?\\n\\nThis cannot be undone.',
                confirmText: 'Yes, Delete',
                cancelText: 'Cancel'
            }).then(function(confirmed) {
                if (!confirmed) return;
                
                $button.prop('disabled', true).text('Deleting...');
                
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'vmpfence_delete_ip',
                        ip: ip,
                        nonce: nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            VMPFenceNotifications.showSuccess('IP record deleted successfully');
                            $button.closest('tr').fadeOut(function() {
                                $(this).remove();
                            });
                        } else {
                            VMPFenceNotifications.showError('Failed to delete IP: ' + response.data);
                            $button.prop('disabled', false).text('Delete Record');
                        }
                    },
                    error: function() {
                        VMPFenceNotifications.showError('Failed to delete IP');
                        $button.prop('disabled', false).text('Delete Record');
                    }
                });
            });
        });
    }
    
    // Initial binding for page-loaded buttons
    bindActionButtons();
    
    // Active Only checkbox filter
    $('#vmpfence-filter-active').on('change', function() {
        // If search is active, prevent filter change
        if (lastSearchTerm !== '') {
            VMPFenceNotifications.showWarning('Please clear search before changing filters');
            $(this).prop('checked', !$(this).prop('checked')); // Revert checkbox
            return;
        }
        
        var isActive = $(this).is(':checked');
        var currentSource = new URLSearchParams(window.location.search).get('source') || '';
        
        var url = 'admin.php?page=' + currentPage;
        if (currentTab) {
            url += '&tab=' + currentTab;
        }
        // Always include active_only parameter - 1 for checked, 0 for unchecked
        url += '&active_only=' + (isActive ? '1' : '0');
        if (currentSource) {
            url += '&source=' + currentSource;
        }
        
        window.location.href = url;
    });
    
    // Source filter buttons (only target buttons with data-source attribute)
    $('.vmpfence-source-filter[data-source]').on('click', function() {
        // If search is active, prevent filter change
        if (lastSearchTerm !== '') {
            VMPFenceNotifications.showWarning('Please clear search before changing filters');
            return;
        }
        var source = $(this).data('source');
        var isActive = <?php echo $filter_active ? 'true' : 'false'; ?>;
        
        var url = 'admin.php?page=' + currentPage;
        if (currentTab) {
            url += '&tab=' + currentTab;
        }
        // Always include active_only parameter
        url += '&active_only=' + (isActive ? '1' : '0');
        // Only add source parameter if it's not empty (empty = all sources)
        if (source && source !== '') {
            url += '&source=' + source;
        }
        
        window.location.href = url;
    });
    
    // Auto-open IP Address tab if prefill_ip parameter is present
    <?php if (!empty($prefill_ip)): ?>
    // Auto-open IP Address tab
    setTimeout(function() {
        var $ipTab = $('.vmpfence-block-tabs .vmpfence-tab[data-tab="ip-address"]');
        if ($ipTab.length > 0 && !$ipTab.hasClass('active')) {
            $ipTab.trigger('click');
            
            // Show info notification based on source
            <?php if ($prefill_source === 'live-traffic'): ?>
            VMPFenceNotifications.showInfo(
                'IP address from Live Traffic has been pre-filled. Please enter a block reason and submit.',
                5000
            );
            <?php elseif ($prefill_source === 'recent-traffic'): ?>
            VMPFenceNotifications.showInfo(
                'IP address from Recent Traffic has been pre-filled. Please enter a block reason and submit.',
                5000
            );
            <?php elseif ($prefill_source === 'whois'): ?>
            VMPFenceNotifications.showInfo(
                'IP address from WHOIS lookup has been pre-filled. Please enter a block reason and submit.',
                5000
            );
            <?php else: ?>
            VMPFenceNotifications.showInfo(
                'IP address has been pre-filled. Please enter a block reason and submit.',
                5000
            );
            <?php endif; ?>
            
            // Focus on reason field after tab opens
            setTimeout(function() {
                $('#reason').focus();
            }, 300);
        }
    }, 200);
    <?php endif; ?>
    
    // ====================================
    // CUSTOM PATTERN MULTI-FIELD FORM HANDLER
    // ====================================
    
    // Bug #24: Client-side IP/CIDR/Range validation helper
    function validateIPOrRange(value) {
        value = value.replace(/\s+/g, ''); // Remove all spaces
        
        // Bug #28 fix: Check for dash-separated range only if both parts look like IPs
        if (value.indexOf('-') !== -1) {
            var parts = value.split('-');
            if (parts.length !== 2) {
                return 'Invalid IP range format. Use: start_ip-end_ip';
            }
            
            var startIP = parts[0];
            var endIP = parts[1];
            
            if (!startIP || !endIP) {
                return 'IP range is incomplete. Both start and end IPs are required.';
            }
            
            // Bug #28 fix: Basic IP format check - only treat as IP range if both parts look like IPs
            // This prevents hostnames like "192.my-server.com" from being validated as ranges
            var ipv4Pattern = /^(\d{1,3}\.){3}\d{1,3}$/;
            var ipv6Pattern = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;
            
            var startValid = ipv4Pattern.test(startIP) || ipv6Pattern.test(startIP);
            var endValid = ipv4Pattern.test(endIP) || ipv6Pattern.test(endIP);
            
            if (!startValid || !endValid) {
                // Malformed IP range - provide specific error
                return 'Invalid IP range format. Both start and end must be valid IP addresses. Use format: 192.168.0.120-192.168.0.169';
            } else {
                // Both parts are valid IPs - proceed with range validation
                
                if (startIP === endIP) {
                    return 'Start and end IPs are identical. Please use the "IP Address" tab to block a single IP instead.';
                }
                
                return true;
            }
        }
        
        // Check for CIDR notation
        if (value.indexOf('/') !== -1) {
            var cidrParts = value.split('/');
            if (cidrParts.length !== 2) {
                return 'Invalid CIDR format. Use: ip_address/mask';
            }
            
            var mask = parseInt(cidrParts[1]);
            if (isNaN(mask) || mask < 0 || mask > 128) {
                return 'Invalid CIDR mask. Must be 0-32 for IPv4 or 0-128 for IPv6.';
            }
            
            return true;
        }
        
        // Check for single IP (basic validation)
        var ipv4Pattern = /^(\d{1,3}\.){3}\d{1,3}$/;
        var ipv6Pattern = /^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}$/;
        
        if (!ipv4Pattern.test(value) && !ipv6Pattern.test(value)) {
            return 'Invalid IP address format.';
        }
        
        return true;
    }
    
    $('#vmpfence-custom-pattern-form').on('submit', function(e) {
        e.preventDefault();
        
        // Collect all pattern fields
        var patterns = [];
        var reason = $('#pattern-reason').val().trim();
        
        // Validate reason is required
        if (!reason) {
            VMPFenceNotifications.showError('Please enter a reason for blocking');
            return;
        }
        
        // Collect filled pattern fields with validation
        var validationError = null;
        $('.pattern-field').each(function() {
            var $field = $(this);
            var value = $field.val().trim();
            
            if (value) {
                var type = '';
                var fieldId = $field.attr('id');
                
                // Determine pattern type from field ID
                if (fieldId === 'pattern-ip-range') {
                    type = 'ip_range';
                    // Client-side validation for IP/CIDR/Range
                    var validationResult = validateIPOrRange(value);
                    if (validationResult !== true) {
                        validationError = validationResult;
                        return false; // Break loop
                    }
                } else if (fieldId === 'pattern-hostname') {
                    type = 'hostname';
                } else if (fieldId === 'pattern-user-agent') {
                    type = 'user_agent';
                } else if (fieldId === 'pattern-referrer') {
                    type = 'referrer';
                }
                
                if (type) {
                    patterns.push({
                        type: type,
                        value: value
                    });
                }
            }
        });
        
        // Check if validation failed
        if (validationError) {
            VMPFenceNotifications.showError(validationError);
            return;
        }
        
        // Validate at least one pattern is filled
        if (patterns.length === 0) {
            VMPFenceNotifications.showError('Please fill in at least one pattern field');
            return;
        }
        
        // Generate group_id (timestamp + random hex)
        var timestamp = Math.floor(Date.now() / 1000);
        var randomHex = Math.random().toString(16).substr(2, 6);
        var groupId = timestamp + '_' + randomHex;
        
        // Disable submit button
        var $btn = $(this).find('button[type="submit"]');
        var originalText = $btn.text();
        $btn.prop('disabled', true).text('BLOCKING...');
        
        // Submit via AJAX
        $.ajax({
            url: vmpfencePatternAjax.ajax_url,
            method: 'POST',
            data: {
                action: 'vmpfence_add_custom_pattern',
                nonce: vmpfencePatternAjax.nonce,
                patterns: patterns,
                group_id: groupId,
                reason: reason
            },
            success: function(response) {
                if (response.success) {
                    VMPFenceNotifications.showSuccess((response.data.message || 'Patterns blocked successfully') + '. Reloading page in 2 seconds...');
                    
                    // Reset form
                    $('#vmpfence-custom-pattern-form')[0].reset();
                    
                    // Close tab
                    $('.vmpfence-block-tabs .vmpfence-tab').removeClass('active');
                    $('#tab-custom-pattern').slideUp(300);
                    
                    // Reload page after 2 seconds to show updated list
                    setTimeout(function() {
                        window.location.reload();
                    }, 2000);
                } else {
                    VMPFenceNotifications.showError(response.data.message || 'Failed to add patterns');
                    $btn.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Network error. Please try again.');
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
});
</script>
