<?php
/**
 * Settings management for BotFend Anti-Bot Firewall
 * @package BotFend\Admin
 * @since 4.0.0
 * @version 4.8.4 - Fixed bounded sanitization for settings flagged by WP.org review
 */

namespace BotFend\Admin;

use BotFend\Core\Config;
use BotFend\Core\Core;
use WP_Error;

defined('ABSPATH') || exit;

/**
 * Class AdminSettings
 * Handles all settings registration, sanitization, and management
 */
class AdminSettings {
    
    /**
     * Core instance
     *
     * @var Core
     */
    private $core;
    
    /**
     * Config instance
     *
     * @var Config
     */
    private $config;
    
    /**
     * Constructor
     * @param Core $core Core instance
     */
    public function __construct(Core $core) {
        $this->core = $core;
        $this->config = Config::get_instance();
    }
    
    /**
     * Get config value with backward compatibility
     */
    private function get_config_value($key, $default = '') {
        $config_key = str_replace('botfend_', '', $key);
        return $this->config->get_string($config_key, $default);
    }
    
    /**
     * Get config boolean
     */
    private function get_config_bool($key, $default = false): bool {
        return $this->config->get_bool($key, $default);
    }
    
    /**
     * Get config integer
     */
    private function get_config_int($key, $default = 0): int {
        return $this->config->get_int($key, $default);
    }
    
    /**
     * Update config value (writes to both config and options for consistency)
     */
    private function update_config_value($key, $value) {
        $result = update_option($key, $value);
        $config_key = str_replace('botfend_', '', $key);
        $this->config->set($config_key, $value);
        return $result;
    }
    
    /**
     * Get settings groups for admin display - ALL 14 TABS
     */
    public function get_settings_groups() {
        return [
            // TAB 1: GENERAL
            'general' => [
                'title' => esc_html__('General', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Basic plugin configuration and core security posture.', 'botfend-anti-bot-firewall'),
                'options' => [
                    'botfend_enabled',
                    'botfend_enable_adaptive',
                    'botfend_adaptive_mode',
                    'botfend_log_only',
                    'botfend_debug_mode',
                    'botfend_block_proxy',
                    'botfend_rate_limit',
                    'botfend_block_duration',
                    'botfend_notify_admin',
                    'botfend_allow_unblock',
                    'botfend_perpetual_enabled',
                    'botfend_perpetual_threshold',
                    'botfend_perpetual_window',
                ]
            ],
            
            // TAB 2: SESSION & API
            'session_api' => [
                'title' => esc_html__('Session & API', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Configure session management and API detection behavior.', 'botfend-anti-bot-firewall'),
                'options' => [
                    'botfend_api_detection',
                    'botfend_disable_sessions',
                    'botfend_force_sessions',
                    'botfend_session_required_patterns',
                    'botfend_custom_api_patterns',
                    'botfend_session_regenerate',
                    'botfend_session_timeout',
                    'botfend_session_bind_ip',
                    'botfend_session_bind_useragent',
                    'botfend_session_secure_cookie',
                    'botfend_session_httponly',
                    'botfend_session_samesite',
                    'botfend_bot_detection_sensitivity',
                    'botfend_session_storage',
                ]
            ],
            
            // TAB 3: DETECTION (Generic bot detection only)
            'detection' => [
                'title' => esc_html__('Detection', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Generic bot detection settings. Configure scoring for User-Agent, Proxy, Headers, Geographic Risk, TLS, and Known Attackers.', 'botfend-anti-bot-firewall'),
                'options' => [
                    // User Agent Scoring
                    'botfend_score_empty_ua',
                    'botfend_score_suspicious_ua',
                    'botfend_score_crawler_impersonation',
                    
                    // Rate & Behavioral Scoring
                    'botfend_score_high_rate',
                    'botfend_score_ctr_anomaly',
                    
                    // Proxy & Header Detection
                    'botfend_score_proxy',
                    'botfend_score_suspicious_headers',
                    
                    // TLS Detection
                    'botfend_enable_tls_detection',
                    'botfend_score_weak_tls',
                    
                    // Known Attacker Detection
                    'botfend_enable_threat_intel',
                    'botfend_score_known_attacker',
                    
                    // Geographic Risk Detection
                    'botfend_high_risk_countries',
                    'botfend_score_high_risk_country',
                    'botfend_blocked_countries',
                ]
            ],
            
            // TAB 4: TOR SYSTEM
            'tor_system' => [
                'title' => esc_html__('TOR System', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Configure TOR exit node detection and handling. TOR traffic can be scored, challenged, or blocked based on your preferences.', 'botfend-anti-bot-firewall'),
                'options' => [
                    'botfend_enable_tor_detection',
                    'botfend_score_tor',
                    'botfend_tor_action',
                    'botfend_tor_update_frequency',
                    'botfend_tor_last_update',
                ]
            ],
            
            // TAB 5: 404 SYSTEM
            '404_system' => [
                'title' => esc_html__('404 System', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Configure 404 abuse detection. Track excessive 404s and detect malicious path scanning patterns.', 'botfend-anti-bot-firewall'),
                'options' => [
                    'botfend_enable_advanced_404',
                    'botfend_max_404s',
                    'botfend_score_404_abuse',
                    'botfend_score_advanced_404',
                    'botfend_advanced_404_block_threshold',
                ]
            ],
            
            // TAB 6: THIRD PARTY
'third_party' => [
    'title' => esc_html__('Third Party', 'botfend-anti-bot-firewall'),
    'description' => esc_html__('Configure integration with external threat intelligence and security services.', 'botfend-anti-bot-firewall'),
    'options' => [
        'botfend_enable_iphub',
        'botfend_iphub_api_key',
        'botfend_iphub_mode',
        'botfend_allow_crawlers',
        'botfend_enable_abuseipdb',
        'botfend_abuseipdb_api_key',
        'botfend_abuseipdb_confidence',
        'botfend_abuseipdb_action',
        'botfend_enable_crawler_verification',
        'botfend_allow_legacy_crawlers',
        'botfend_enable_reverse_dns',
        'botfend_enable_external_tor_check',
        'botfend_enable_geolocation',
        'botfend_geolocation_service',
        'botfend_geolocation_cache_ttl',
        
        'botfend_enable_recaptcha',
        'botfend_recaptcha_version',
        'botfend_recaptcha_v3_site_key',
        'botfend_recaptcha_v3_secret_key',
        'botfend_recaptcha_v3_threshold',
        'botfend_recaptcha_v2_site_key',
        'botfend_recaptcha_v2_secret_key',
        'botfend_recaptcha_on_login',
        'botfend_recaptcha_on_registration',
        'botfend_recaptcha_on_lostpassword',
        'botfend_enable_comment_recaptcha',
        'botfend_comment_recaptcha_loggedin',
        'botfend_recaptcha_bypass_whitelist',
    ]
],
            
            // TAB 7: WAF
            'waf' => [
                'title' => esc_html__('WAF', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Configure Web Application Firewall protection against SQL injection, XSS, and other web attacks.', 'botfend-anti-bot-firewall'),
                'options' => [
                    'botfend_enable_waf',
                    'botfend_waf_action_mode',
                    'botfend_waf_block_threshold',
                    'botfend_waf_immediate_block',
                    'botfend_waf_integrate_scoring',
                    'botfend_waf_context_aware',
                    'botfend_waf_max_scan_time',
                    'botfend_waf_rate_limit',
                    'botfend_waf_wp_rules',
                ]
            ],
             
            // TAB 8: WORDPRESS PROTECTION
            'wordpress' => [
                'title' => esc_html__('WordPress', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Protect against WordPress-specific vulnerabilities and attacks.', 'botfend-anti-bot-firewall'),
                'options' => [
                    // Core Protection
                    'botfend_enable_wp_protection',
                    'botfend_wp_protection_threshold',
                    'botfend_block_wp_attacks',
                    'botfend_wp_attack_block_duration',
                    
                    // XML-RPC & REST API
                    'botfend_disable_xmlrpc',
                    'botfend_restrict_rest_api',
                    
                    // Login Protection
                    'botfend_max_login_attempts',
                    'botfend_max_login_failures',
                    'botfend_login_failure_window',
                    'botfend_login_block_duration',
                    'botfend_brute_force_block_duration',
                    'botfend_login_delay_suspicious',
                    
                    // Comment Protection
                    'botfend_enable_comment_protection',
                    
                    // Security Hardening
                    'botfend_block_author_scan',
                    'botfend_disable_pingbacks',
                    'botfend_add_security_headers',
                    'botfend_enable_wpcontent_protection',
                    
                    // Country Whitelist (WordPress-specific)
                    'botfend_enable_country_whitelist',
                    'botfend_whitelist_countries',
                    'botfend_whitelist_max_score',
                    
                    // Auto-Unblock
                    'botfend_enable_auto_unblock',
                    'botfend_auto_unblock_interval',
                ]
            ],
           
            // TAB 9: ADVANCED PROTECTION
            'advanced' => [
                'title' => esc_html__('Advanced', 'botfend-anti-bot-firewall'),
                'description' => esc_html__('Enable and configure advanced protection features including threat intelligence and behavioral analysis.', 'botfend-anti-bot-firewall'),
                'options' => [
                    // Threat Intelligence Feeds
                    'botfend_enable_threat_intel',
                    'botfend_threat_feed_blocklist_de',
                    'botfend_threat_feed_firehol_level1',
                    'botfend_threat_feed_emerging_threats',
                    'botfend_feed_weight_blocklist_de',
                    'botfend_feed_weight_firehol_level1',
                    'botfend_feed_weight_emerging_threats',
                    'botfend_feed_performance_tracking',
                    'botfend_feed_auto_optimization',
                    'botfend_feed_cache_enabled',
                    'botfend_feed_cache_duration',
                    'botfend_feed_retry_attempts',
                    
                    // Advanced Detection Features
                    'botfend_enable_signatures',
                    'botfend_enable_connection_fp',
                    'botfend_enable_intelligent_session',
                    'botfend_enable_behavioral_analysis',
                    'botfend_enable_smart_duration',
                    
                    // Behavioral Analysis Settings
                    'botfend_behavior_min_requests',
                    'botfend_behavior_time_window',
                    'botfend_behavior_block_threshold',
                    'botfend_behavior_penalty_enabled',
                    'botfend_behavior_max_penalty',
                    'botfend_behavior_penalty_ttl',
                    'botfend_behavior_sensitivity',
                    
                    // Behavioral Exemptions
                    'botfend_behavior_exempt_admins',
                    'botfend_behavior_exempt_editors',
                    'botfend_behavior_exempt_logged_in',
                    'botfend_behavior_exempt_ajax',
                    'botfend_behavior_exempt_api',
                    'botfend_behavior_exempt_paths',
                    'botfend_behavior_max_tracking',
                    'botfend_behavior_tracking_ttl',
                ]
            ],
                   
            
                    // TAB 10: CHALLENGES
                    'challenges' => [
                        'title' => esc_html__('Challenges', 'botfend-anti-bot-firewall'),
                        'description' => esc_html__('Configure JavaScript challenges, honeypots, and bot verification mechanisms.', 'botfend-anti-bot-firewall'),
                        'options' => [
                            'botfend_enable_js_challenge',
                            'botfend_enable_honeypot',
                            'botfend_challenge_probability',
                            'botfend_challenge_rate_limit',
                            'botfend_challenge_rate_window',
                            'botfend_challenge_expiry',
                            'botfend_challenge_bypass_crawlers',
                            'botfend_honeypot_block_duration',
                            'botfend_honeypot_progressive_blocking',
                            'botfend_honeypot_urls',
                            'botfend_block_headless_browsers',
                            'botfend_headless_block_duration',
                            'botfend_challenge_logging',
                            'botfend_whitelisted_paths',
                        ]
                    ],
                    
                    // TAB 11: PATHS
                    'paths' => [
                        'title' => esc_html__('Paths', 'botfend-anti-bot-firewall'),
                        'description' => esc_html__('Configure IP whitelists and permanent blocklists.', 'botfend-anti-bot-firewall'),
                        'options' => [
                            'botfend_whitelist_ips',
                            'botfend_permanent_blocklist',
                        ]
                    ],
                    
                    // TAB 12: SYSTEM
                    'system' => [
                        'title' => esc_html__('System', 'botfend-anti-bot-firewall'),
                        'description' => esc_html__('Plugin system, maintenance, and performance settings.', 'botfend-anti-bot-firewall'),
                        'options' => [
                            // IP Validation
                            'botfend_ip_validation_mode',
                            'botfend_trusted_proxies',
                            'botfend_ip_headers',
                            
                            // Cache Performance Settings
                            'botfend_enable_cache',
                            'botfend_cache_ttl',
                            'botfend_cache_use_object_cache',
                            'botfend_cache_max_memory_items',
                            'botfend_cache_performance_logging',
                            'botfend_cache_slow_request_threshold',
                            
                            // Performance Optimization
                            'botfend_disable_admin_checks',
                            'botfend_disable_editor_checks',
                            'botfend_cache_blocklist',
                            'botfend_skip_ajax_checks',
                            
                            // Rate Limits for Authenticated Users
                            'botfend_admin_rate_limit',
                            'botfend_editor_rate_limit',
                            'botfend_rate_limit_window',
                            'botfend_rate_limit_block_duration',
                            'botfend_bypass_admin_rate_limit',
                            
                            // Logging
                            'botfend_enable_centralized_logging',
                            'botfend_log_throttle_seconds',
                            'botfend_log_deduplication_window',
                            'botfend_enable_smart_aggregation',
                            'botfend_max_detailed_logs',
                            'botfend_aggregate_after_hours',
                            'botfend_keep_aggregates_days',
                            'botfend_log_sampling_rate',
                            'botfend_critical_score_threshold',
                            
                            // Logs Display
                            'botfend_logs_auto_refresh',
                            'botfend_logs_refresh_interval',
                            'botfend_logs_items_per_page',
                            'botfend_date_format',
                            'botfend_time_format',
                            
                            // Unblock Requests Display
                            'botfend_unblock_items_per_page',
                            'botfend_unblock_auto_refresh',
                            'botfend_unblock_refresh_interval',
                            'botfend_enable_unblock_export',
                            
                            // Dashboard
                            'botfend_dashboard_auto_refresh',
                            'botfend_dashboard_refresh_interval',
                            
                            // Data Management
                            'botfend_remove_data_on_uninstall',
                        ]
                    ],
                    
                    // TAB 13: FILE GUARD
                    'file_guard' => [
                        'title' => esc_html__('File Guard', 'botfend-anti-bot-firewall'),
                        'description' => esc_html__('Protect your WordPress installation from malicious file uploads, insecure permissions, and unauthorized file access.', 'botfend-anti-bot-firewall'),
                        'options' => [
                            'botfend_protect_uploads',
                            'botfend_scan_uploads',
                            'botfend_blocked_upload_extensions',
                            'botfend_disable_file_editors',
                            'botfend_disable_file_mods',
                            'botfend_monitor_permissions',
                            'botfend_auto_fix_permissions',
                            'botfend_alert_on_file_change',
                        ]
                    ],
                    
                    // TAB 14: EXPORT/IMPORT
                    'export_import' => [
                        'title' => esc_html__('Export/Import', 'botfend-anti-bot-firewall'),
                        'description' => esc_html__('Export or import your settings for backup or migration purposes.', 'botfend-anti-bot-firewall'),
                        'options' => [
                            'botfend_enable_export',
                            'botfend_enable_import',
                            'botfend_export_format',
                            'botfend_export_include_sensitive',
                            'botfend_import_merge_strategy',
                            'botfend_import_backup_first',
                        ]
                    ],
                ];
            }
            
            /**
             * Register all plugin settings with separate groups for tabs
             */
                   public function register_settings() {
            // Sanitization callbacks
            $checkbox_callback = [$this, 'sanitize_checkbox_option'];
            $textarea_callback = 'sanitize_textarea_field';
            $api_key_callback = [$this, 'sanitize_api_key'];
            $array_callback = [$this, 'sanitize_array_option'];
            
            // ======================
            // TAB 1: GENERAL SETTINGS
            // ======================
            register_setting('botfend_general_settings', 'botfend_enabled', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_general_settings', 'botfend_enable_adaptive', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_general_settings', 'botfend_adaptive_mode', [
                'sanitize_callback' => 'sanitize_text_field',
                'default' => 'balanced'
            ]);
            register_setting('botfend_general_settings', 'botfend_log_only', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_general_settings', 'botfend_debug_mode', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_general_settings', 'botfend_block_proxy', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_general_settings', 'botfend_rate_limit', [
                'sanitize_callback' => [$this, 'sanitize_rate_limit_bounded'],
                'default' => '100'
            ]);
            register_setting('botfend_general_settings', 'botfend_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '24'
            ]);
            register_setting('botfend_general_settings', 'botfend_notify_admin', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_general_settings', 'botfend_allow_unblock', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_general_settings', 'botfend_perpetual_enabled', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_general_settings', 'botfend_perpetual_threshold', [
                'sanitize_callback' => [$this, 'sanitize_perpetual_threshold'],
                'default' => '3'
            ]);
            register_setting('botfend_general_settings', 'botfend_perpetual_window', [
                'sanitize_callback' => [$this, 'sanitize_perpetual_window'],
                'default' => '30'
            ]);
            
            // ======================
            // TAB 2: SESSION & API SETTINGS
            // ======================
            register_setting('botfend_session_api_settings', 'botfend_api_detection', [
                'sanitize_callback' => function($input) {
                    $valid = ['conservative', 'balanced', 'aggressive'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'balanced';
                },
                'default' => 'balanced'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_disable_sessions', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_force_sessions', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_required_patterns', [
                'sanitize_callback' => $textarea_callback,
                'default' => "/wp-admin/\n/wp-login.php\n/dashboard/\n" . wp_parse_url(admin_url('admin-ajax.php'), PHP_URL_PATH)
            ]);
            register_setting('botfend_session_api_settings', 'botfend_custom_api_patterns', [
                'sanitize_callback' => $textarea_callback,
                'default' => "/api/\n/rest/\n/graphql\n/v1/\n/v2/"
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_regenerate', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_timeout', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '1800'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_bind_ip', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_bind_useragent', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_secure_cookie', [
                'sanitize_callback' => $checkbox_callback,
                'default' => is_ssl() ? '1' : '0'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_httponly', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_samesite', [
                'sanitize_callback' => function($input) {
                    $valid = ['Lax', 'Strict', 'None'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'Lax';
                },
                'default' => 'Lax'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_bot_detection_sensitivity', [
                'sanitize_callback' => function($input) {
                    $valid = ['low', 'medium', 'high', 'custom'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'medium';
                },
                'default' => 'medium'
            ]);
            register_setting('botfend_session_api_settings', 'botfend_session_storage', [
                'sanitize_callback' => function($input) {
                    $valid = ['files', 'database', 'memcached', 'redis'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'files';
                },
                'default' => 'files'
            ]);
            
            // ======================
            // TAB 3: DETECTION SETTINGS (Generic)
            // ======================
            register_setting('botfend_detection_settings', 'botfend_score_empty_ua', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '3'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_suspicious_ua', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '2'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_crawler_impersonation', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '7'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_high_rate', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '3'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_ctr_anomaly', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '3'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_proxy', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '3'
            ]);
            // FIXED: Changed from sanitize_range_option (0-100 float) to sanitize_score (0-10 integer)
            register_setting('botfend_detection_settings', 'botfend_score_suspicious_headers', [
                'sanitize_callback' => [$this, 'sanitize_score'],
                'default' => '2'
            ]);
            register_setting('botfend_detection_settings', 'botfend_enable_tls_detection', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_weak_tls', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '3'
            ]);
            register_setting('botfend_detection_settings', 'botfend_enable_threat_intel', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_known_attacker', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '8'
            ]);
            register_setting('botfend_detection_settings', 'botfend_high_risk_countries', [
                'sanitize_callback' => [$this, 'sanitize_country_list'],
                'default' => 'CN,RU,UA,BR,IN,VN,ID,TH,IR,PK,NL,FR,DE,AU,KR'
            ]);
            register_setting('botfend_detection_settings', 'botfend_score_high_risk_country', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '4'
            ]);
            register_setting('botfend_detection_settings', 'botfend_blocked_countries', [
                'sanitize_callback' => [$this, 'sanitize_country_list'],
                'default' => 'CN,IR,KP'
            ]);
            
            // ======================
            // TAB 4: TOR SYSTEM SETTINGS
            // ======================
            register_setting('botfend_tor_settings', 'botfend_enable_tor_detection', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_tor_settings', 'botfend_score_tor', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '4'
            ]);
            register_setting('botfend_tor_settings', 'botfend_tor_action', [
                'sanitize_callback' => function($input) {
                    $valid_actions = ['log_only', 'challenge', 'block', 'add_score'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid_actions, true) ? $input : 'challenge';
                },
                'default' => 'challenge'
            ]);
            register_setting('botfend_tor_settings', 'botfend_tor_update_frequency', [
                'sanitize_callback' => function($input) {
                    $valid_frequencies = ['hourly', 'daily', 'weekly'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid_frequencies, true) ? $input : 'daily';
                },
                'default' => 'daily'
            ]);
            register_setting('botfend_tor_settings', 'botfend_tor_last_update', [
                'sanitize_callback' => 'absint',
                'default' => 0
            ]);
            
            // ======================
            // TAB 5: 404 SYSTEM SETTINGS
            // ======================
            register_setting('botfend_404_settings', 'botfend_enable_advanced_404', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_404_settings', 'botfend_max_404s', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '10'
            ]);
            register_setting('botfend_404_settings', 'botfend_score_404_abuse', [
                'sanitize_callback' => [$this, 'sanitize_score'],
                'default' => '5'
            ]);
            register_setting('botfend_404_settings', 'botfend_score_advanced_404', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '4'
            ]);
            register_setting('botfend_404_settings', 'botfend_advanced_404_block_threshold', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '5'
            ]);
            
// ======================
// TAB 6: THIRD PARTY SETTINGS
// ======================
register_setting('botfend_third_party_settings', 'botfend_enable_iphub', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_iphub_api_key', [
    'sanitize_callback' => [$this, 'sanitize_api_key'],
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_iphub_mode', [
    'sanitize_callback' => function($input) {
        $valid_modes = ['strict', 'moderate', 'lenient'];
        $input = sanitize_text_field($input);
        return in_array($input, $valid_modes, true) ? $input : 'moderate';
    },
    'default' => 'moderate'
]);
register_setting('botfend_third_party_settings', 'botfend_allow_crawlers', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '1'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_abuseipdb', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_abuseipdb_api_key', [
    'sanitize_callback' => [$this, 'sanitize_api_key'],
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_abuseipdb_confidence', [
    'sanitize_callback' => [$this, 'sanitize_range_option'],
    'default' => '80'
]);
register_setting('botfend_third_party_settings', 'botfend_abuseipdb_action', [
    'sanitize_callback' => function($input) {
        $valid_actions = ['block', 'challenge', 'add_score', 'log_only'];
        $input = sanitize_text_field($input);
        return in_array($input, $valid_actions, true) ? $input : 'block';
    },
    'default' => 'block'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_crawler_verification', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '1'
]);
register_setting('botfend_third_party_settings', 'botfend_allow_legacy_crawlers', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_reverse_dns', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_external_tor_check', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_geolocation', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_geolocation_service', [
    'sanitize_callback' => function($input) {
        $valid_services = ['local', 'ip-api', 'ipapi', 'ipwhois', 'auto'];
        $input = sanitize_text_field($input);
        return in_array($input, $valid_services, true) ? $input : 'local';
    },
    'default' => 'local'
]);
register_setting('botfend_third_party_settings', 'botfend_geolocation_cache_ttl', [
    'sanitize_callback' => function($input) {
        $input = absint($input);
        if ($input < 1) return 1;
        if ($input > 30) return 30;
        return $input;
    },
    'default' => '7'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_recaptcha', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_version', [
    'sanitize_callback' => function($input) {
        $valid = ['v2', 'v3'];
        $input = sanitize_text_field($input);
        return in_array($input, $valid, true) ? $input : 'v3';
    },
    'default' => 'v3'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_v3_site_key', [
    'sanitize_callback' => 'sanitize_text_field',
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_v3_secret_key', [
    'sanitize_callback' => [$this, 'sanitize_api_key'],
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_v3_threshold', [
    'sanitize_callback' => [$this, 'sanitize_range_option'],
    'default' => '0.5'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_v2_site_key', [
    'sanitize_callback' => 'sanitize_text_field',
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_v2_secret_key', [
    'sanitize_callback' => [$this, 'sanitize_api_key'],
    'default' => ''
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_on_login', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_on_registration', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_on_lostpassword', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_enable_comment_recaptcha', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_comment_recaptcha_loggedin', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
register_setting('botfend_third_party_settings', 'botfend_recaptcha_bypass_whitelist', [
    'sanitize_callback' => [$this, 'sanitize_checkbox_option'],
    'default' => '0'
]);
            
            // ======================
            // TAB 7: WAF SETTINGS
            // ======================
            register_setting('botfend_waf_settings', 'botfend_enable_waf', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_action_mode', [
                'sanitize_callback' => function($input) {
                    $valid = ['score', 'block', 'challenge', 'log_only'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'score';
                },
                'default' => 'score'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_block_threshold', [
                'sanitize_callback' => [$this, 'sanitize_block_threshold'],
                'default' => '15'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_immediate_block', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_integrate_scoring', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_context_aware', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_max_scan_time', [
                'sanitize_callback' => 'floatval',
                'default' => '0.5'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_rate_limit', [
                'sanitize_callback' => 'absint',
                'default' => '10'
            ]);
            register_setting('botfend_waf_settings', 'botfend_waf_wp_rules', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            
            // ======================
            // TAB 8: WORDPRESS PROTECTION SETTINGS
            // ======================
            register_setting('botfend_wordpress_settings', 'botfend_enable_wp_protection', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_wp_protection_threshold', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '10'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_block_wp_attacks', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_wp_attack_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '24'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_disable_xmlrpc', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_restrict_rest_api', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_max_login_attempts', [
                'sanitize_callback' => function($input) {
                    return $this->sanitize_rate_limit_bounded($input, 1, 50);
                },
                'default' => '10'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_max_login_failures', [
                'sanitize_callback' => function($input) {
                    return $this->sanitize_rate_limit_bounded($input, 1, 20);
                },
                'default' => '5'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_login_failure_window', [
                'sanitize_callback' => [$this, 'sanitize_login_window'],
                'default' => '900'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_login_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_login_block_duration_bounded'],
                'default' => '15'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_brute_force_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '24'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_login_delay_suspicious', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_enable_comment_protection', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_block_author_scan', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_disable_pingbacks', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_add_security_headers', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_enable_wpcontent_protection', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_enable_country_whitelist', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_whitelist_countries', [
                'sanitize_callback' => [$this, 'sanitize_country_list'],
                'default' => ''
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_whitelist_max_score', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '8'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_enable_auto_unblock', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_wordpress_settings', 'botfend_auto_unblock_interval', [
                'sanitize_callback' => [$this, 'sanitize_auto_unblock_interval'],
                'default' => '24'
            ]);
            
            // ======================
            // TAB 9: ADVANCED SETTINGS
            // ======================
            register_setting('botfend_advanced_settings', 'botfend_enable_threat_intel', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_threat_feed_blocklist_de', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_threat_feed_firehol_level1', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_threat_feed_emerging_threats', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_weight_blocklist_de', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '8'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_weight_firehol_level1', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '9'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_weight_emerging_threats', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '7'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_performance_tracking', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_auto_optimization', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_cache_enabled', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_feed_cache_duration', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '3600'
            ]);
            // FIXED: Changed from sanitize_integer_option to sanitize_feed_retry_attempts (0-10 bounded)
            register_setting('botfend_advanced_settings', 'botfend_feed_retry_attempts', [
                'sanitize_callback' => [$this, 'sanitize_feed_retry_attempts'],
                'default' => '3'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_enable_signatures', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_enable_connection_fp', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_enable_intelligent_session', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_enable_behavioral_analysis', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_enable_smart_duration', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_min_requests', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '5'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_time_window', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '300'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_block_threshold', [
                'sanitize_callback' => [$this, 'sanitize_block_threshold'],
                'default' => '10'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_penalty_enabled', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_max_penalty', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '5'
            ]);
            // FIXED: Changed from sanitize_integer_option to sanitize_tracking_ttl (300-86400 bounded)
            register_setting('botfend_advanced_settings', 'botfend_behavior_penalty_ttl', [
                'sanitize_callback' => [$this, 'sanitize_tracking_ttl'],
                'default' => '3600'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_admins', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_editors', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_logged_in', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_ajax', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_api', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_exempt_paths', [
                'sanitize_callback' => [$this, 'sanitize_path_patterns'],
                'default' => "/wp-admin/*\n/wp-login.php\n/wp-json/*\n/wp-cron.php"
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_sensitivity', [
                'sanitize_callback' => function($input) {
                    $valid = ['low', 'medium', 'high'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'medium';
                },
                'default' => 'medium'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_max_tracking', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '100'
            ]);
            register_setting('botfend_advanced_settings', 'botfend_behavior_tracking_ttl', [
                'sanitize_callback' => [$this, 'sanitize_tracking_ttl'],
                'default' => '3600'
            ]);
            
            // ======================
            // TAB 10: CHALLENGES SETTINGS
            // ======================
            register_setting('botfend_challenges_settings', 'botfend_enable_js_challenge', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_enable_honeypot', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_challenge_probability', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '30'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_challenge_rate_limit', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '5'
            ]);
            // FIXED: Changed from sanitize_integer_option to sanitize_rate_window (60-3600 bounded)
            register_setting('botfend_challenges_settings', 'botfend_challenge_rate_window', [
                'sanitize_callback' => [$this, 'sanitize_rate_window'],
                'default' => '300'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_challenge_expiry', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '86400'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_challenge_bypass_crawlers', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_honeypot_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '24'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_honeypot_progressive_blocking', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_honeypot_urls', [
                'sanitize_callback' => $textarea_callback,
                'default' => "/wp-admin.bak\n/wp-login.php.bak\n/license.txt\n/readme.html\n/xmlrpc.php.bak\n/admin.php\n/administrator/index.php\n/wp-content/uploads/.htaccess.bak\n/.env\n/config.php.bak\n/phpinfo.php\n/test.php"
            ]);
            register_setting('botfend_challenges_settings', 'botfend_block_headless_browsers', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_headless_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '24'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_challenge_logging', [
                'sanitize_callback' => function($input) {
                    $valid = ['minimal', 'normal', 'verbose'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'normal';
                },
                'default' => 'normal'
            ]);
            register_setting('botfend_challenges_settings', 'botfend_whitelisted_paths', [
                'sanitize_callback' => $textarea_callback,
                'default' => "/.well-known/traffic-advice\n/.well-known/security.txt\n/.well-known/assetlinks.json\n/.well-known/apple-app-site-association\n/.well-known/dnt-policy.txt\n/.well-known/pki-validation/\n/robots.txt\n/favicon.ico\n/sitemap.xml\n/sitemap_index.xml\n/humans.txt\n/ads.txt"
            ]);
            
            // ======================
            // TAB 11: PATHS SETTINGS
            // ======================
            register_setting('botfend_paths_settings', 'botfend_whitelist_ips', [
                'sanitize_callback' => [$this, 'sanitize_ip_list'],
                'default' => ''
            ]);
            register_setting('botfend_paths_settings', 'botfend_permanent_blocklist', [
                'sanitize_callback' => [$this, 'sanitize_ip_list'],
                'default' => ''
            ]);
            
            // ======================
            // TAB 12: SYSTEM SETTINGS
            // ======================
            register_setting('botfend_system_settings', 'botfend_ip_validation_mode', [
                'sanitize_callback' => function($input) {
                    $valid = ['strict', 'balanced', 'permissive'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'balanced';
                },
                'default' => 'balanced'
            ]);
            register_setting('botfend_system_settings', 'botfend_trusted_proxies', [
                'sanitize_callback' => [$this, 'sanitize_proxy_list'],
                'default' => [
                    '173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
                    '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
                    '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
                    '104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22', '2400:cb00::/32',
                    '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32',
                    '2a06:98c0::/29', '2c0f:f248::/32',
                ]
            ]);
            register_setting('botfend_system_settings', 'botfend_ip_headers', [
                'sanitize_callback' => [$this, 'sanitize_header_list'],
                'default' => [
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_FORWARDED_FOR',
                    'HTTP_X_REAL_IP',
                    'HTTP_CLIENT_IP',
                    'REMOTE_ADDR'
                ]
            ]);
            register_setting('botfend_system_settings', 'botfend_enable_cache', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_ttl', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '3600'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_use_object_cache', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_max_memory_items', [
                'sanitize_callback' => function($input) {
                    return $this->sanitize_integer_option($input, 100, 5000);
                },
                'default' => '500'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_performance_logging', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_slow_request_threshold', [
                'sanitize_callback' => function($input) {
                    return $this->sanitize_integer_option($input, 50, 1000);
                },
                'default' => '200'
            ]);
            register_setting('botfend_system_settings', 'botfend_disable_admin_checks', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_disable_editor_checks', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_cache_blocklist', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_skip_ajax_checks', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_admin_rate_limit', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '60'
            ]);
            register_setting('botfend_system_settings', 'botfend_editor_rate_limit', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '45'
            ]);
            register_setting('botfend_system_settings', 'botfend_rate_limit_window', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '60'
            ]);
            register_setting('botfend_system_settings', 'botfend_rate_limit_block_duration', [
                'sanitize_callback' => [$this, 'sanitize_block_duration_bounded'],
                'default' => '30'
            ]);
            register_setting('botfend_system_settings', 'botfend_bypass_admin_rate_limit', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_system_settings', 'botfend_enable_centralized_logging', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_log_throttle_seconds', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '10'
            ]);
            register_setting('botfend_system_settings', 'botfend_log_deduplication_window', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '300'
            ]);
            register_setting('botfend_system_settings', 'botfend_enable_smart_aggregation', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_max_detailed_logs', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '300'
            ]);
            // FIXED: Changed from sanitize_integer_option to sanitize_aggregation_hours (1-720 bounded)
            register_setting('botfend_system_settings', 'botfend_aggregate_after_hours', [
                'sanitize_callback' => [$this, 'sanitize_aggregation_hours'],
                'default' => '24'
            ]);
            register_setting('botfend_system_settings', 'botfend_keep_aggregates_days', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '90'
            ]);
            register_setting('botfend_system_settings', 'botfend_log_sampling_rate', [
                'sanitize_callback' => [$this, 'sanitize_percentage_option'],
                'default' => '0.1'
            ]);
            register_setting('botfend_system_settings', 'botfend_critical_score_threshold', [
                'sanitize_callback' => [$this, 'sanitize_range_option'],
                'default' => '7'
            ]);
            register_setting('botfend_system_settings', 'botfend_logs_auto_refresh', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_system_settings', 'botfend_logs_refresh_interval', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '30000'
            ]);
            register_setting('botfend_system_settings', 'botfend_logs_items_per_page', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '100'
            ]);
            register_setting('botfend_system_settings', 'botfend_date_format', [
                'sanitize_callback' => 'sanitize_text_field',
                'default' => get_option('date_format')
            ]);
            register_setting('botfend_system_settings', 'botfend_time_format', [
                'sanitize_callback' => 'sanitize_text_field',
                'default' => get_option('time_format')
            ]);
            register_setting('botfend_system_settings', 'botfend_unblock_items_per_page', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '50'
            ]);
            register_setting('botfend_system_settings', 'botfend_unblock_auto_refresh', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_system_settings', 'botfend_unblock_refresh_interval', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '30000'
            ]);
            register_setting('botfend_system_settings', 'botfend_enable_unblock_export', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_system_settings', 'botfend_dashboard_auto_refresh', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_system_settings', 'botfend_dashboard_refresh_interval', [
                'sanitize_callback' => [$this, 'sanitize_integer_option'],
                'default' => '30'
            ]);
            register_setting('botfend_system_settings', 'botfend_remove_data_on_uninstall', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            
            // ======================
            // TAB 13: FILE GUARD SETTINGS
            // ======================
            register_setting('botfend_file_guard_settings', 'botfend_protect_uploads', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_scan_uploads', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_blocked_upload_extensions', [
                'sanitize_callback' => [$this, 'sanitize_array_option'],
                'default' => ['php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'phps', 'pht', 'phtm', 'htaccess', 'htpasswd', 'ini', 'log', 'sql']
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_disable_file_editors', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_disable_file_mods', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_monitor_permissions', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_auto_fix_permissions', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_file_guard_settings', 'botfend_alert_on_file_change', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            
            // ======================
            // TAB 14: EXPORT/IMPORT SETTINGS
            // ======================
            register_setting('botfend_export_import_settings', 'botfend_enable_export', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_export_import_settings', 'botfend_enable_import', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            register_setting('botfend_export_import_settings', 'botfend_export_format', [
                'sanitize_callback' => function($input) {
                    $valid = ['json', 'xml', 'csv'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'json';
                },
                'default' => 'json'
            ]);
            register_setting('botfend_export_import_settings', 'botfend_export_include_sensitive', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '0'
            ]);
            register_setting('botfend_export_import_settings', 'botfend_import_merge_strategy', [
                'sanitize_callback' => function($input) {
                    $valid = ['merge', 'replace', 'skip'];
                    $input = sanitize_text_field($input);
                    return in_array($input, $valid, true) ? $input : 'merge';
                },
                'default' => 'merge'
            ]);
            register_setting('botfend_export_import_settings', 'botfend_import_backup_first', [
                'sanitize_callback' => $checkbox_callback,
                'default' => '1'
            ]);
            
            // Sync with config after registration
            add_action('updated_option', [$this, 'sync_option_to_config'], 10, 3);
            add_action('added_option', [$this, 'sync_added_option_to_config'], 10, 2);
        }
        
        /**
         * Sync updated option to config
         */
        public function sync_option_to_config($option, $old_value, $new_value) {
            if (strpos($option, 'botfend_') === 0) {
                $config_key = str_replace('botfend_', '', $option);
                $this->config->set($config_key, $new_value);
            }
        }
        
        /**
         * Sync newly added option to config
         */
        public function sync_added_option_to_config($option, $value) {
            if (strpos($option, 'botfend_') === 0) {
                $config_key = str_replace('botfend_', '', $option);
                $this->config->set($config_key, $value);
            }
        }
        
        // ============================================
        // SANITIZATION METHODS
        // ============================================
        
        public function sanitize_checkbox_option($input) {
            if (!isset($input)) {
                return '0';
            }
            
            if (is_string($input)) {
                $input = sanitize_text_field($input);
            }
            
            $truthy_values = ['1', 'on', 'yes', 'true', true, 1];
            
            foreach ($truthy_values as $truthy) {
                if ($input === $truthy) {
                    return '1';
                }
            }
            
            return '0';
        }

        /**
         * Sanitize integer with specific bounds
         */
        public function sanitize_integer_bounded($input, $min, $max, $default = 0) {
            if ($input === '' || $input === null || !is_numeric($input)) {
                return $default;
            }
            
            $input = intval($input);
            $input = max($min, $input);
            $input = min($input, $max);
            return $input;
        }

        /**
         * Sanitize perpetual threshold (2-10 range)
         */
        public function sanitize_perpetual_threshold($input) {
            return $this->sanitize_integer_bounded($input, 2, 10, 3);
        }

        /**
         * Sanitize perpetual window (7-365 days)
         */
        public function sanitize_perpetual_window($input) {
            return $this->sanitize_integer_bounded($input, 7, 365, 30);
        }

        /**
         * Sanitize tracking TTL (300-86400 seconds)
         */
        public function sanitize_tracking_ttl($input) {
            return $this->sanitize_integer_bounded($input, 300, 86400, 3600);
        }

        /**
         * FIXED: Sanitize score value (0-10 integer)
         * Used for: botfend_score_suspicious_headers
         */
        public function sanitize_score($input) {
            return $this->sanitize_integer_bounded($input, 0, 10, 2);
        }

        /**
         * FIXED: Sanitize feed retry attempts (0-10)
         * Used for: botfend_feed_retry_attempts
         */
        public function sanitize_feed_retry_attempts($input) {
            return $this->sanitize_integer_bounded($input, 0, 10, 3);
        }

        /**
         * FIXED: Sanitize rate window (60-3600 seconds)
         * Used for: botfend_challenge_rate_window
         */
        public function sanitize_rate_window($input) {
            return $this->sanitize_integer_bounded($input, 60, 3600, 300);
        }

        /**
         * FIXED: Sanitize aggregation hours (1-720 hours)
         * Used for: botfend_aggregate_after_hours
         */
        public function sanitize_aggregation_hours($input) {
            return $this->sanitize_integer_bounded($input, 1, 720, 24);
        }

        /**
         * Sanitize block threshold (5-20)
         */
        public function sanitize_block_threshold($input) {
            return $this->sanitize_integer_bounded($input, 5, 20, 10);
        }

        /**
         * Sanitize rate limit (1-200)
         */
        public function sanitize_rate_limit_bounded($input, $min = 1, $max = 200) {
            return $this->sanitize_integer_bounded($input, $min, $max, 100);
        }

        /**
         * Sanitize block duration (0-720 hours)
         */
        public function sanitize_block_duration_bounded($input) {
            return $this->sanitize_integer_bounded($input, 0, 720, 24);
        }

        /**
         * Sanitize login block duration (0-1440 minutes)
         */
        public function sanitize_login_block_duration_bounded($input) {
            return $this->sanitize_integer_bounded($input, 0, 1440, 15);
        }

        /**
         * Sanitize auto unblock interval (1-168 hours)
         */
        public function sanitize_auto_unblock_interval($input) {
            return $this->sanitize_integer_bounded($input, 1, 168, 24);
        }

        /**
         * Sanitize login window (60-86400 seconds)
         */
        public function sanitize_login_window($input) {
            $input = $this->sanitize_integer_bounded($input, 60, 86400, 900);
            return round($input / 60) * 60;
        }

        public function sanitize_integer_option($input, $min = 0, $max = 1000000) {
            if ($input === '' || $input === null || !is_numeric($input)) {
                return 0;
            }
            
            $input = intval($input);
            $input = max($min, $input);
            return min($input, $max);
        }

        public function sanitize_range_option($input) {
            if ($input === '' || $input === null || !is_numeric($input)) {
                return 0.0;
            }
            
            $input = floatval($input);
            $input = min(max(0.0, $input), 100.0);
            return round($input, 2);
        }
        
        public function sanitize_percentage_option($input) {
            if ($input === '' || $input === null || !is_numeric($input)) {
                return 0.1;
            }
            
            $input = floatval($input);
            $input = min(max(0.0, $input), 1.0);
            return round($input, 3);
        }

        public function sanitize_ip_list($input) {
            if (!is_string($input)) {
                return '';
            }
            
            $lines = explode("\n", sanitize_textarea_field($input));
            $valid_ips = [];
            
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) {
                    continue;
                }
                
                if (strpos($line, '#') === 0) {
                    $valid_ips[] = sanitize_text_field($line);
                    continue;
                }
                
                $dangerous_patterns = [
                    '--', ';', '/*', '*/', 'UNION', 'SELECT', 'INSERT', 
                    'DELETE', 'UPDATE', 'DROP', 'SCRIPT', 'JAVASCRIPT'
                ];
                
                $line_upper = strtoupper($line);
                foreach ($dangerous_patterns as $pattern) {
                    if (strpos($line_upper, $pattern) !== false) {
                        continue 2;
                    }
                }
                
                if (strpos($line, '/') !== false) {
                    $parts = explode('/', $line, 2);
                    if (count($parts) !== 2) {
                        continue;
                    }
                    
                    $ip = sanitize_text_field($parts[0]);
                    $mask = sanitize_text_field($parts[1]);
                    
                    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
                        continue;
                    }
                    
                    $mask_int = intval($mask);
                    $max_mask = (strpos($ip, ':') !== false) ? 128 : 32;
                    if ($mask_int < 0 || $mask_int > $max_mask) {
                        continue;
                    }
                    
                    $valid_ips[] = $ip . '/' . $mask_int;
                } else {
                    $ip = sanitize_text_field($line);
                    if (filter_var($ip, FILTER_VALIDATE_IP)) {
                        $valid_ips[] = $ip;
                    }
                }
            }
            
            return implode("\n", $valid_ips);
        }

        public function sanitize_api_key($input) {
            if (!is_string($input)) {
                return '';
            }
            
            $input = sanitize_text_field($input);
            $input = trim($input);
            
            if (strlen($input) > 256) {
                return '';
            }
            
            $dangerous_patterns = [
                '--', ';', '/*', '*/', 'UNION', 'SELECT', 'INSERT', 
                'DELETE', 'UPDATE', 'DROP', 'SCRIPT', 'JAVASCRIPT'
            ];
            
            $input_upper = strtoupper($input);
            foreach ($dangerous_patterns as $pattern) {
                if (strpos($input_upper, $pattern) !== false) {
                    return '';
                }
            }
            
            if (!preg_match('/^[a-zA-Z0-9_\-\.=]+$/', $input)) {
                return '';
            }
            
            return $input;
        }

        public function sanitize_array_option($input) {
            if (is_string($input)) {
                if (strpos($input, ',') !== false) {
                    $items = array_map('trim', explode(',', $input));
                } else {
                    $items = array_map('trim', explode("\n", $input));
                }
            } elseif (is_array($input)) {
                $items = $input;
            } else {
                return [];
            }
            
            $sanitized = [];
            foreach ($items as $item) {
                $item = sanitize_text_field($item);
                if (!empty($item)) {
                    $sanitized[] = $item;
                }
            }
            
            return array_unique($sanitized);
        }
        
        public function sanitize_proxy_list($input) {
            if (is_string($input)) {
                $lines = explode("\n", $input);
            } elseif (is_array($input)) {
                $lines = $input;
            } else {
                return [];
            }
            
            $valid_proxies = [];
            
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) {
                    continue;
                }
                
                if (strpos($line, '#') === 0) {
                    continue;
                }
                
                if (strpos($line, '/') !== false) {
                    list($ip, $mask) = explode('/', $line, 2);
                    $mask = (int) $mask;
                    
                    if (filter_var($ip, FILTER_VALIDATE_IP) && $mask >= 0 && $mask <= 128) {
                        $valid_proxies[] = $ip . '/' . $mask;
                    }
                } elseif (filter_var($line, FILTER_VALIDATE_IP)) {
                    $valid_proxies[] = $line;
                }
            }
            
            return $valid_proxies;
        }

        public function sanitize_header_list($input) {
            if (!is_array($input)) {
                return [
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_FORWARDED_FOR',
                    'HTTP_X_REAL_IP',
                    'HTTP_CLIENT_IP',
                    'REMOTE_ADDR'
                ];
            }
            
            $valid_headers = [];
            
            foreach ($input as $header) {
                if (!is_string($header)) {
                    continue;
                }
                
                $header = sanitize_text_field($header);
                if (empty($header)) {
                    continue;
                }
                
                if (strpos($header, 'HTTP_') === 0 || $header === 'REMOTE_ADDR') {
                    $valid_headers[] = $header;
                }
            }
            
            if (!in_array('REMOTE_ADDR', $valid_headers, true)) {
                $valid_headers[] = 'REMOTE_ADDR';
            }
            
            return $valid_headers;
        }

        public function sanitize_path_patterns($input) {
            if (!is_string($input)) {
                return '';
            }
            
            $lines = explode("\n", sanitize_textarea_field($input));
            $valid_patterns = [];
            
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) {
                    continue;
                }
                
                if (strpos($line, '#') === 0) {
                    $valid_patterns[] = sanitize_text_field($line);
                    continue;
                }
                
                $dangerous_patterns = [
                    '..', 'php://', 'data://', 'expect://', 'file://', 
                    'phar://', 'ssh2://', 'rar://', 'ogg://', 'zlib://'
                ];
                
                $line_lower = strtolower($line);
                foreach ($dangerous_patterns as $pattern) {
                    if (strpos($line_lower, $pattern) !== false) {
                        continue 2;
                    }
                }
                
                if (strlen($line) > 500) {
                    continue;
                }
                
                $valid_patterns[] = sanitize_text_field($line);
            }
            
            return implode("\n", $valid_patterns);
        }
        
        public function sanitize_country_list($input) {
            if (!is_string($input)) {
                return '';
            }
            
            $countries = preg_split('/[,\n]/', sanitize_text_field($input));
            $valid_countries = array();
            
            foreach ($countries as $country) {
                $country = trim(strtoupper($country));
                if (preg_match('/^[A-Z]{2}$/', $country)) {
                    $valid_countries[] = $country;
                }
            }
            
            return implode(',', array_unique($valid_countries));
        }
        
        public function sanitize_link_density_ratio($input) {
            if ($input === '' || $input === null || !is_numeric($input)) {
                return 0.3;
            }
            
            $input = floatval($input);
            $input = min(max(0.0, $input), 1.0);
            return round($input, 2);
        }
        
        /**
         * Export all settings to JSON
         */
        public function export_settings() {
            $all_settings = [];
            $settings_groups = $this->get_settings_groups();
            
            foreach ($settings_groups as $group => $group_info) {
                foreach ($group_info['options'] as $option_name) {
                    $value = get_option($option_name, false);
                    if ($value !== false) {
                        $all_settings[$option_name] = $value;
                    } else {
                        $config_key = str_replace('botfend_', '', $option_name);
                        $config_value = $this->config->get_string($config_key, '');
                        if ($config_value !== '') {
                            $all_settings[$option_name] = $config_value;
                        }
                    }
                }
            }
            
            $export_data = [
                'plugin' => 'BotFend Anti-Bot Firewall',
                'version' => BOTFEND_VERSION,
                'export_date' => current_time('mysql'),
                'settings' => $all_settings
            ];
            
            $include_sensitive = $this->get_config_bool('export_include_sensitive', false);
            if (!$include_sensitive) {
                $sensitive_keys = [
                    'botfend_iphub_api_key',
                    'botfend_abuseipdb_api_key',
                    'botfend_recaptcha_v3_secret_key',
                    'botfend_recaptcha_v2_secret_key',
                ];
                foreach ($sensitive_keys as $key) {
                    if (isset($all_settings[$key])) {
                        unset($all_settings[$key]);
                    }
                }
            }
            
            return wp_json_encode($export_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        }
        
        /**
         * Import settings from JSON
         */
        public function import_settings($json_data) {
            $data = json_decode($json_data, true);
            
            if (!$data || !isset($data['settings']) || !is_array($data['settings'])) {
                return new WP_Error('invalid_json', esc_html__('Invalid settings file format.', 'botfend-anti-bot-firewall'));
            }
            
            $imported = 0;
            $skipped = 0;
            $settings_groups = $this->get_settings_groups();
            $valid_options = [];
            
            foreach ($settings_groups as $group_info) {
                foreach ($group_info['options'] as $option_name) {
                    $valid_options[] = $option_name;
                }
            }
            
            $merge_strategy = $this->get_config_string('import_merge_strategy', 'merge');
            
            foreach ($data['settings'] as $option_name => $value) {
                if (in_array($option_name, $valid_options)) {
                    if ($merge_strategy === 'skip' && get_option($option_name, false) !== false) {
                        $skipped++;
                        continue;
                    }
                    
                    update_option($option_name, $value);
                    
                    $config_key = str_replace('botfend_', '', $option_name);
                    $this->config->set($config_key, $value);
                    
                    $imported++;
                } else {
                    $skipped++;
                }
            }
            
            $this->config->clear_cache();
            
            return [
                'imported' => $imported,
                'skipped' => $skipped,
                'total' => count($data['settings'])
            ];
        }
        
        /**
         * Reset all settings to defaults
         */
        public function reset_to_defaults() {
            $settings_groups = $this->get_settings_groups();
            
            foreach ($settings_groups as $group_info) {
                foreach ($group_info['options'] as $option_name) {
                    delete_option($option_name);
                    $config_key = str_replace('botfend_', '', $option_name);
                    $this->config->delete($config_key);
                }
            }
            
            $this->config->clear_cache();
            $this->clear_plugin_transients();
            
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('BotFend: All settings reset to defaults');
            }
            
            return true;
        }
        
        /**
         * Clear all plugin transients
         * (Made public so it can be triggered via the admin UI)
         */
        public function clear_plugin_transients() {
            global $wpdb;
            
            $wpdb->query($wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
                $wpdb->esc_like('_transient_botfend_') . '%',
                $wpdb->esc_like('_transient_timeout_botfend_') . '%'
            ));
            
            if (function_exists('wp_cache_flush_group')) {
                wp_cache_flush_group('botfend_defender');
            }
            
            delete_transient('botfend_recent_errors');
        }
        
        private function get_config_string($key, $default = '') {
            return $this->get_config_value($key, $default);
        }
}