<?php
/**
 * VMPFence Firewall Options View
 *
 * @package VMPFence
 * @since 2.1.0 Added dynamic progress cards and advanced options
 * @since 2.2.2 Updated to reflect VMP Security branding, improved UI/UX design
 * @since 2.2.4 Added WAF optimization modal and integrated with new optimization workflow
 * @since 2.2.5 Filter by logic updated, IPs and URLs now support comma or newline separation
 */

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

// Handle install default WAF rules
if (isset($_POST['install_defaults']) && check_admin_referer('vmpfence_waf_install_defaults')) {
    $installed = VMPFence_WAF_Rule::install_default_rules();
    echo '<div class="notice notice-success"><p>' . sprintf(__('%d default rules installed successfully.', 'vmpfence-security'), $installed) . '</p></div>';
}

// Load current brute force configuration values
$brute_force_settings = array(
    // Boolean settings
    'brute_force_enabled' => VMPFence_Config::get('brute_force_enabled', 1),
    'lock_invalid_usernames' => VMPFence_Config::get('lock_invalid_usernames', 0),
    'prevent_leaked_passwords_enabled' => VMPFence_Config::get('prevent_leaked_passwords_enabled', 0),
    'enforce_strong_passwords' => VMPFence_Config::get('enforce_strong_passwords', 1),
    'dont_reveal_users' => VMPFence_Config::get('dont_reveal_users', 1),
    'prevent_admin_username' => VMPFence_Config::get('prevent_admin_username', 1),
    'prevent_username_discovery' => VMPFence_Config::get('prevent_username_discovery', 1),
    'disable_app_passwords' => VMPFence_Config::get('disable_app_passwords', 1),
    'block_post_requests' => VMPFence_Config::get('block_post_requests', 0),
    'check_password_strength' => VMPFence_Config::get('check_password_strength', 1),
    'participate_security_network' => VMPFence_Config::get('participate_security_network', 1),
    
    // Integer settings
    'max_login_attempts' => VMPFence_Config::get('max_login_attempts', 20),
    'max_forgot_password_attempts' => VMPFence_Config::get('max_forgot_password_attempts', 20),
    'count_failures_window' => VMPFence_Config::get('count_failures_window', 240),
    'lockout_duration' => VMPFence_Config::get('lockout_duration', 240),
    'permanent_ban_threshold' => VMPFence_Config::get('permanent_ban_threshold', 10),
    
    // String settings
    'prevent_leaked_passwords_scope' => VMPFence_Config::get('prevent_leaked_passwords_scope', 'admin'),
    'strong_passwords_scope' => VMPFence_Config::get('strong_passwords_scope', 'recommended'),
    'custom_block_text' => VMPFence_Config::get('custom_block_text', ''),
    
    // Array settings
    'blocked_usernames' => VMPFence_Config::get('blocked_usernames', array())
);

// Load rate limiting configuration values
$rate_limiting_enabled = VMPFence_Config::get('rate_limiting_enabled', 0);
$realtime_ip_blocklist_enabled = VMPFence_Config::get('realtime_ip_blocklist_enabled', 1);
$google_crawler_treatment = VMPFence_Config::get('google_crawler_treatment', 'verified_google');
$global_rate_limit = VMPFence_Config::get('global_rate_limit', 'unlimited');
$global_rate_action = VMPFence_Config::get('global_rate_action', 'throttle');
$crawler_rate_limit = VMPFence_Config::get('crawler_rate_limit', 'unlimited');
$crawler_rate_action = VMPFence_Config::get('crawler_rate_action', 'throttle');
$crawler_404_limit = VMPFence_Config::get('crawler_404_limit', 'unlimited');
$crawler_404_action = VMPFence_Config::get('crawler_404_action', 'throttle');
$human_rate_limit = VMPFence_Config::get('human_rate_limit', 'unlimited');
$human_rate_action = VMPFence_Config::get('human_rate_action', 'throttle');
$human_404_limit = VMPFence_Config::get('human_404_limit', 'unlimited');
$human_404_action = VMPFence_Config::get('human_404_action', 'throttle');
$rate_block_duration = VMPFence_Config::get('rate_block_duration', 5);
$throttle_behavior = VMPFence_Config::get('throttle_behavior', 'show_503');
$throttle_delay_duration = VMPFence_Config::get('throttle_delay_duration', 5);
$allowlisted_404_urls = VMPFence_Config::get('allowlisted_404_urls', array());
$waf_enabled = VMPFence_Config::get('waf_enabled', 1);
$waf_protection_level = VMPFence_Config::get('waf_protection_level', 'basic');

// Load advanced firewall configuration values
$delay_ip_blocking = VMPFence_Config::get('delay_ip_blocking', 0);
$whitelisted_ips_bypass = VMPFence_Config::get('whitelisted_ips_bypass', '');
$whitelisted_services_json = VMPFence_Config::get('whitelisted_services', '{}');
$blocked_urls = VMPFence_Config::get('blocked_urls', '');
$ignored_ips_waf = VMPFence_Config::get('ignored_ips_waf', '');

// Parse whitelisted services JSON
$whitelisted_services = array();
if (!empty($whitelisted_services_json)) {
    $decoded = json_decode($whitelisted_services_json, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $whitelisted_services = $decoded;
    }
}

// Convert blocked usernames array to textarea format
$blocked_usernames_text = is_array($brute_force_settings['blocked_usernames']) 
    ? implode("\n", $brute_force_settings['blocked_usernames']) 
    : '';

// Convert allowlisted 404 URLs array to textarea format
$allowlisted_404_urls_text = is_array($allowlisted_404_urls) 
    ? implode("\n", $allowlisted_404_urls) 
    : '';

// Enqueue firewall options CSS
wp_enqueue_style('vmpfence-firewall-options-css', plugins_url('assets/css/firewall-options.css', dirname(__FILE__)), array(), '1.0.0');

// Enqueue toast notification system
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 WAF optimization assets
wp_enqueue_style('vmpfence-waf-optimization-modals', plugins_url('assets/css/waf-optimization-modals.css', dirname(__FILE__)), array(), '1.0.1');
wp_enqueue_script('vmpfence-waf-optimization', plugins_url('assets/js/waf-optimization.js', dirname(__FILE__)), array('jquery'), '1.0.1', true);

// Localize WAF optimization script with nonce
wp_localize_script('vmpfence-waf-optimization', 'vmpfence_waf_ajax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'waf_optimizer_nonce' => wp_create_nonce('vmpfence_waf_optimizer_nonce')
));


// Enqueue jQuery
wp_enqueue_script('jquery');

// Enqueue Select2 for custom dropdowns
wp_enqueue_style('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css', array(), '4.1.0');
wp_enqueue_script('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), '4.1.0', true);

// Create inline script for AJAX variables
$ajax_nonce = wp_create_nonce('vmpfence_firewall_nonce');
$protection_level_nonce = wp_create_nonce('vmpfence_protection_level_nonce');
$waf_optimizer_nonce = wp_create_nonce('vmpfence_waf_optimizer_nonce');
$ajax_url = admin_url('admin-ajax.php');

// Check if WAF banner should be shown
$waf_notice_dismissed = get_option('vmpfence_waf_notice_dismissed', 0);
$show_waf_banner = ($waf_protection_level !== 'extended' && !$waf_notice_dismissed);

?>

<!-- Inline AJAX Configuration -->
<script type="text/javascript">
var vmpfence_ajax = {
    ajax_url: '<?php echo esc_js($ajax_url); ?>',
    nonce: '<?php echo esc_js($ajax_nonce); ?>',
    waf_optimizer_nonce: '<?php echo esc_js($waf_optimizer_nonce); ?>'
};
var vmpfence_firewall_ajax = {
    ajax_url: '<?php echo esc_js($ajax_url); ?>',
    nonce: '<?php echo esc_js($ajax_nonce); ?>',
    protection_level_nonce: '<?php echo esc_js($protection_level_nonce); ?>'
};
</script>

<!-- Top Navigation Bar -->
<div class="vmpfence-options-header vmpfence-sticky-header">
    <div class="vmpfence-options-nav">
        <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-firewall') ); ?>" class="vmpfence-back-link">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            Back to Firewall
        </a>
    </div>
    <div class="vmpfence-options-actions">
        <button class="vmpfence-btn-restore">RESTORE DEFAULTS</button>
        <button class="vmpfence-btn-cancel">CANCEL CHANGES</button>
        <button class="vmpfence-btn-save">SAVE CHANGES</button>
        
        <!-- Nonce field for AJAX security -->
        <input type="hidden" id="vmpfence_firewall_options_nonce" value="<?php echo esc_attr( wp_create_nonce('vmpfence_firewall_options') ); ?>">
    </div>
</div>

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

<!-- Main Options Content -->
<div class="vmpfence-options-content">
    <?php if ($show_waf_banner): ?>
        <!-- WAF Optimization Banner -->
        <div class="vmpfence-waf-optimization-banner" id="vmpfence-waf-optimization-banner">
            <div class="vmpfence-waf-banner-content">
                <p><strong>Optimize Your Firewall Protection:</strong> To make your site as secure as possible, optimize the VMP Security Web Application Firewall to run before WordPress loads. This provides maximum protection against attacks.</p>
            </div>
            <div class="vmpfence-waf-banner-actions">
                <button type="button" class="vmpfence-waf-banner-btn vmpfence-waf-banner-btn-primary" id="vmpfence-waf-banner-configure">
                    CLICK HERE TO CONFIGURE
                </button>
                <button type="button" class="vmpfence-waf-banner-btn vmpfence-waf-banner-btn-secondary" id="vmpfence-waf-banner-dismiss">
                    DISMISS
                </button>
            </div>
        </div>
        <?php 
        ?>
    <?php endif; ?>
    <!-- Title Section -->
    <div class="vmpfence-options-title-section">
        <div class="vmpfence-options-title">
            <h1>
                <img src="<?php echo esc_url( VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg' ); ?>" alt="VMP Fence" style="width: 32px; height: 32px; vertical-align: middle; margin-right: 10px;"> 
                Firewall Options
            </h1>
        </div>
        <!-- <div class="vmpfence-options-learn-more">
            <a href="#" class="vmpfence-learn-more-link">Learn more about the Firewall ↗</a>
        </div> -->
    </div>
    
    <!-- Four Progress Cards -->
    <div class="vmpfence-options-cards-row">
        <!-- WAF Card -->
        <div class="vmpfence-options-card">
            <div class="vmpfence-options-progress" data-status-type="firewall_waf">
                <?php 
                $firewall_enabled = VMPFence_Config::get('waf_enabled', 0);
                
                // Calculate WAF percentage: Rules (25%) + Premium (10%) + Real-Time Blocklist (35%) + Optimize (20%) + Rate Limiting (10%)
                if ($firewall_enabled) {
                    // Get rule enablement percentage from database
                    global $wpdb;
                    $table_name = $wpdb->prefix . 'vmpfence_waf_rules';
                    $total_rules = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
                    $disabled_rules = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE enabled = 0");
                    
                    $rule_percentage = 1.0;
                    if ($total_rules > 0) {
                        $enabled_rules = $total_rules - $disabled_rules;
                        $rule_percentage = $enabled_rules / $total_rules;
                    }
                    
                    // Check other features
                    $license_type = VMPFence_License::get_license_type();
                    $is_premium = ($license_type === VMPFence_Constants::LICENSE_PREMIUM);
                    $blacklist_enabled = VMPFence_Config::get('realtime_ip_blocklist_enabled', 0);
                    $protection_level = VMPFence_Config::get('waf_protection_level', 'basic');
                    $optimized = ($protection_level === 'extended');
                    $rate_limiting = VMPFence_Config::get('rate_limiting_enabled', 0);
                    
                    // Calculate percentage
                    $waf_percentage_decimal = 0.0;
                    $waf_percentage_decimal += $rule_percentage * 0.25;  // 25% for rules
                    $waf_percentage_decimal += ($is_premium ? 1.0 : 0.0) * 0.10;  // 10% for premium
                    $waf_percentage_decimal += ($blacklist_enabled ? 1.0 : 0.0) * 0.35;  // 35% for blocklist
                    $waf_percentage_decimal += ($optimized ? 1.0 : 0.0) * 0.20;  // 20% for optimization
                    $waf_percentage_decimal += ($rate_limiting ? 1.0 : 0.0) * 0.10;  // 10% for rate limiting
                    
                    $waf_percentage = round($waf_percentage_decimal * 100);
                } else {
                    $waf_percentage = 0;
                }
                
                // Set color based on percentage
                if ($waf_percentage >= 80) {
                    $waf_color = '#28a745'; // Green
                } elseif ($waf_percentage >= 60) {
                    $waf_color = '#17a2b8'; // Blue
                } elseif ($waf_percentage >= 40) {
                    $waf_color = '#ffc107'; // Yellow
                } else {
                    $waf_color = '#dc3545'; // Red
                }
                ?>
                <svg class="vmpfence-circle-chart" viewBox="0 0 33.83098862 33.83098862" width="100" height="100">
                    <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <circle class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($waf_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($waf_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <text x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($waf_percentage); ?>%</text>
                </svg>
            </div>
            <div class="vmpfence-options-card-info">
                <h3>Web Application Firewall</h3>
                <p>Stops Complex Attacks</p>
            </div>
        </div>

        <!-- Firewall Rules Card -->
        <div class="vmpfence-options-card">
            <div class="vmpfence-options-progress" data-status-type="firewall_rules">
                <?php 
                // Check premium status
                $license_type = VMPFence_License::get_license_type();
                $is_premium = ($license_type === VMPFence_Constants::LICENSE_PREMIUM);
                
                // Free users: 70% if firewall enabled, Premium users: 100% if enabled
                if ($firewall_enabled) {
                    $rules_percentage = $is_premium ? 100 : 70;
                } else {
                    $rules_percentage = 0;
                }
                
                // Set color based on percentage
                if ($rules_percentage >= 80) {
                    $rules_color = '#28a745'; // Green
                } elseif ($rules_percentage >= 60) {
                    $rules_color = '#17a2b8'; // Blue
                } elseif ($rules_percentage >= 40) {
                    $rules_color = '#ffc107'; // Yellow
                } else {
                    $rules_color = '#dc3545'; // Red
                }
                
                $rules_title = $is_premium ? 'Firewall Rules: Premium' : 'Firewall Rules: Community';
                $rules_description = $is_premium ? 'Real-time rule updates' : 'Rule updates delayed by 30 days';
                ?>
                <svg class="vmpfence-circle-chart" viewBox="0 0 33.83098862 33.83098862" width="100" height="100">
                    <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <circle class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($rules_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($rules_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <text x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($rules_percentage); ?>%</text>
                </svg>
            </div>
            <div class="vmpfence-options-card-info">
                <h3><?php echo esc_html($rules_title); ?></h3>
                <p><?php echo esc_html($rules_description); ?></p>
            </div>
        </div>

        <!-- IP Blocklist Card -->
        <div class="vmpfence-options-card">
            <div class="vmpfence-options-progress" data-status-type="realtime_blocklist">
                <?php 
                $blocked_ip_stats = VMPFence_Blocked_IP::get_stats();
                $api_ip_count = $blocked_ip_stats['api'] + $blocked_ip_stats['both'];
                $realtime_blocklist_enabled = VMPFence_Config::get('realtime_ip_blocklist_enabled', 0);
                $blocklist_percentage = $realtime_blocklist_enabled ? 100 : 0;
                
                // Set color based on percentage
                if ($blocklist_percentage >= 80) {
                    $blocklist_color = '#28a745'; // Green
                } elseif ($blocklist_percentage >= 60) {
                    $blocklist_color = '#17a2b8'; // Blue
                } elseif ($blocklist_percentage >= 40) {
                    $blocklist_color = '#ffc107'; // Yellow
                } else {
                    $blocklist_color = '#dc3545'; // Red
                }
                
                $blocklist_status = $realtime_blocklist_enabled ? 'Enabled' : 'Disabled';
                ?>
                <svg class="vmpfence-circle-chart" viewBox="0 0 33.83098862 33.83098862" width="100" height="100">
                    <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <circle class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($blocklist_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($blocklist_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <text x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($blocklist_percentage); ?>%</text>
                </svg>
            </div>
            <div class="vmpfence-options-card-info">
                <h3>Real-Time IP Blocklist: <?php echo esc_html($blocklist_status); ?></h3>
                <p>Blocks requests from known malicious IPs<?php if ($realtime_blocklist_enabled && $api_ip_count > 0): ?> (<?php echo number_format($api_ip_count); ?> synced)<?php endif; ?></p>
            </div>
        </div>

        <!-- Brute Force Card -->
        <div class="vmpfence-options-card">
            <div class="vmpfence-options-progress" data-status-type="firewall_brute_force">
                <?php 
                // Calculate brute force percentage based on all features
                // Base (10%) + Network (50%) + Strong Passwords (10%) + Mask Errors (10%) + Block Admin (10%) + Disable Author (10%)
                $brute_force_enabled = VMPFence_Config::get('brute_force_enabled', 0);
                $network_protection = VMPFence_Config::get('participate_security_network', 0);
                $strong_passwords = VMPFence_Config::get('enforce_strong_passwords', 0);
                $mask_errors = VMPFence_Config::get('dont_reveal_users', 0);
                $block_admin = VMPFence_Config::get('prevent_admin_username', 0);
                $disable_author = VMPFence_Config::get('prevent_username_discovery', 0);
                
                $brute_force_percentage = 0;
                if ($brute_force_enabled) {
                    $brute_force_percentage += 10;
                    if ($network_protection) $brute_force_percentage += 50;
                    if ($strong_passwords) $brute_force_percentage += 10;
                    if ($mask_errors) $brute_force_percentage += 10;
                    if ($block_admin) $brute_force_percentage += 10;
                    if ($disable_author) $brute_force_percentage += 10;
                }
                
                // Set color based on percentage
                if ($brute_force_percentage >= 80) {
                    $brute_force_color = '#28a745'; // Green
                } elseif ($brute_force_percentage >= 60) {
                    $brute_force_color = '#17a2b8'; // Blue
                } elseif ($brute_force_percentage >= 40) {
                    $brute_force_color = '#ffc107'; // Yellow
                } else {
                    $brute_force_color = '#dc3545'; // Red
                }
                ?>
                <svg class="vmpfence-circle-chart" viewBox="0 0 33.83098862 33.83098862" width="100" height="100">
                    <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <circle class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($brute_force_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($brute_force_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                    <text x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($brute_force_percentage); ?>%</text>
                </svg>
            </div>
            <div class="vmpfence-options-card-info">
                <h3>Brute Force Protection</h3>
                <p>Stops Password Guessing Attacks</p>
            </div>
        </div>
    </div>

    <!-- Collapsible Sections -->
    <div class="vmpfence-options-sections">        
        <!-- Basic Firewall Options Section -->
        <div class="vmpfence-basic-firewall-section">
            <h2 class="vmpfence-section-title">Basic Firewall Options</h2>
            
            <div class="vmpfence-firewall-grid">
                <!-- WAF Status -->
                <div class="vmpfence-firewall-box">
                    <h3>Web Application Firewall Status</h3>
                    <!-- <p><strong>Enabled and Protecting:</strong> In this mode, the VMP Security Web Application Firewall is actively blocking requests matching known attack patterns, protecting your site from attackers.</p> -->
                    <select id="waf_enabled" class="vmpfence-select">
                        <option value="1"<?php selected($waf_enabled, 1); ?>>Enabled and Protecting</option>
                        <option value="0"<?php selected($waf_enabled, 0); ?>>Disabled</option>
                    </select>
                    <p style="font-size: 16px; color: #666; line-height: 1.5;">The Web Application Firewall actively blocks malicious requests matching known attack patterns.</p>
                </div>

                <!-- Protection Level -->
                <div class="vmpfence-firewall-box">
                    <h3>Protection Level</h3>
                    <?php if ($waf_protection_level === 'extended'): ?>
                        <p style="font-size: 16px; color: #666; line-height: 1.5;"><strong>Extended Protection:</strong> All PHP requests will be processed by the firewall prior to running.</p>
                        <p style="font-size: 14px; color: #666; line-height: 1.5;">If you're moving to a new host or a new installation location, you may need to temporarily disable extended protection to avoid any file not found errors. Use this action to remove the configuration changes that enable extended protection mode or you can <a href="#">remove them manually</a>.</p>
                        <button class="vmpfence-btn-outline" id="remove-extended-protection">REMOVE EXTENDED PROTECTION</button>
                    <?php else: ?>
                        <p style="font-size: 16px; color: #666; line-height: 1.5;"><strong>Basic WordPress Protection:</strong> The plugin will load as a regular plugin after WordPress has been loaded, and while it can block many malicious requests, some vulnerable plugins or WordPress itself may run vulnerable code before all plugins are loaded.</p>
                        <button class="vmpfence-btn-primary" id="optimize-firewall">OPTIMIZE THE VMP FIREWALL</button>
                    <?php endif; ?>
                </div>

                <!-- Real-Time IP Blocklist -->
                <div class="vmpfence-firewall-box">
                    <h3>Real-Time IP Blocklist</h3>
                    <p>This feature blocks all traffic from IPs with a high volume of recent malicious activity using VMP Security's real-time blocklist.</p>
                    <div class="vmpfence-btn-group">
                        <input type="hidden" id="realtime_ip_blocklist_enabled" value="<?php echo esc_attr($realtime_ip_blocklist_enabled); ?>">
                        <button type="button" class="vmpfence-toggle-btn <?php echo !$realtime_ip_blocklist_enabled ? 'vmpfence-toggle-btn-active' : ''; ?>" data-value="off">DISABLED</button>
                        <button type="button" class="vmpfence-toggle-btn <?php echo $realtime_ip_blocklist_enabled ? 'vmpfence-toggle-btn-active' : ''; ?>" data-value="on">ENABLED</button>
                    </div>
                    
                    <p style="font-weight: 500; font-size: 12px; color: #666; line-height: 1.5; margin-top: 40px;">When enabled, the plugin automatically syncs blocked IPs from the API server every hour.</p>
                </div>
            </div>
        </div>

        <!-- Advanced Firewall Options Section -->
        <div class="vmpfence-options-section">
            <div class="vmpfence-options-section-header" onclick="toggleSection('advanced-firewall')">
                <h2>Advanced Firewall Options</h2>
                <svg class="vmpfence-chevron" width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="vmpfence-options-section-content" id="advanced-firewall-section" style="display: none;">
                
                <!-- Delay IP and Country Blocking -->
                 <!-- This will be implemented after 'Load firewall earlier then wordpress' or 'Extended Protection' is implemented -->
                <!-- <div class="vmpfence-advanced-option">
                    <div class="vmpfence-checkbox-wrapper">
                        <input type="checkbox" id="delay_ip_blocking"<?php checked($delay_ip_blocking, 1); ?>>
                        <label for="delay_ip_blocking">
                            <strong>Delay IP and Country blocking until after WordPress and plugins have loaded (only process firewall rules early)</strong>
                            <span class="vmpfence-help-icon">?</span>
                        </label>
                    </div>
                </div> -->

                <!-- Allowlisted IP Addresses -->
                <div class="vmpfence-advanced-option">
                    <label class="vmpfence-label-main">
                        Allowlisted IP addresses that bypass all rules <span class="vmpfence-help-icon">?</span>
                    </label>
                    <textarea id="whitelisted_ips_bypass" rows="6" class="vmpfence-textarea-full" placeholder=""><?php echo esc_textarea(implode("\n", array_map('trim', preg_split('/[,\s]+/', $whitelisted_ips_bypass, -1, PREG_SPLIT_NO_EMPTY)))); ?></textarea>
                    <p class="vmpfence-help-description">
                        Allowlisted IPs must be separated by commas or placed on separate lines. Supports both IPv4 and IPv6. You can specify ranges using the following formats: IPv4: 127.0.0.1/24, 127.0.0.[1-100], or 127.0.0.1-127.0.0.100; IPv6: 2001:db8::/32. 
                        VMP Security automatically allowlists <a href="https://en.wikipedia.org/wiki/Private_network" target="_blank" rel="noopener noreferrer">private networks</a> because these are not routable on the public Internet.
                    </p>
                </div>

                <!-- Allowlisted Services -->
                <div class="vmpfence-advanced-option">
                    <label class="vmpfence-label-main">
                        Allowlisted services <span class="vmpfence-help-icon">?</span>
                    </label>
                    <div class="vmpfence-services-grid">
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_sucuri"<?php checked(!empty($whitelisted_services['sucuri'])); ?>>
                            <span>Sucuri</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_facebook"<?php checked(!empty($whitelisted_services['facebook'])); ?>>
                            <span>Facebook</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_uptime"<?php checked(!empty($whitelisted_services['uptime'])); ?>>
                            <span>Uptime Robot</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_statuscake"<?php checked(!empty($whitelisted_services['statuscake'])); ?>>
                            <span>StatusCake</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_managewp"<?php checked(!empty($whitelisted_services['managewp'])); ?>>
                            <span>ManageWP</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_seznam"<?php checked(!empty($whitelisted_services['seznam'])); ?>>
                            <span>Seznam Search Engine</span>
                        </label>
                        <label class="vmpfence-service-checkbox">
                            <input type="checkbox" id="service_google"<?php checked(!empty($whitelisted_services['google'])); ?>>
                            <span>Google Search Engine</span>
                        </label>
                    </div>
                </div>

                <!-- Immediately Block IPs -->
                <div class="vmpfence-advanced-option">
                    <label class="vmpfence-label-main">
                        Immediately block IPs that access these URLs <span class="vmpfence-help-icon" title="When blocked via this option, an IP address will be blocked for the duration you have specified with the option ''How long is an IP address blocked'' when it breaks a rule found under the Rate Limiting rules.">?</span>
                    </label>
                    <textarea id="blocked_urls" rows="6" class="vmpfence-textarea-full" placeholder=""><?php echo esc_textarea(implode("\n", array_map('trim', preg_split('/[,\s]+/', $blocked_urls, -1, PREG_SPLIT_NO_EMPTY)))); ?></textarea>
                    <p class="vmpfence-help-description">
                        Separate multiple URLs with commas or place them on separate lines. Asterisks are wildcards, but use with care. If you see an attacker repeatedly probing your site for a known vulnerability you can use this to immediately block them. All URLs must start with a "/" without quotes and must be relative, e.g. /badURL/one/, /bannedPage.html, /starts/with-*, */starts-with-*, *ends-with-*
                    </p>
                </div>

                <!-- Ignored IP Addresses for WAF Alerting -->
                 <!-- This will be implemented after firewall is fully developed & alert system is added -->
                <!-- <div class="vmpfence-advanced-option">
                    <label class="vmpfence-label-main">
                        Ignored IP addresses for VMP Security Web Application Firewall alerting <span class="vmpfence-help-icon">?</span>
                    </label>
                    <textarea id="ignored_ips_waf" rows="6" class="vmpfence-textarea-full" placeholder=""><?php echo esc_textarea($ignored_ips_waf); ?></textarea>
                    <p class="vmpfence-help-description">
                        Ignored IPs must be separated by commas or placed on separate lines. These addresses will be ignored from any alerts about increased attacks and can be used to ignore things like standalone website security scanners.
                    </p>
                </div> -->

                <!-- WAF Rules Management Section -->
                <?php
                // Get all WAF rules
                $waf_rules = VMPFence_WAF_Rule::get_all();
                
                // Safety check - ensure we have a valid array
                if (!is_array($waf_rules)) {
                    $waf_rules = array();
                }
                
                // Category descriptions
                $waf_category_descriptions = array(
                    'xss' => 'Cross-Site Scripting (XSS) attacks attempt to inject malicious scripts into web pages viewed by other users.',
                    'sqli' => 'SQL Injection attacks try to manipulate database queries by inserting malicious SQL code.',
                    'sql_injection' => 'SQL Injection attacks try to manipulate database queries by inserting malicious SQL code.',
                    'rfi' => 'Remote File Inclusion attacks attempt to include and execute files from remote servers.',
                    'remote_file_inclusion' => 'Remote File Inclusion attacks attempt to include and execute files from remote servers.',
                    'lfi' => 'Local File Inclusion attacks try to include and execute local files on the server.',
                    'rce' => 'Remote Code Execution attacks attempt to execute arbitrary code on the server.',
                    'command_injection' => 'Command Injection attacks try to execute system commands through vulnerable application inputs.',
                    'file_upload' => 'Malicious File Upload attacks attempt to upload dangerous files that can compromise the server.',
                    'ldap_injection' => 'LDAP Injection attacks manipulate LDAP queries to bypass authentication or access unauthorized data.',
                    'null_byte' => 'Null Byte attacks use null characters to bypass security filters and access restricted files.',
                    'protocol' => 'Protocol-level attacks target vulnerabilities in network protocols and communication.',
                    'scanner' => 'Automated Security Scanners that probe for vulnerabilities should be detected and blocked.',
                    'wordpress' => 'WordPress-specific attacks target common vulnerabilities in WordPress core, plugins, and themes.',
                    'malware' => 'Malware detection rules identify known malicious code patterns and signatures.',
                    'spam' => 'Spam protection rules block automated spam submissions and bot activity.',
                    'server_misconfig' => 'Server Misconfiguration rules detect attempts to exploit common server configuration errors.',
                    'traversal' => 'Directory Traversal attacks try to access files outside the intended directory structure.',
                    'directory_traversal' => 'Directory Traversal attacks try to access files outside the intended directory structure.',
                    'xxe' => 'XML External Entity (XXE) attacks exploit vulnerabilities in XML parsers to access sensitive data.'
                );
                
                // Group rules by category and calculate stats
                $waf_categories_data = array();
                $category_to_db_categories = array(); // Track which DB categories map to each display category
                
                foreach ($waf_rules as $rule) {
                    // Skip rules without required fields
                    if (!isset($rule['category']) || empty($rule['category'])) {
                        continue;
                    }
                    
                    $original_category = trim($rule['category']); // Keep original for mapping
                    $category = strtolower($original_category); // Normalize to lowercase and trim
                    
                    // Comprehensive category name normalization - merge variations and aliases
                    $category_mapping = array(
                        'local_file_inclusion' => 'lfi',
                        'sql_injection' => 'sqli',
                        'sql' => 'sqli',  // Merge standalone 'sql' with 'sqli'
                        'remote_file_inclusion' => 'rfi',
                        'directory_traversal' => 'traversal',
                        'protocol_violation' => 'protocol',
                        'server_misconfig' => 'configuration',  // Merge variations
                        'command_injection' => 'rce',  // Command injection is a type of RCE
                    );
                    
                    if (isset($category_mapping[$category])) {
                        $category = $category_mapping[$category];
                    }
                    
                    // Track which original DB categories map to this display category
                    if (!isset($category_to_db_categories[$category])) {
                        $category_to_db_categories[$category] = array();
                    }
                    if (!in_array($original_category, $category_to_db_categories[$category])) {
                        $category_to_db_categories[$category][] = $original_category;
                    }
                    
                    if (!isset($waf_categories_data[$category])) {
                        $waf_categories_data[$category] = array(
                            'total' => 0,
                            'enabled' => 0,
                            'description' => isset($waf_category_descriptions[$category]) ? $waf_category_descriptions[$category] : 'Security rules for ' . ucfirst(str_replace('_', ' ', $category)) . '.'
                        );
                    }
                    $waf_categories_data[$category]['total']++;
                    if (isset($rule['enabled']) && $rule['enabled'] == 1) {
                        $waf_categories_data[$category]['enabled']++;
                    }
                }
                
                // Sort categories alphabetically
                ksort($waf_categories_data);
                
                // Check if API integration is available
                $waf_has_api = class_exists('VMPFence_API_Client') && 
                               class_exists('VMPFence_Config') && 
                               !empty(VMPFence_Config::get('central_api_key', ''));
                $waf_license_tier = class_exists('VMPFence_License') ? VMPFence_License::get_license_type() : 'free';
                $waf_is_premium = ($waf_license_tier === 'premium');
                ?>
                
                <div class="vmpfence-rules-section" id="waf-rules-section">
                    <h3 class="vmpfence-rules-title">
                        Rules <span class="vmpfence-help-icon">?</span>
                    </h3>
                    
                    <?php if (empty($waf_categories_data)): ?>
                    <div class="notice notice-warning inline" style="margin: 20px 0;">
                        <p><?php _e('No WAF rules found. Install default rules to get started.', 'vmpfence-security'); ?></p>
                    </div>
                    <form method="post" style="margin-top: 20px;">
                        <?php wp_nonce_field('vmpfence_waf_install_defaults'); ?>
                        <button type="submit" name="install_defaults" class="button button-primary">
                            <?php _e('Install Default Rules', 'vmpfence-security'); ?>
                        </button>
                    </form>
                    <?php else: ?>
                    
                    <!-- Category-Based Rules Table -->
                    <table class="wp-list-table widefat fixed striped vmpfence-waf-categories-table">
                        <thead>
                            <tr>
                                <th style="width: 80px; text-align: center;"><?php _e('Enable', 'vmpfence-security'); ?></th>
                                <th style="width: 200px;"><?php _e('Category', 'vmpfence-security'); ?></th>
                                <th><?php _e('Description', 'vmpfence-security'); ?></th>
                                <th style="width: 120px; text-align: center;"><?php _e('Rules Count', 'vmpfence-security'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($waf_categories_data as $category => $data): ?>
                            <tr>
                                <td style="text-align: center;">
                                    <label class="vmpfence-category-toggle">
                                        <input type="checkbox" 
                                               class="category-toggle-checkbox" 
                                               data-category="<?php echo esc_attr($category); ?>"
                                               data-db-categories="<?php echo esc_attr(json_encode($category_to_db_categories[$category])); ?>"
                                               data-total="<?php echo esc_attr($data['total']); ?>"
                                               data-enabled="<?php echo esc_attr($data['enabled']); ?>"
                                               <?php checked($data['enabled'] == $data['total'] && $data['total'] > 0); ?>>
                                        <span class="vmpfence-category-toggle-slider"></span>
                                    </label>
                                </td>
                                <td>
                                    <span class="badge badge-<?php echo esc_attr(strtolower($category)); ?>">
                                        <?php echo esc_html(strtoupper(str_replace('_', ' ', $category))); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html($data['description']); ?></td>
                                <td style="text-align: center;">
                                    <span class="category-status" data-category="<?php echo esc_attr($category); ?>">
                                        <?php if ($data['enabled'] == $data['total']): ?>
                                        <strong style="color: #46b450;"><?php echo esc_html($data['enabled'] . '/' . $data['total']); ?> Enabled</strong>
                                        <?php elseif ($data['enabled'] == 0): ?>
                                        <strong style="color: #dc3232;"><?php echo esc_html($data['enabled'] . '/' . $data['total']); ?> Disabled</strong>
                                        <?php else: ?>
                                        <strong style="color: #f0b849;"><?php echo esc_html($data['enabled'] . '/' . $data['total']); ?> Partial</strong>
                                        <?php endif; ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    
                    <?php endif; ?>
                    
                    <div class="vmpfence-rules-footer" style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center;">
                        <button class="vmpfence-btn-refresh" id="vmpfence-sync-waf-rules-btn" 
                                data-nonce="<?php echo wp_create_nonce('vmpfence_sync_waf_rules'); ?>"
                                <?php echo !$waf_has_api ? 'disabled' : ''; ?>>
                            MANUALLY REFRESH RULES
                        </button>
                        <?php if (!$waf_has_api): ?>
                        <span style="color: #dc3545; font-size: 13px;">
                            ⚠️ <?php _e('API key required to sync rules', 'vmpfence-security'); ?>
                        </span>
                        <?php endif; ?>
                        <span class="vmpfence-update-info" id="vmpfence-sync-status"></span>
                    </div>
                    
                    <style>
                        /* Category Toggle Switch - Modern Switch Design */
                        .vmpfence-category-toggle {
                            position: relative;
                            display: inline-block;
                            width: 48px;
                            height: 24px;
                        }

                        .vmpfence-category-toggle input {
                            opacity: 0;
                            width: 0;
                            height: 0;
                        }

                        .vmpfence-category-toggle-slider {
                            position: absolute;
                            cursor: pointer;
                            top: 0;
                            left: 0;
                            right: 0;
                            bottom: 0;
                            background-color: #ccc;
                            transition: 0.3s ease;
                            border-radius: 24px;
                        }

                        .vmpfence-category-toggle-slider:before {
                            position: absolute;
                            content: \"\";
                            height: 18px;
                            width: 18px;
                            left: 3px;
                            bottom: 3px;
                            background-color: white;
                            transition: 0.3s ease;
                            border-radius: 50%;
                            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
                        }

                        /* ON state - Midnight Blue background */
                        .vmpfence-category-toggle input:checked + .vmpfence-category-toggle-slider {
                            background-color: #191970;
                        }

                        .vmpfence-category-toggle input:checked + .vmpfence-category-toggle-slider:before {
                            transform: translateX(24px);
                        }

                        /* Hover effects */
                        .vmpfence-category-toggle input:not(:checked) + .vmpfence-category-toggle-slider:hover {
                            background-color: #b3b3b3;
                        }

                        .vmpfence-category-toggle input:checked + .vmpfence-category-toggle-slider:hover {
                            background-color: #14145a;
                        }
                        
                        /* Focus state for accessibility */
                        .vmpfence-category-toggle input:focus + .vmpfence-category-toggle-slider {
                            box-shadow: 0 0 0 3px rgba(25, 25, 112, 0.2);
                        }
                        
                        /* Unsaved changes animation */
                        @keyframes pendingPulse {
                            0%, 100% { opacity: 1; }
                            50% { opacity: 0.6; }
                        }
                        
                        .unsaved-indicator {
                            animation: pendingPulse 2s ease-in-out infinite;
                        }
                        
                        /* Category badge styles */
                        .vmpfence-waf-categories-table .badge {
                            display: inline-block;
                            padding: 6px 12px;
                            border-radius: 4px;
                            font-size: 11px;
                            font-weight: 600;
                            text-transform: uppercase;
                            background: transparent;
                            color: #555;
                        }
                    </style>
                </div>

            </div>
        </div>

        <!-- Brute Force Protection Section -->
        <div class="vmpfence-options-section">
            <div class="vmpfence-options-section-header" onclick="toggleSection('brute-force')">
                <h2>Brute Force Protection</h2>
                <svg class="vmpfence-chevron" width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="vmpfence-options-section-content" id="brute-force-section" style="display: none;">
                
                <!-- Enable Brute Force Protection -->
                <div class="vmpfence-option-group vmpfence-option-with-toggle">
                    <div class="vmpfence-option-left">
                        <h3 style="font-size: 14px; font-weight: 600; color: #000000;">Enable brute force protection <span class="vmpfence-help-icon">?</span></h3>
                        <p>This option enables all "Brute Force Protection" options, including strong password enforcement and invalid login throttling. You can modify individual options below.</p>
                    </div>
                    <div class="vmpfence-option-right">
                        <div class="vmpfence-btn-group">
                            <button class="vmpfence-toggle-btn<?php echo !$brute_force_settings['brute_force_enabled'] ? ' vmpfence-toggle-btn-active' : ''; ?>" data-value="off">OFF</button>
                            <button class="vmpfence-toggle-btn<?php echo $brute_force_settings['brute_force_enabled'] ? ' vmpfence-toggle-btn-active' : ''; ?>" data-value="on">ON</button>
                        </div>
                        <input type="hidden" id="brute_force_enabled" value="<?php echo $brute_force_settings['brute_force_enabled'] ? '1' : '0'; ?>">
                    </div>
                </div>

                <!-- Max Login Failures -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="max_login_failures_enabled" checked style="visibility: hidden;">
                            <span>Lock out after how many login failures <span class="vmpfence-help-icon" title="This setting controls the maximum number of failed login attempts before the user is locked out.">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="max_login_failures" class="vmpfence-select">
                            <option value="2"<?php selected($brute_force_settings['max_login_attempts'], 2); ?>>2</option>
                            <option value="3"<?php selected($brute_force_settings['max_login_attempts'], 3); ?>>3</option>
                            <option value="4"<?php selected($brute_force_settings['max_login_attempts'], 4); ?>>4</option>
                            <option value="5"<?php selected($brute_force_settings['max_login_attempts'], 5); ?>>5</option>
                            <option value="6"<?php selected($brute_force_settings['max_login_attempts'], 6); ?>>6</option>
                            <option value="7"<?php selected($brute_force_settings['max_login_attempts'], 7); ?>>7</option>
                            <option value="8"<?php selected($brute_force_settings['max_login_attempts'], 8); ?>>8</option>
                            <option value="9"<?php selected($brute_force_settings['max_login_attempts'], 9); ?>>9</option>
                            <option value="10"<?php selected($brute_force_settings['max_login_attempts'], 10); ?>>10</option>
                            <option value="20"<?php selected($brute_force_settings['max_login_attempts'], 20); ?>>20</option>
                            <option value="30"<?php selected($brute_force_settings['max_login_attempts'], 30); ?>>30</option>
                            <option value="40"<?php selected($brute_force_settings['max_login_attempts'], 40); ?>>40</option>
                            <option value="50"<?php selected($brute_force_settings['max_login_attempts'], 50); ?>>50</option>
                            <option value="60"<?php selected($brute_force_settings['max_login_attempts'], 60); ?>>60</option>
                            <option value="70"<?php selected($brute_force_settings['max_login_attempts'], 70); ?>>70</option>
                            <option value="80"<?php selected($brute_force_settings['max_login_attempts'], 80); ?>>80</option>
                            <option value="90"<?php selected($brute_force_settings['max_login_attempts'], 90); ?>>90</option>
                            <option value="100"<?php selected($brute_force_settings['max_login_attempts'], 100); ?>>100</option>
                            <option value="200"<?php selected($brute_force_settings['max_login_attempts'], 200); ?>>200</option>
                            <option value="300"<?php selected($brute_force_settings['max_login_attempts'], 300); ?>>300</option>
                            <option value="400"<?php selected($brute_force_settings['max_login_attempts'], 400); ?>>400</option>
                            <option value="500"<?php selected($brute_force_settings['max_login_attempts'], 500); ?>>500</option>
                        </select>
                    </div>
                </div>

                <!-- Forgot Password Attempts -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="max_forgot_password_enabled" checked style="visibility: hidden;">
                            <span>Lock out after how many forgot password attempts <span class="vmpfence-help-icon" title="This setting controls the maximum number of failed password reset attempts before the user is locked out.">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="max_forgot_password" class="vmpfence-select">
                            <option value="1"<?php selected($brute_force_settings['max_forgot_password_attempts'], 1); ?>>1</option>
                            <option value="2"<?php selected($brute_force_settings['max_forgot_password_attempts'], 2); ?>>2</option>
                            <option value="3"<?php selected($brute_force_settings['max_forgot_password_attempts'], 3); ?>>3</option>
                            <option value="4"<?php selected($brute_force_settings['max_forgot_password_attempts'], 4); ?>>4</option>
                            <option value="5"<?php selected($brute_force_settings['max_forgot_password_attempts'], 5); ?>>5</option>
                            <option value="6"<?php selected($brute_force_settings['max_forgot_password_attempts'], 6); ?>>6</option>
                            <option value="7"<?php selected($brute_force_settings['max_forgot_password_attempts'], 7); ?>>7</option>
                            <option value="8"<?php selected($brute_force_settings['max_forgot_password_attempts'], 8); ?>>8</option>
                            <option value="9"<?php selected($brute_force_settings['max_forgot_password_attempts'], 9); ?>>9</option>
                            <option value="10"<?php selected($brute_force_settings['max_forgot_password_attempts'], 10); ?>>10</option>
                            <option value="20"<?php selected($brute_force_settings['max_forgot_password_attempts'], 20); ?>>20</option>
                            <option value="30"<?php selected($brute_force_settings['max_forgot_password_attempts'], 30); ?>>30</option>
                            <option value="40"<?php selected($brute_force_settings['max_forgot_password_attempts'], 40); ?>>40</option>
                            <option value="50"<?php selected($brute_force_settings['max_forgot_password_attempts'], 50); ?>>50</option>
                            <option value="60"<?php selected($brute_force_settings['max_forgot_password_attempts'], 60); ?>>60</option>
                            <option value="70"<?php selected($brute_force_settings['max_forgot_password_attempts'], 70); ?>>70</option>
                            <option value="80"<?php selected($brute_force_settings['max_forgot_password_attempts'], 80); ?>>80</option>
                            <option value="90"<?php selected($brute_force_settings['max_forgot_password_attempts'], 90); ?>>90</option>
                            <option value="100"<?php selected($brute_force_settings['max_forgot_password_attempts'], 100); ?>>100</option>
                            <option value="200"<?php selected($brute_force_settings['max_forgot_password_attempts'], 200); ?>>200</option>
                            <option value="300"<?php selected($brute_force_settings['max_forgot_password_attempts'], 300); ?>>300</option>
                            <option value="400"<?php selected($brute_force_settings['max_forgot_password_attempts'], 400); ?>>400</option>
                            <option value="500"<?php selected($brute_force_settings['max_forgot_password_attempts'], 500); ?>>500</option>
                        </select>
                    </div>
                </div>

                <!-- Count Failures Time Period -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="count_failures_period_enabled" checked style="visibility: hidden;">
                            <span>Count failures over what time period <span class="vmpfence-help-icon" title="This setting controls the time window for counting failed login attempts.">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="count_failures_window" class="vmpfence-select">
                            <option value="5"<?php selected($brute_force_settings['count_failures_window'], 5); ?>>5 minutes</option>
                            <option value="10"<?php selected($brute_force_settings['count_failures_window'], 10); ?>>10 minutes</option>
                            <option value="30"<?php selected($brute_force_settings['count_failures_window'], 30); ?>>30 minutes</option>
                            <option value="60"<?php selected($brute_force_settings['count_failures_window'], 60); ?>>1 hour</option>
                            <option value="120"<?php selected($brute_force_settings['count_failures_window'], 120); ?>>2 hours</option>
                            <option value="240"<?php selected($brute_force_settings['count_failures_window'], 240); ?>>4 hours</option>
                            <option value="360"<?php selected($brute_force_settings['count_failures_window'], 360); ?>>6 hours</option>
                            <option value="720"<?php selected($brute_force_settings['count_failures_window'], 720); ?>>12 hours</option>
                            <option value="1440"<?php selected($brute_force_settings['count_failures_window'], 1440); ?>>1 day</option>
                        </select>
                    </div>
                </div>

                <!-- Lockout Duration -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="lockout_duration_enabled" checked style="visibility: hidden;">
                            <span>Amount of time a user is locked out <span class="vmpfence-help-icon" title="This setting controls how long a user is locked out after exceeding the maximum number of login attempts.">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="lockout_duration" class="vmpfence-select">
                            <option value="5"<?php selected($brute_force_settings['lockout_duration'], 5); ?>>5 minutes</option>
                            <option value="10"<?php selected($brute_force_settings['lockout_duration'], 10); ?>>10 minutes</option>
                            <option value="30"<?php selected($brute_force_settings['lockout_duration'], 30); ?>>30 minutes</option>
                            <option value="60"<?php selected($brute_force_settings['lockout_duration'], 60); ?>>1 hour</option>
                            <option value="120"<?php selected($brute_force_settings['lockout_duration'], 120); ?>>2 hours</option>
                            <option value="240"<?php selected($brute_force_settings['lockout_duration'], 240); ?>>4 hours</option>
                            <option value="360"<?php selected($brute_force_settings['lockout_duration'], 360); ?>>6 hours</option>
                            <option value="720"<?php selected($brute_force_settings['lockout_duration'], 720); ?>>12 hours</option>
                            <option value="1440"<?php selected($brute_force_settings['lockout_duration'], 1440); ?>>1 day</option>
                            <option value="2880"<?php selected($brute_force_settings['lockout_duration'], 2880); ?>>2 days</option>
                            <option value="7200"<?php selected($brute_force_settings['lockout_duration'], 7200); ?>>5 days</option>
                            <option value="14400"<?php selected($brute_force_settings['lockout_duration'], 14400); ?>>10 days</option>
                            <option value="28800"<?php selected($brute_force_settings['lockout_duration'], 28800); ?>>20 days</option>
                            <option value="43200"<?php selected($brute_force_settings['lockout_duration'], 43200); ?>>1 month</option>
                            <option value="86400"<?php selected($brute_force_settings['lockout_duration'], 86400); ?>>2 months</option>
                        </select>
                    </div>
                </div>

                <!-- Lock Out Invalid Usernames -->
                <div class="vmpfence-option-group">
                     <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="lock_invalid_usernames"<?php checked($brute_force_settings['lock_invalid_usernames']); ?>>
                        <span>Immediately lock out invalid usernames <span class="vmpfence-help-icon" title="When enabled, any IP that tries to login with a username that doesn't exist will be immediately blocked for the configured lockout duration. This prevents username enumeration attacks.">?</span></span>
                    </label>
                </div>

                <!-- Block Username Patterns -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-with-text">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="blocked_usernames_enabled" checked style="visibility: hidden;">
                        <span>Immediately block the IP of users who try to sign in as these usernames <span class="vmpfence-help-icon" title="When enabled, any IP that tries to login with a blocked username will be immediately blocked for the configured lockout duration.">?</span></span>
                    </label>
                    <div style="margin-left: 28px;">
                        <p class="vmpfence-option-note">Hit enter to add a username</p>
                        <textarea id="blocked_usernames" class="vmpfence-input-text" placeholder="Enter usernames, one per line" rows="3"><?php echo esc_textarea($blocked_usernames_text); ?></textarea>
                    </div>
                </div>

                <!-- Prevent Leaked Passwords -->
                 <!-- FUTURE Implementaion When SERVER SIDE is Ready -->
                <!-- <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="prevent_leaked_passwords_enabled"<?php checked($brute_force_settings['prevent_leaked_passwords_enabled']); ?>>
                            <span>Prevent the use of passwords leaked in data breaches <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="prevent_leaked_passwords_scope" class="vmpfence-select">
                            <option value="admin"<?php selected($brute_force_settings['prevent_leaked_passwords_scope'], 'admin'); ?>>For admins only</option>
                            <option value="all"<?php selected($brute_force_settings['prevent_leaked_passwords_scope'], 'all'); ?>>For all users with "publish posts" capability</option>
                        </select>
                    </div>
                </div> -->

                <!-- Additional Options Subsection -->
                <div class="vmpfence-subsection-header">
                    <h3>Additional Options</h3>
                </div>

                <!-- Enforce Strong Passwords -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <input type="checkbox" id="enforce_strong_passwords"<?php checked($brute_force_settings['enforce_strong_passwords']); ?>>
                            <span>Enforce strong passwords <span class="vmpfence-help-icon" title="Enforce strong passwords">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select id="strong_passwords_scope" class="vmpfence-select">
                            <option value="recommended"<?php selected($brute_force_settings['strong_passwords_scope'], 'recommended'); ?>>Force admins and publishers to use strong passwords (recommended)</option>
                            <option value="all"<?php selected($brute_force_settings['strong_passwords_scope'], 'all'); ?>>Force all members to use strong passwords</option>
                        </select>
                    </div>
                </div>

                <!-- Don't Let WordPress Reveal Valid Users -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="dont_reveal_users"<?php checked($brute_force_settings['dont_reveal_users']); ?>>
                        <span>Don't let WordPress reveal valid users in login errors <span class="vmpfence-help-icon" title="Prevent WordPress from revealing valid usernames in login error messages">?</span></span>
                    </label>
                </div>

                <!-- Prevent Admin Username -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="prevent_admin_username"<?php checked($brute_force_settings['prevent_admin_username']); ?>>
                        <span>Prevent users registering 'admin' username if it doesn't exist <span class="vmpfence-help-icon" title="Prevent users from registering the 'admin' username if it doesn't already exist">?</span></span>
                    </label>
                </div>

                <!-- Prevent Username Discovery -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="prevent_username_discovery"<?php checked($brute_force_settings['prevent_username_discovery']); ?>>
                        <span>Prevent discovery of usernames through '/?author=N' scans, the oEmbed API, the WordPress REST API, and WordPress XML Sitemaps <span class="vmpfence-help-icon" title="Prevent discovery of usernames through '/?author=N' scans, the oEmbed API, the WordPress REST API, and WordPress XML Sitemaps">?</span></span>
                    </label>
                </div>

                <!-- Disable Application Passwords -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="disable_app_passwords"<?php checked($brute_force_settings['disable_app_passwords']); ?>>
                        <span>Disable WordPress application passwords <span class="vmpfence-help-icon">?</span></span>
                    </label>
                </div>

                <!-- Block POST Requests -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-with-text">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="block_post_requests"<?php checked($brute_force_settings['block_post_requests']); ?>>
                        <span>Block IPs who send POST requests with blank User-Agent and Referer <span class="vmpfence-help-icon">?</span></span>
                    </label>
                    <p class="vmpfence-option-note">If you use external services that may send POST requests without these headers, do not use this option, as they will be blocked.</p>
                </div>

                <!-- Custom Block Text -->
                <div class="vmpfence-option-group vmpfence-option-with-textarea">
                    <div class="vmpfence-option-left">
                        <h3>Custom text shown on block pages <span class="vmpfence-help-icon">?</span></h3>
                    </div>
                    <div class="vmpfence-option-right">
                        <textarea id="custom_block_text" rows="4" class="vmpfence-textarea-full" placeholder=""><?php echo esc_textarea($brute_force_settings['custom_block_text']); ?></textarea>
                        <p class="vmpfence-option-note">HTML tags will be stripped prior to output and line breaks will be converted into the appropriate tags.</p>
                    </div>
                </div>

                <!-- Check Password Strength -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="check_password_strength"<?php checked($brute_force_settings['check_password_strength']); ?>>
                        <span>Check password strength on profile update <span class="vmpfence-help-icon">?</span></span>
                    </label>
                </div>

                <!-- Participate in Security Network -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-only">
                    <label class="vmpfence-checkbox-label">
                        <input type="checkbox" id="participate_security_network"<?php checked($brute_force_settings['participate_security_network']); ?>>
                        <span>Participate in the Real-Time VMP Security Network <span class="vmpfence-help-icon">?</span></span>
                    </label>
                </div>

            </div>
        </div>

        <!-- Rate Limiting Section -->
        <div class="vmpfence-options-section">
            <div class="vmpfence-options-section-header" onclick="toggleSection('rate-limiting')">
                <h2>Rate Limiting</h2>
                <svg class="vmpfence-chevron" width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="vmpfence-options-section-content" id="rate-limiting-section" style="display: none;">
                
                <!-- Enable Rate Limiting -->
                <div class="vmpfence-option-group vmpfence-option-with-toggle">
                    <div class="vmpfence-option-left">
                        <h3 style="font-size: 14px; font-weight: 600; color: #000000;">Enable Rate Limiting and Advanced Blocking <span class="vmpfence-help-icon">?</span></h3>
                        <p style="margin-top: 5px; color: #000000; font-size: 13px;"><strong>NOTE:</strong> This checkbox enables ALL blocking/throttling functions including IP, country and advanced blocking, and the "Rate Limiting Rules" below.</p>
                    </div>
                    <div class="vmpfence-option-right">
                        <div class="vmpfence-btn-group">
                            <button class="vmpfence-toggle-btn <?php echo !$rate_limiting_enabled ? 'vmpfence-toggle-btn-active' : ''; ?>" data-value="off">OFF</button>
                            <button class="vmpfence-toggle-btn <?php echo $rate_limiting_enabled ? 'vmpfence-toggle-btn-active' : ''; ?>" data-value="on">ON</button>
                        </div>
                        <input type="hidden" id="rate_limiting_enabled" name="rate_limiting_enabled" value="<?php echo $rate_limiting_enabled ? '1' : '0'; ?>">
                    </div>
                </div>

                <!-- How should we treat Google's crawlers -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>How should we treat Google's crawlers <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select class="vmpfence-select" id="google_crawler_treatment" name="google_crawler_treatment">
                            <option value="verified_google" <?php selected($google_crawler_treatment, 'verified_google'); ?>>Verified Google crawlers will not be rate-limited</option>
                            <option value="no_verification" <?php selected($google_crawler_treatment, 'no_verification'); ?>>Anyone claiming to be Google will not be rate-limited</option>
                            <option value="treat_as_crawler" <?php selected($google_crawler_treatment, 'treat_as_crawler'); ?>>Treat Google like any other Crawler</option>
                        </select>
                    </div>
                </div>

                <!-- If anyone's requests exceed -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>If anyone's requests exceed <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select class="vmpfence-select" id="global_rate_limit" name="global_rate_limit" style="min-width: 120px;">
                                <option value="unlimited" <?php selected($global_rate_limit, 'unlimited'); ?>>Unlimited</option>
                                <option value="1920" <?php selected($global_rate_limit, '1920'); ?>>1920 per minute</option>
                                <option value="960" <?php selected($global_rate_limit, '960'); ?>>960 per minute</option>
                                <option value="480" <?php selected($global_rate_limit, '480'); ?>>480 per minute</option>
                                <option value="240" <?php selected($global_rate_limit, '240'); ?>>240 per minute</option>
                                <option value="120" <?php selected($global_rate_limit, '120'); ?>>120 per minute</option>
                                <option value="60" <?php selected($global_rate_limit, '60'); ?>>60 per minute</option>
                                <option value="30" <?php selected($global_rate_limit, '30'); ?>>30 per minute</option>
                                <option value="15" <?php selected($global_rate_limit, '15'); ?>>15 per minute</option>
                                <option value="10" <?php selected($global_rate_limit, '10'); ?>>10 per minute</option>
                                <option value="5" <?php selected($global_rate_limit, '5'); ?>>5 per minute</option>
                                <option value="4" <?php selected($global_rate_limit, '4'); ?>>4 per minute</option>
                                <option value="3" <?php selected($global_rate_limit, '3'); ?>>3 per minute</option>
                                <option value="2" <?php selected($global_rate_limit, '2'); ?>>2 per minute</option>
                                <option value="1" <?php selected($global_rate_limit, '1'); ?>>1 per minute</option>
                            </select>
                            <span>then</span>
                            <select class="vmpfence-select" id="global_rate_action" name="global_rate_action" style="min-width: 120px;">
                                <option value="throttle" <?php selected($global_rate_action, 'throttle'); ?>>throttle it</option>
                                <option value="block" <?php selected($global_rate_action, 'block'); ?>>block it</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- If a crawler's page views exceed -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>If a crawler's page views exceed <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select class="vmpfence-select" id="crawler_rate_limit" name="crawler_rate_limit" style="min-width: 120px;">
                                <option value="unlimited" <?php selected($crawler_rate_limit, 'unlimited'); ?>>Unlimited</option>
                                <option value="1920" <?php selected($crawler_rate_limit, '1920'); ?>>1920 per minute</option>
                                <option value="960" <?php selected($crawler_rate_limit, '960'); ?>>960 per minute</option>
                                <option value="480" <?php selected($crawler_rate_limit, '480'); ?>>480 per minute</option>
                                <option value="240" <?php selected($crawler_rate_limit, '240'); ?>>240 per minute</option>
                                <option value="120" <?php selected($crawler_rate_limit, '120'); ?>>120 per minute</option>
                                <option value="60" <?php selected($crawler_rate_limit, '60'); ?>>60 per minute</option>
                                <option value="30" <?php selected($crawler_rate_limit, '30'); ?>>30 per minute</option>
                                <option value="15" <?php selected($crawler_rate_limit, '15'); ?>>15 per minute</option>
                                <option value="10" <?php selected($crawler_rate_limit, '10'); ?>>10 per minute</option>
                                <option value="5" <?php selected($crawler_rate_limit, '5'); ?>>5 per minute</option>
                                <option value="4" <?php selected($crawler_rate_limit, '4'); ?>>4 per minute</option>
                                <option value="3" <?php selected($crawler_rate_limit, '3'); ?>>3 per minute</option>
                                <option value="2" <?php selected($crawler_rate_limit, '2'); ?>>2 per minute</option>
                                <option value="1" <?php selected($crawler_rate_limit, '1'); ?>>1 per minute</option>
                            </select>
                            <span>then</span>
                            <select class="vmpfence-select" id="crawler_rate_action" name="crawler_rate_action" style="min-width: 120px;">
                                <option value="throttle" <?php selected($crawler_rate_action, 'throttle'); ?>>throttle it</option>
                                <option value="block" <?php selected($crawler_rate_action, 'block'); ?>>block it</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- If a crawler's pages not found (404s) exceed -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>If a crawler's pages not found (404s) exceed <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select class="vmpfence-select" id="crawler_404_limit" name="crawler_404_limit" style="min-width: 120px;">
                                <option value="unlimited" <?php selected($crawler_404_limit, 'unlimited'); ?>>Unlimited</option>
                                <option value="1920" <?php selected($crawler_404_limit, '1920'); ?>>1920 per minute</option>
                                <option value="960" <?php selected($crawler_404_limit, '960'); ?>>960 per minute</option>
                                <option value="480" <?php selected($crawler_404_limit, '480'); ?>>480 per minute</option>
                                <option value="240" <?php selected($crawler_404_limit, '240'); ?>>240 per minute</option>
                                <option value="120" <?php selected($crawler_404_limit, '120'); ?>>120 per minute</option>
                                <option value="60" <?php selected($crawler_404_limit, '60'); ?>>60 per minute</option>
                                <option value="30" <?php selected($crawler_404_limit, '30'); ?>>30 per minute</option>
                                <option value="15" <?php selected($crawler_404_limit, '15'); ?>>15 per minute</option>
                                <option value="10" <?php selected($crawler_404_limit, '10'); ?>>10 per minute</option>
                                <option value="5" <?php selected($crawler_404_limit, '5'); ?>>5 per minute</option>
                                <option value="4" <?php selected($crawler_404_limit, '4'); ?>>4 per minute</option>
                                <option value="3" <?php selected($crawler_404_limit, '3'); ?>>3 per minute</option>
                                <option value="2" <?php selected($crawler_404_limit, '2'); ?>>2 per minute</option>
                                <option value="1" <?php selected($crawler_404_limit, '1'); ?>>1 per minute</option>
                            </select>
                            <span>then</span>
                            <select class="vmpfence-select" id="crawler_404_action" name="crawler_404_action" style="min-width: 120px;">
                                <option value="throttle" <?php selected($crawler_404_action, 'throttle'); ?>>throttle it</option>
                                <option value="block" <?php selected($crawler_404_action, 'block'); ?>>block it</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- If a human's page views exceed -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>If a human's page views exceed <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select class="vmpfence-select" id="human_rate_limit" name="human_rate_limit" style="min-width: 120px;">
                                <option value="unlimited" <?php selected($human_rate_limit, 'unlimited'); ?>>Unlimited</option>
                                <option value="1920" <?php selected($human_rate_limit, '1920'); ?>>1920 per minute</option>
                                <option value="960" <?php selected($human_rate_limit, '960'); ?>>960 per minute</option>
                                <option value="480" <?php selected($human_rate_limit, '480'); ?>>480 per minute</option>
                                <option value="240" <?php selected($human_rate_limit, '240'); ?>>240 per minute</option>
                                <option value="120" <?php selected($human_rate_limit, '120'); ?>>120 per minute</option>
                                <option value="60" <?php selected($human_rate_limit, '60'); ?>>60 per minute</option>
                                <option value="30" <?php selected($human_rate_limit, '30'); ?>>30 per minute</option>
                                <option value="15" <?php selected($human_rate_limit, '15'); ?>>15 per minute</option>
                                <option value="10" <?php selected($human_rate_limit, '10'); ?>>10 per minute</option>
                                <option value="5" <?php selected($human_rate_limit, '5'); ?>>5 per minute</option>
                                <option value="4" <?php selected($human_rate_limit, '4'); ?>>4 per minute</option>
                                <option value="3" <?php selected($human_rate_limit, '3'); ?>>3 per minute</option>
                                <option value="2" <?php selected($human_rate_limit, '2'); ?>>2 per minute</option>
                                <option value="1" <?php selected($human_rate_limit, '1'); ?>>1 per minute</option>
                            </select>
                            <span>then</span>
                            <select class="vmpfence-select" id="human_rate_action" name="human_rate_action" style="min-width: 120px;">
                                <option value="throttle" <?php selected($human_rate_action, 'throttle'); ?>>throttle it</option>
                                <option value="block" <?php selected($human_rate_action, 'block'); ?>>block it</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- If a human's pages not found (404s) exceed -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>If a human's pages not found (404s) exceed <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <select class="vmpfence-select" id="human_404_limit" name="human_404_limit" style="min-width: 120px;">
                                <option value="unlimited" <?php selected($human_404_limit, 'unlimited'); ?>>Unlimited</option>
                                <option value="1920" <?php selected($human_404_limit, '1920'); ?>>1920 per minute</option>
                                <option value="960" <?php selected($human_404_limit, '960'); ?>>960 per minute</option>
                                <option value="480" <?php selected($human_404_limit, '480'); ?>>480 per minute</option>
                                <option value="240" <?php selected($human_404_limit, '240'); ?>>240 per minute</option>
                                <option value="120" <?php selected($human_404_limit, '120'); ?>>120 per minute</option>
                                <option value="60" <?php selected($human_404_limit, '60'); ?>>60 per minute</option>
                                <option value="30" <?php selected($human_404_limit, '30'); ?>>30 per minute</option>
                                <option value="15" <?php selected($human_404_limit, '15'); ?>>15 per minute</option>
                                <option value="10" <?php selected($human_404_limit, '10'); ?>>10 per minute</option>
                                <option value="5" <?php selected($human_404_limit, '5'); ?>>5 per minute</option>
                                <option value="4" <?php selected($human_404_limit, '4'); ?>>4 per minute</option>
                                <option value="3" <?php selected($human_404_limit, '3'); ?>>3 per minute</option>
                                <option value="2" <?php selected($human_404_limit, '2'); ?>>2 per minute</option>
                                <option value="1" <?php selected($human_404_limit, '1'); ?>>1 per minute</option>
                            </select>
                            <span>then</span>
                            <select class="vmpfence-select" id="human_404_action" name="human_404_action" style="min-width: 120px;">
                                <option value="throttle" <?php selected($human_404_action, 'throttle'); ?>>throttle it</option>
                                <option value="block" <?php selected($human_404_action, 'block'); ?>>block it</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- How long is an IP address blocked when it breaks a rule -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>How long is an IP address blocked when it breaks a rule <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select class="vmpfence-select" id="rate_block_duration" name="rate_block_duration">
                            <option value="1" <?php selected($rate_block_duration, 1); ?>>1 minute</option>
                            <option value="5" <?php selected($rate_block_duration, 5); ?>>5 minutes</option>
                            <option value="30" <?php selected($rate_block_duration, 30); ?>>30 minutes</option>
                            <option value="60" <?php selected($rate_block_duration, 60); ?>>1 hour</option>
                            <option value="120" <?php selected($rate_block_duration, 120); ?>>2 hours</option>
                            <option value="360" <?php selected($rate_block_duration, 360); ?>>6 hours</option>
                            <option value="720" <?php selected($rate_block_duration, 720); ?>>12 hours</option>
                            <option value="1440" <?php selected($rate_block_duration, 1440); ?>>1 day</option>
                            <option value="2880" <?php selected($rate_block_duration, 2880); ?>>2 days</option>
                            <option value="7200" <?php selected($rate_block_duration, 7200); ?>>5 days</option>
                            <option value="8640" <?php selected($rate_block_duration, 8640); ?>>10 days</option>
                            <option value="43200" <?php selected($rate_block_duration, 43200); ?>>1 month</option>
                        </select>
                    </div>
                </div>

                <!-- How should Throttle behave -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row" id="throttle_behavior_option" style="display: none;">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>How should Throttle behave? <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <select class="vmpfence-select" id="throttle_behavior" name="throttle_behavior">
                            <option value="slow_down" <?php selected($throttle_behavior, 'slow_down'); ?>>Slow Down Page Loading</option>
                            <option value="show_503" <?php selected($throttle_behavior, 'show_503'); ?>>Show 503 Unavailable Page</option>
                        </select>
                    </div>
                </div>

                <!-- Throttle delay duration -->
                <div class="vmpfence-option-group vmpfence-option-checkbox-row" id="throttle_delay_option" style="display: none;">
                    <div class="vmpfence-option-left">
                        <label class="vmpfence-checkbox-label">
                            <span>Page load delay duration (seconds) <span class="vmpfence-help-icon">?</span></span>
                        </label>
                    </div>
                    <div class="vmpfence-option-right">
                        <input type="number" class="vmpfence-input" id="throttle_delay_duration" name="throttle_delay_duration" value="<?php echo esc_attr($throttle_delay_duration); ?>" min="1" max="100" style="width: 100px;">
                        <span style="margin-left: 8px; color: #666; font-size: 13px;">seconds</span>
                    </div>
                </div>

                <!-- Allowlisted 404 URLs -->
                <div class="vmpfence-option-group vmpfence-option-with-textarea">
                    <div class="vmpfence-option-left">
                        <h3>Allowlisted 404 URLs <span class="vmpfence-help-icon">?</span></h3>
                        <p style="margin-top: 5px; color: #000000; font-size: 13px;">These URL patterns will be excluded from the throttling rules used to limit crawlers.</p>
                    </div>
                    <div class="vmpfence-option-right">
                        <textarea rows="4" class="vmpfence-textarea-full" id="allowlisted_404_urls" name="allowlisted_404_urls"><?php echo esc_textarea($allowlisted_404_urls_text); ?></textarea>
                    </div>
                </div>

            </div>
        </div>

        <!-- Allowlisted URLs Section -->
        <div class="vmpfence-options-section">
            <div class="vmpfence-options-section-header" onclick="toggleSection('allowlisted-urls')">
                <h2>Allowlisted URLs</h2>
                <svg class="vmpfence-chevron" width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class="vmpfence-options-section-content" id="allowlisted-urls-section" style="display: none;">
                
                <!-- Add Allowlisted URL/Param Section -->
                <div class="vmpfence-allowlist-form">
                    <h3 style="margin-bottom: 8px; font-size: 14px; font-weight: 600;">Add Allowlisted URL/Param <span class="vmpfence-help-icon">?</span></h3>
                    <p style="margin-bottom: 15px; font-size: 13px; color: #555; line-height: 1.4;">
                        The URL/parameters in this table will not be tested by the firewall. They are typically added while the firewall is in Learning Mode or by an admin who identifies a particular action/request as a false positive.
                    </p>
                    
                    <div class="vmpfence-allowlist-row" style="display: flex; align-items: center; gap: 10px; margin-bottom: 20px;">
                        <input type="text" id="allowlist_url" placeholder="URL" style="border: 1px solid #ddd; padding: 8px 10px; font-size: 13px; width: 200px; height: 36px; border-radius: 3px;">
                        <select id="allowlist_param_type" style="border: 1px solid #ddd; padding: 8px 10px; font-size: 13px; width: 180px; height: 36px; border-radius: 3px;">
                            <option value="POST Body">POST Body</option>
                            <option value="Query String">Query String</option>
                            <option value="Cookie">Cookie</option>
                            <option value="File Name">File Name</option>
                            <option value="Header">Header</option>
                        </select>
                        <input type="text" id="allowlist_param_name" placeholder="Param Name" style="border: 1px solid #ddd; padding: 8px 10px; font-size: 13px; width: 150px; height: 36px; border-radius: 3px;">
                        <button type="button" class="vmpfence-btn-add" style="background: #24248d; color: white; border: none; padding: 8px 16px; border-radius: 3px; cursor: pointer; font-size: 13px; font-weight: 600;">ADD</button>
                    </div>
                </div>

                <!-- Action and Filter Section -->
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; padding: 20px 25px;">
                    <!-- Action Buttons -->
                    <div style="display: flex; gap: 5px;">
                        <button type="button" class="vmpfence-btn-action vmpfence-btn-delete" style="background: #dc3232; color: white; border: none; padding: 6px 12px; border-radius: 3px; font-size: 11px; font-weight: 600; cursor: pointer; text-transform: uppercase;">DELETE</button>
                        <button type="button" class="vmpfence-btn-action vmpfence-btn-enable" style="background: #46b450; color: white; border: none; padding: 6px 12px; border-radius: 3px; font-size: 11px; font-weight: 600; cursor: pointer; text-transform: uppercase;">ENABLE</button>
                        <button type="button" class="vmpfence-btn-action vmpfence-btn-disable" style="background: #ddd; color: #666; border: none; padding: 6px 12px; border-radius: 3px; font-size: 11px; font-weight: 600; cursor: pointer; text-transform: uppercase;">DISABLE</button>
                    </div>
                    
                    <!-- Filter Section -->
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <select class="vmpfence-filter-select" style="border: 1px solid #ddd; padding: 6px 8px; font-size: 12px; border-radius: 3px; min-width: 110px;">
                            <option value="url">URL</option>
                            <option value="param">Param</option>
                            <option value="source">Source</option>
                            <option value="user">User</option>
                            <option value="ip">IP</option>
                        </select>
                        <input type="text" class="vmpfence-filter-input" placeholder="Filter Value" style="border: 1px solid #ddd; padding: 6px 8px; font-size: 12px; width: 150px; border-radius: 3px;">
                        <button type="button" class="vmpfence-btn-filter" style="background: #24248d; color: white; border: none; padding: 6px 12px; border-radius: 3px; font-size: 11px; font-weight: 600; cursor: pointer; text-transform: uppercase;">FILTER</button>
                    </div>
                </div>

                <!-- Allowlisted URLs Table -->
                <div class="vmpfence-allowlist-table-wrapper">
                    <?php wp_nonce_field('vmpfence_allowlist_nonce', 'vmpfence_allowlist_nonce'); ?>
                    <table class="vmpfence-allowlist-table">
                        <thead>
                            <tr>
                                <th style="width: 30px;"><input type="checkbox" class="vmpfence-select-all"></th>
                                <th style="width: 60px;">Enabled</th>
                                <th style="width: 120px;">URL</th>
                                <th style="width: 100px;">Param</th>
                                <th style="width: 120px;">Created</th>
                                <th style="width: 100px;">Source</th>
                                <th style="width: 60px;">User</th>
                                <th style="width: 80px;">IP</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Table rows will be populated via AJAX -->
                        </tbody>
                    </table>
                </div>

                <!-- Monitor Background Requests Section -->
                <div class="vmpfence-monitor-section" style="margin-top: 20px; padding: 20px 25px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 3px;">
                    <h3 style="margin: 0 0 10px 0; font-size: 14px; font-weight: 600; color: #333;">
                        Monitor background requests from an administrator's web browser for false positives 
                        <span class="vmpfence-help-icon" style="margin-left: 5px;">?</span>
                    </h3>
                    <div style="display: flex; gap: 20px; align-items: center;">
                        <label class="vmpfence-checkbox-label" style="display: flex; align-items: center; font-size: 13px; color: #333;">
                            <input type="checkbox" id="monitor_frontend" checked style="margin-right: 8px;">
                            <span>Front-end Website</span>
                        </label>
                        <label class="vmpfence-checkbox-label" style="display: flex; align-items: center; font-size: 13px; color: #333;">
                            <input type="checkbox" id="monitor_admin" checked style="margin-right: 8px;">
                            <span>Admin Panel</span>
                        </label>
                    </div>
                </div>

            </div>
        </div>

    </div>

</div>

<!-- JavaScript for Toggle Sections -->
<script type="text/javascript">
function toggleSection(sectionId) {
    const content = document.getElementById(sectionId + '-section');
    const header = content.previousElementSibling;
    const section = content.parentElement;
    const chevron = header.querySelector('.vmpfence-chevron');
    
    if (content.style.display === 'none' || content.style.display === '') {
        content.style.display = 'block';
        section.classList.add('expanded');
        if (chevron) chevron.style.transform = 'rotate(90deg)';
    } else {
        content.style.display = 'none';
        section.classList.remove('expanded');
        if (chevron) chevron.style.transform = 'rotate(0deg)';
    }
}

// Save button functionality
jQuery(document).ready(function($) {
    // Add CSS animation for spinning icon
    $('<style>@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }</style>').appendTo('head');
    
    // All allowlist functionality is now handled by firewall-options.js
    // This includes: ADD, DELETE, ENABLE, DISABLE, FILTER, and SELECT ALL
    
    // Handle URL hash to auto-open sections and scroll to specific settings
    if (window.location.hash) {
        var hash = window.location.hash.substring(1); // Remove the # symbol
        
        // Check if hash is participate_security_network
        if (hash === 'participate_security_network') {
            // Open the Brute Force Protection dropdown using the toggleSection function
            setTimeout(function() {
                // Use the existing toggleSection function
                toggleSection('brute-force');
                
                // Scroll to the checkbox after opening the section
                setTimeout(function() {
                    var targetElement = $('#' + hash);
                    if (targetElement.length) {
                        // Scroll to the element with offset for header
                        $('html, body').animate({
                            scrollTop: targetElement.offset().top - 100
                        }, 500);
                        
                        // Highlight the checkbox area briefly
                        targetElement.closest('.vmpfence-option-group').css({
                            'background-color': '#fff3cd',
                            'border-radius': '4px',
                            'transition': 'background-color 0.3s ease'
                        });
                        
                        // Remove highlight after 2 seconds
                        setTimeout(function() {
                            targetElement.closest('.vmpfence-option-group').css({
                                'background-color': '',
                                'border-radius': ''
                            });
                        }, 2000);
                    }
                }, 300);
            }, 100);
        }
        // Handle rate-limiting section auto-expand
        else if (hash === 'rate-limiting') {
            setTimeout(function() {
                // Use the existing toggleSection function to open Rate Limiting section
                toggleSection('rate-limiting');
                
                // Scroll to the section header
                setTimeout(function() {
                    var sectionHeader = $('#rate-limiting-section').prev('.vmpfence-options-section-header');
                    if (sectionHeader.length) {
                        // Scroll to the section with offset for header
                        $('html, body').animate({
                            scrollTop: sectionHeader.offset().top - 100
                        }, 500);
                    }
                }, 300);
            }, 100);
        }
        // Handle rate-limiting section auto-expand
        else if (hash === 'rate-limiting') {
            setTimeout(function() {
                // Use the existing toggleSection function to open Rate Limiting section
                toggleSection('rate-limiting');
                
                // Scroll to the section header
                setTimeout(function() {
                    var sectionHeader = $('#rate-limiting-section').prev('.vmpfence-options-section-header');
                    if (sectionHeader.length) {
                        // Scroll to the section with offset for header
                        $('html, body').animate({
                            scrollTop: sectionHeader.offset().top - 100
                        }, 500);
                    }
                }, 300);
            }, 100);
        }
        // Handle waf-rules section auto-expand and scroll
        else if (hash === 'waf-rules') {
            setTimeout(function() {
                // Open the Advanced Firewall Options section (ID is advanced-firewall-section)
                var sectionContent = $('#advanced-firewall-section');
                var sectionHeader = sectionContent.prev('.vmpfence-options-section-header');
                var section = sectionContent.parent();
                var chevron = sectionHeader.find('.vmpfence-chevron');
                
                // Expand the section if not already expanded
                if (sectionContent.css('display') === 'none') {
                    sectionContent.css('display', 'block');
                    section.addClass('expanded');
                    if (chevron.length) {
                        chevron.css('transform', 'rotate(90deg)');
                    }
                }
                
                // Scroll to the rules table after opening
                setTimeout(function() {
                    var rulesSection = $('#waf-rules-section');
                    if (rulesSection.length) {
                        // Scroll to the element with offset for header
                        $('html, body').animate({
                            scrollTop: rulesSection.offset().top - 100
                        }, 500);
                        
                        // Highlight briefly
                        rulesSection.css({
                            'background-color': '#fff3cd',
                            'border-radius': '4px',
                            'padding': '15px',
                            'transition': 'background-color 0.3s ease'
                        });
                        
                        setTimeout(function() {
                            rulesSection.css('background-color', '');
                        }, 2000);
                    }
                }, 300);
            }, 100);
        }
        // Handle brute-force section auto-expand and scroll
        else if (hash === 'brute-force') {
            setTimeout(function() {
                // Use the existing toggleSection function to open Brute Force section
                toggleSection('brute-force');
                
                // Scroll to the section header
                setTimeout(function() {
                    var sectionHeader = $('#brute-force-section').prev('.vmpfence-options-section-header');
                    if (sectionHeader.length) {
                        // Scroll to the section with offset for header
                        $('html, body').animate({
                            scrollTop: sectionHeader.offset().top - 100
                        }, 500);
                        
                        // Highlight briefly
                        sectionHeader.css({
                            'background-color': '#fff3cd',
                            'transition': 'background-color 0.3s ease'
                        });
                        
                        setTimeout(function() {
                            sectionHeader.css('background-color', '');
                        }, 2000);
                    }
                }, 300);
            }, 100);
        }
    }
    
    // Track category toggle changes (don't save immediately)
    window.categoryChanges = {};
    
    // Store original states on page load
    window.originalCategoryStates = {};
    $('.category-toggle-checkbox').each(function() {
        var category = $(this).data('category');
        var enabled = parseInt($(this).data('enabled'));
        var total = parseInt($(this).data('total'));
        // State is 1 (ON) only if ALL rules are enabled, 0 (OFF) otherwise
        var originalState = (enabled === total && total > 0) ? 1 : 0;
        window.originalCategoryStates[category] = originalState;
    });
    
    $(document).on('change', '.category-toggle-checkbox', function() {
        var checkbox = $(this);
        var category = checkbox.data('category');
        var dbCategories = checkbox.data('db-categories'); // Array of actual DB category names
        var isEnabled = checkbox.is(':checked') ? 1 : 0;
        var originalState = window.originalCategoryStates[category];
        var row = checkbox.closest('tr');
        
        // Check if current state differs from original
        if (isEnabled !== originalState) {
            // Store the change (pending save) with actual DB categories
            window.categoryChanges[category] = {
                enabled: isEnabled,
                db_categories: dbCategories
            };
            
            // Visual feedback - add "unsaved changes" indicator
            row.css({
                'background-color': '#fff3cd',
                'border-left': '3px solid #f0b849',
                'transition': 'all 0.3s ease'
            });
        } else {
            // Reverted to original - remove from changes and clear highlight
            delete window.categoryChanges[category];
            
            row.css({
                'background-color': '',
                'border-left': '',
                'transition': 'all 0.3s ease'
            });
        }
        
        // console.log('[VMPFence] Category ' + category + ' toggled to: ' + (isEnabled ? 'enabled' : 'disabled') + ' (DB categories: ' + JSON.stringify(dbCategories) + ', pending save: ' + (isEnabled !== originalState) + ')');
    });
    
    // Sync WAF rules from API (MANUALLY REFRESH RULES button) - WITH TOAST NOTIFICATIONS
    $('#vmpfence-sync-waf-rules-btn').on('click', function() {
        var $button = $(this);
        var $status = $('#vmpfence-sync-status');
        var nonce = $button.data('nonce');
        var originalText = $button.text();
        
        // Show confirmation modal
        VMPFenceNotifications.showConfirmModal({
            title: 'Sync WAF Rules',
            message: 'This will fetch the latest firewall rules from the API.\n\nDo you want to continue?',
            confirmText: 'Yes, Sync Rules',
            cancelText: 'Cancel',
            type: 'info'
        }).then(function(confirmed) {
            if (!confirmed) return;
            
            // Show loading notification
            var loadingToast = VMPFenceNotifications.showInfo('Syncing firewall rules from API...', 0, 'Please Wait');
            
            $button.prop('disabled', true).text('🔄 Syncing...');
            $status.html('<em style="color: #666;">Please wait...</em>');
            
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    action: 'vmpfence_sync_waf_rules',
                    nonce: nonce
                },
                success: function(response) {
                    // Remove loading toast
                    VMPFenceNotifications.removeToast(loadingToast);
                    
                    if (response.success) {
                        $status.html('<strong style="color: #00a32a;">✅ ' + response.data.message + '</strong>');
                        
                        // Show success toast
                        VMPFenceNotifications.showSuccess(
                            response.data.message + ' Page will reload in 2 seconds.',
                            3000,
                            'Rules Synced Successfully'
                        );
                        
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        $status.html('<strong style="color: #dc3232;">❌ ' + response.data + '</strong>');
                        $button.prop('disabled', false).text(originalText);
                        
                        // Show error toast
                        VMPFenceNotifications.showError(
                            response.data || 'Failed to sync firewall rules',
                            5000,
                            'Sync Failed'
                        );
                    }
                },
                error: function(xhr, status, error) {
                    // Remove loading toast
                    VMPFenceNotifications.removeToast(loadingToast);
                    
                    $status.html('<strong style="color: #dc3232;">❌ AJAX error occurred</strong>');
                    $button.prop('disabled', false).text(originalText);
                    
                    // Show error toast
                    VMPFenceNotifications.showError(
                        'Network error: ' + (error || 'Connection failed'),
                        6000,
                        'Request Failed'
                    );
                }
            });
        });
    });
});
</script>

<?php
// Properly enqueue the firewall options JavaScript file
wp_enqueue_script(
    'vmpfence-firewall-options',
    plugin_dir_url(__FILE__) . '../assets/js/firewall-options.js',
    array('jquery'),
    '2.2.1',
    true
);

// Localize script with AJAX URL and nonce
wp_localize_script('vmpfence-firewall-options', 'vmpfence_ajax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('vmpfence_firewall_options')
));

// Include WAF optimization modals
$plugin_root = plugin_dir_path(__FILE__) . '../../';
require_once $plugin_root . 'firewall/views/waf-optimization-modal.php';
require_once $plugin_root . 'firewall/views/waf-removal-modal.php';

?>
