<?php
/**
 * Dashboard page handler for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Admin\Pages
 * @version 4.9.2 - Extracted JS to external asset file
 */

namespace BotFend\Admin\Pages;

use BotFend\Core\Config;
use BotFend\Core\Core;
use BotFend\Core\FirewallSetup;

defined('ABSPATH') || exit;

class Dashboard {

    private $core;
    private $database;
    private $config;
    private $wpdb;
    private $advanced_404;
    private $behavioral_analyzer;
    private $threat_intel;
    private $iphub;
    private $abuseipdb;
    private $tor_system;

    public function __construct(Core $core) {
        $this->core = $core;
        $this->config = Config::get_instance();
        global $wpdb;
        $this->wpdb = $wpdb;

        $components = $core->get_components();
        $this->database = $components['database'] ?? null;
        $this->advanced_404 = $components['advanced_404'] ?? null;
        $this->behavioral_analyzer = $components['behavioral_analyzer'] ?? null;
        $this->threat_intel = $components['threat_intel'] ?? null;
        $this->iphub = $components['iphub'] ?? null;
        $this->abuseipdb = $components['abuseipdb'] ?? null;
        $this->tor_system = $components['tor_system'] ?? null;

        add_action('wp_ajax_botfend_refresh_dashboard', [$this, 'ajax_refresh_dashboard']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_dashboard_assets']);
    }

    public function enqueue_dashboard_assets(string $hook): void {
        if (strpos($hook, 'botfend-dashboard') === false) {
            return;
        }

        wp_enqueue_style(
            'botfend-dashboard-css',
            BOTFEND_ASSETS_URL . 'css/botfend-dashboard.css',
            [],
            BOTFEND_VERSION
        );
        
        wp_enqueue_script(
            'botfend-dashboard-js',
            BOTFEND_ASSETS_URL . 'js/dashboard.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );
        
        wp_localize_script('botfend-dashboard-js', 'botfendDashboard', [
            'ajax_url'          => admin_url('admin-ajax.php'),
            'refreshNonce'      => wp_create_nonce('botfend_dashboard_refresh'),
            'threatFeedsNonce'  => wp_create_nonce('botfend_threat_feeds'),
            'torNodesNonce'     => wp_create_nonce('botfend_update_tor_nodes'),
            'refreshText'       => esc_html__('Refresh Data', 'botfend-anti-bot-firewall'),
            'refreshingText'    => esc_html__('Refreshing...', 'botfend-anti-bot-firewall'),
            'refreshSuccess'    => esc_html__('Dashboard refreshed successfully!', 'botfend-anti-bot-firewall'),
            'refreshFailed'     => esc_html__('Failed to refresh data.', 'botfend-anti-bot-firewall'),
            'errorOccurred'     => esc_html__('Error refreshing data.', 'botfend-anti-bot-firewall'),
            'confirmClear'      => esc_html__('Are you sure you want to flush all temporary blocks?', 'botfend-anti-bot-firewall'),
            'confirmCleanLogs'  => esc_html__('Are you sure you want to clean old logs?', 'botfend-anti-bot-firewall'),
            'updatingFeedsText' => esc_html__('Updating Feeds...', 'botfend-anti-bot-firewall'),
            'pleaseWaitText'    => esc_html__('Please wait, this may take up to 60 seconds...', 'botfend-anti-bot-firewall'),
            'unknownErrorText'  => esc_html__('Unknown error occurred.', 'botfend-anti-bot-firewall'),
            'serverTimeoutText' => esc_html__('Server error. Check error logs.', 'botfend-anti-bot-firewall'),
            'requestTimeoutText'=> esc_html__('Request timeout. Try again.', 'botfend-anti-bot-firewall'),
            'updatingTorText'   => esc_html__('Updating TOR Nodes...', 'botfend-anti-bot-firewall'),
        ]);
    }

    private function get_config_bool(string $key, bool $default = false): bool {
        return $this->config->get_bool($key, $default);
    }

    private function get_dashboard_stats(): array {
        if (!$this->database) {
            return $this->get_default_stats();
        }
        return $this->database->get_dashboard_stats();
    }

    private function get_default_stats(): array {
        return [
            'total_requests_7d' => 0,
            'blocked_requests_7d' => 0,
            'active_blocks' => 0,
            'permanent_blocks' => 0,
        ];
    }

    private function get_protection_score(): array {
        $features = [
            'Web Application Firewall' => ['key' => 'enable_waf', 'weight' => 10, 'default' => true, 'tab' => 'waf'],
            'WordPress Protection' => ['key' => 'enable_wp_protection', 'weight' => 10, 'default' => true, 'tab' => 'wordpress'],
            'Disable File Modifications' => ['key' => 'disable_file_mods', 'weight' => 9, 'default' => false, 'tab' => 'file_guard'],
            'Disable Theme/Plugin Editors' => ['key' => 'disable_file_editors', 'weight' => 8, 'default' => false, 'tab' => 'file_guard'],
            'Uploads Execution Protection' => ['key' => 'protect_uploads', 'weight' => 8, 'default' => false, 'tab' => 'file_guard'],
            'Scan Uploaded Files' => ['key' => 'scan_uploads', 'weight' => 8, 'default' => false, 'tab' => 'file_guard'],
            'Monitor File Permissions' => ['key' => 'monitor_permissions', 'weight' => 7, 'default' => false, 'tab' => 'file_guard'],
            'Behavioral Analysis' => ['key' => 'enable_behavioral_analysis', 'weight' => 7, 'default' => true, 'tab' => 'advanced'],
            'Honeypot Traps' => ['key' => 'enable_honeypot', 'weight' => 6, 'default' => true, 'tab' => 'challenges'],
            'XML-RPC Protection' => ['key' => 'disable_xmlrpc', 'weight' => 6, 'default' => false, 'tab' => 'wordpress'],
            'REST API Protection' => ['key' => 'restrict_rest_api', 'weight' => 5, 'default' => true, 'tab' => 'wordpress'],
            'Author Enumeration Protection' => ['key' => 'block_author_scan', 'weight' => 3, 'default' => true, 'tab' => 'wordpress'],
            'Pingback Protection' => ['key' => 'disable_pingbacks', 'weight' => 3, 'default' => false, 'tab' => 'wordpress'],
            '404 Protection' => ['key' => 'enable_advanced_404', 'weight' => 6, 'default' => true, 'tab' => '404_system'],
            'Threat Intelligence' => ['key' => 'enable_threat_intel', 'weight' => 5, 'default' => true, 'tab' => 'advanced'],
            'Signature Detection' => ['key' => 'enable_signatures', 'weight' => 5, 'default' => true, 'tab' => 'advanced'],
            'Session Analysis' => ['key' => 'enable_intelligent_session', 'weight' => 4, 'default' => true, 'tab' => 'advanced'],
            'JavaScript Challenges' => ['key' => 'enable_js_challenge', 'weight' => 3, 'default' => true, 'tab' => 'challenges'],
            'TOR Detection' => ['key' => 'enable_tor_detection', 'weight' => 3, 'default' => true, 'tab' => 'tor_system'],
            'Crawler Verification' => ['key' => 'enable_crawler_verification', 'weight' => 3, 'default' => true, 'tab' => 'third_party'],
            'IPHub' => ['key' => 'enable_iphub', 'weight' => 3, 'default' => false, 'tab' => 'third_party'],
            'AbuseIPDB' => ['key' => 'enable_abuseipdb', 'weight' => 3, 'default' => false, 'tab' => 'third_party'],
            'reCAPTCHA' => ['key' => 'enable_recaptcha', 'weight' => 4, 'default' => false, 'tab' => 'third_party'],
            'Comment Protection' => ['key' => 'enable_comment_protection', 'weight' => 3, 'default' => true, 'tab' => 'wordpress'],
            'Smart Block Duration' => ['key' => 'enable_smart_duration', 'weight' => 2, 'default' => true, 'tab' => 'advanced'],
            'Auto-Unblock' => ['key' => 'enable_auto_unblock', 'weight' => 2, 'default' => true, 'tab' => 'wordpress'],
            'Security Headers' => ['key' => 'add_security_headers', 'weight' => 2, 'default' => true, 'tab' => 'wordpress'],
            'Centralized Logging' => ['key' => 'enable_centralized_logging', 'weight' => 2, 'default' => true, 'tab' => 'general'],
            'Smart Aggregation' => ['key' => 'enable_smart_aggregation', 'weight' => 3, 'default' => true, 'tab' => 'system'],
            'Country Whitelist' => ['key' => 'enable_country_whitelist', 'weight' => 1, 'default' => false, 'tab' => 'wordpress'],
            'Caching' => ['key' => 'enable_cache', 'weight' => 1, 'default' => true, 'tab' => 'system'],
        ];

        $total_weight = 0;
        $earned_weight = 0;
        $active_features = [];
        $inactive_features = [];

        foreach ($features as $label => $feature) {
            $total_weight += $feature['weight'];
            $is_active = $this->get_config_bool($feature['key'], $feature['default']);
            
            if ($is_active) {
                $earned_weight += $feature['weight'];
                $active_features[] = ['label' => $label, 'weight' => $feature['weight'], 'tab' => $feature['tab']];
            } else {
                $inactive_features[] = ['label' => $label, 'weight' => $feature['weight'], 'tab' => $feature['tab']];
            }
        }

        $score_percent = $total_weight > 0 ? round(($earned_weight / $total_weight) * 100) : 0;
        
        if ($score_percent >= 80) {
            $level = 'excellent';
            $level_text = esc_html__('Excellent', 'botfend-anti-bot-firewall');
            $level_color = '#46b450';
        } elseif ($score_percent >= 70) {
            $level = 'good';
            $level_text = esc_html__('Good', 'botfend-anti-bot-firewall');
            $level_color = '#ffb900';
        } elseif ($score_percent >= 50) {
            $level = 'fair';
            $level_text = esc_html__('Fair', 'botfend-anti-bot-firewall');
            $level_color = '#ffa500';
        } else {
            $level = 'poor';
            $level_text = esc_html__('Poor', 'botfend-anti-bot-firewall');
            $level_color = '#dc3232';
        }

        return [
            'score_percent' => $score_percent,
            'earned_weight' => $earned_weight,
            'total_weight' => $total_weight,
            'level' => $level,
            'level_text' => $level_text,
            'level_color' => $level_color,
            'active_count' => count($active_features),
            'total_count' => count($features),
            'active_features' => $active_features,
            'inactive_features' => $inactive_features,
        ];
    }

    private function get_iphub_status(): array {
        if (!$this->iphub) {
            return [
                'enabled' => false,
                'configured' => false,
                'mode' => 'moderate',
                'status' => 'unavailable',
                'status_text' => esc_html__('Not available', 'botfend-anti-bot-firewall'),
                'total_blocks' => 0,
                'last_check' => esc_html__('Never', 'botfend-anti-bot-firewall'),
            ];
        }
        
        $enabled = $this->get_config_bool('enable_iphub', false);
        $api_key = $this->config->get_string('iphub_api_key', '');
        $mode = $this->config->get_string('iphub_mode', 'moderate');
        
        $api_stats = [];
        if (method_exists($this->iphub, 'get_api_statistics')) {
            $api_stats = $this->iphub->get_api_statistics();
        }
        
        $status = 'inactive';
        $status_text = esc_html__('Disabled', 'botfend-anti-bot-firewall');
        
        if ($enabled) {
            if (empty($api_key)) {
                $status = 'warning';
                $status_text = esc_html__('API key missing', 'botfend-anti-bot-firewall');
            } else {
                $status = 'active';
                $status_text = esc_html__('Active', 'botfend-anti-bot-firewall');
            }
        }
        
        $mode_descriptions = [
            'strict' => esc_html__('Strict - Block ALL non-residential IPs', 'botfend-anti-bot-firewall'),
            'moderate' => esc_html__('Moderate - Block ONLY suspicious IPs', 'botfend-anti-bot-firewall'),
            'lenient' => esc_html__('Lenient - Allow all IPs', 'botfend-anti-bot-firewall'),
        ];
        
        return [
            'enabled' => $enabled,
            'configured' => !empty($api_key),
            'mode' => $mode,
            'mode_description' => $mode_descriptions[$mode] ?? ucfirst($mode),
            'status' => $status,
            'status_text' => $status_text,
            'total_blocks' => $api_stats['total_blocks'] ?? 0,
            'last_check' => $api_stats['last_check'] ?? esc_html__('Never', 'botfend-anti-bot-firewall'),
        ];
    }

    private function get_abuseipdb_status(): array {
        if (!$this->abuseipdb) {
            return [
                'enabled' => false,
                'configured' => false,
                'threshold' => 80,
                'action' => 'block',
                'status' => 'unavailable',
                'status_text' => esc_html__('Not available', 'botfend-anti-bot-firewall'),
                'total_blocks' => 0,
                'suspended' => false,
            ];
        }
        
        $enabled = $this->get_config_bool('enable_abuseipdb', false);
        $api_key = $this->config->get_string('abuseipdb_api_key', '');
        $threshold = $this->config->get_int('abuseipdb_confidence', 80);
        $action = $this->config->get_string('abuseipdb_action', 'block');
        
        $circuit_status = [];
        if (method_exists($this->abuseipdb, 'get_circuit_breaker_status')) {
            $circuit_status = $this->abuseipdb->get_circuit_breaker_status();
        }
        
        $api_stats = [];
        if (method_exists($this->abuseipdb, 'get_api_statistics')) {
            $api_stats = $this->abuseipdb->get_api_statistics();
        }
        
        $status = 'inactive';
        $status_text = esc_html__('Disabled', 'botfend-anti-bot-firewall');
        
        if ($enabled) {
            if (empty($api_key)) {
                $status = 'warning';
                $status_text = esc_html__('API key missing', 'botfend-anti-bot-firewall');
            } elseif ($circuit_status['suspended'] ?? false) {
                $status = 'suspended';
                $status_text = esc_html__('Rate limited - Paused', 'botfend-anti-bot-firewall');
            } else {
                $status = 'active';
                $status_text = esc_html__('Active', 'botfend-anti-bot-firewall');
            }
        }
        
        $action_labels = [
            'block' => esc_html__('Block Immediately', 'botfend-anti-bot-firewall'),
            'challenge' => esc_html__('Challenge', 'botfend-anti-bot-firewall'),
            'add_score' => esc_html__('Add to Score', 'botfend-anti-bot-firewall'),
            'log_only' => esc_html__('Log Only', 'botfend-anti-bot-firewall'),
        ];
        
        return [
            'enabled' => $enabled,
            'configured' => !empty($api_key),
            'threshold' => $threshold,
            'action' => $action,
            'action_label' => $action_labels[$action] ?? $action,
            'status' => $status,
            'status_text' => $status_text,
            'suspended' => $circuit_status['suspended'] ?? false,
            'suspended_until' => $circuit_status['suspended_until'] ?? null,
            'total_blocks' => $api_stats['total_blocks'] ?? 0,
            'last_check' => $api_stats['last_check'] ?? esc_html__('Never', 'botfend-anti-bot-firewall'),
        ];
    }

    private function get_tor_status(): array {
        if (!$this->tor_system) {
            return [
                'enabled' => false,
                'status' => 'unavailable',
                'status_text' => esc_html__('Not available', 'botfend-anti-bot-firewall'),
                'node_count' => 0,
                'action' => 'challenge',
                'action_label' => esc_html__('Challenge', 'botfend-anti-bot-firewall'),
                'score' => 4,
                'last_update' => esc_html__('Never', 'botfend-anti-bot-firewall'),
                'last_update_raw' => 0,
            ];
        }
        
        $tor_data = $this->tor_system->get_status();
        
        $status = 'inactive';
        $status_text = esc_html__('Disabled', 'botfend-anti-bot-firewall');
        
        if ($tor_data['enabled']) {
            if ($tor_data['node_count'] > 0) {
                $status = 'active';
                $status_text = esc_html__('Active', 'botfend-anti-bot-firewall');
            } else {
                $status = 'warning';
                $status_text = esc_html__('No nodes loaded', 'botfend-anti-bot-firewall');
            }
        }
        
        $action_labels = [
            'block' => esc_html__('Block', 'botfend-anti-bot-firewall'),
            'challenge' => esc_html__('Challenge', 'botfend-anti-bot-firewall'),
            'add_score' => esc_html__('Add Score', 'botfend-anti-bot-firewall'),
            'log_only' => esc_html__('Log Only', 'botfend-anti-bot-firewall'),
        ];
        
        $last_update = $tor_data['last_update'] ?? 0;
        $last_update_display = $last_update > 0 
            ? human_time_diff($last_update, time()) . ' ' . esc_html__('ago', 'botfend-anti-bot-firewall')
            : esc_html__('Never', 'botfend-anti-bot-firewall');
        
        return [
            'enabled' => $tor_data['enabled'],
            'status' => $status,
            'status_text' => $status_text,
            'node_count' => $tor_data['node_count'] ?? 0,
            'action' => $tor_data['action'] ?? 'challenge',
            'action_label' => $action_labels[$tor_data['action'] ?? 'challenge'] ?? esc_html__('Challenge', 'botfend-anti-bot-firewall'),
            'score' => $tor_data['score'] ?? 4,
            'last_update' => $last_update_display,
            'last_update_raw' => $last_update,
        ];
    }

    public function ajax_refresh_dashboard(): void {
        check_ajax_referer('botfend_dashboard_refresh', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Insufficient permissions', 'botfend-anti-bot-firewall')], 403);
        }

        $stats = $this->get_dashboard_stats();
        $protection = $this->get_protection_score();

        wp_send_json_success([
            'stats' => $stats,
            'protection' => $protection,
            'timestamp' => current_time('mysql'),
        ]);
    }

    public function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'botfend-anti-bot-firewall'));
        }

        $stats = $this->get_dashboard_stats();
        $protection = $this->get_protection_score();
        $utilities = $this->core->get_utilities();

        $stats_404 = ['total_404s' => 0, 'unique_ips' => 0, 'top_offenders' => [], 'crawler_404s' => 0, 'avg_score' => 0];
        if ($this->advanced_404 && method_exists($this->advanced_404, 'get_statistics')) {
            $stats_404 = $this->advanced_404->get_statistics(24);
        }
        $top_5_offenders = array_slice($stats_404['top_offenders'] ?? [], 0, 5);
        $top_attacker_ip = !empty($top_5_offenders) ? $top_5_offenders[0]['ip'] : false;
        $crawler_404s = $stats_404['crawler_404s'] ?? 0;

        $stats_behavior = ['active_tracking' => 0, 'common_patterns' => [], 'avg_behavior_score' => 0];
        if ($this->behavioral_analyzer && method_exists($this->behavioral_analyzer, 'get_statistics')) {
            $stats_behavior = $this->behavioral_analyzer->get_statistics();
        }

        $is_ti_enabled = $this->get_config_bool('enable_threat_intel', true);
        $stats_ti = ['total_feeds' => 0, 'enabled_feeds' => 0, 'total_entries' => 0, 'feeds' => [], 'last_overall_update' => esc_html__('Never', 'botfend-anti-bot-firewall')];
        if ($this->threat_intel && method_exists($this->threat_intel, 'get_feed_statistics')) {
            $dynamic_ti_stats = $this->threat_intel->get_feed_statistics();
            $stats_ti = array_merge($stats_ti, $dynamic_ti_stats);
        }

        $iphub_status = $this->get_iphub_status();
        $abuseipdb_status = $this->get_abuseipdb_status();
        $tor_status = $this->get_tor_status();

        $firewall_setup = new FirewallSetup($this->config, $utilities);
        $fw_status_data = $firewall_setup->get_status();
        $fw_mode = $fw_status_data['mode'];

        $fw_color = '#dc3232';
        $fw_text = esc_html__('No Protection', 'botfend-anti-bot-firewall');
        $fw_icon = 'dashicons-shield-off';
        $fw_bg = '#fde7e7';

        if ($fw_mode === 'full') {
            $fw_color = '#46b450';
            $fw_text = esc_html__('Full Protection', 'botfend-anti-bot-firewall');
            $fw_icon = 'dashicons-shield-alt';
            $fw_bg = '#e7f5e8';
        } elseif ($fw_mode === 'basic') {
            $fw_color = '#ffb900';
            $fw_text = esc_html__('Basic Protection', 'botfend-anti-bot-firewall');
            $fw_icon = 'dashicons-shield';
            $fw_bg = '#fff3e0';
        }
        ?>
        <div class="wrap botfend-dashboard-wrap">
            <div class="botfend-dashboard-header">
                <div class="botfend-header-title-wrap">
                    <h1 class="botfend-page-title">
                        <?php echo esc_html__('BotFend Anti-Bot Firewall', 'botfend-anti-bot-firewall'); ?>
                    </h1>
                    <span class="botfend-version-badge">v<?php echo esc_attr(BOTFEND_VERSION); ?></span>
                </div>
                <div class="botfend-header-actions">
                    <button type="button" class="button botfend-refresh-dashboard">
                        <span class="dashicons dashicons-update"></span>
                        <?php esc_html_e('Refresh Data', 'botfend-anti-bot-firewall'); ?>
                    </button>
                </div>
            </div>

            <div class="botfend-central-firewall-banner" style="background-color: <?php echo esc_attr($fw_bg); ?>; border: 1px solid <?php echo esc_attr($fw_color); ?>;">
                <div class="botfend-cfb-content">
                    <span class="dashicons <?php echo esc_attr($fw_icon); ?>" style="color: <?php echo esc_attr($fw_color); ?>;"></span>
                    <div class="botfend-cfb-text">
                        <h2><?php esc_html_e('Firewall Status', 'botfend-anti-bot-firewall'); ?></h2>
                        <p>
                            <?php esc_html_e('Mode:', 'botfend-anti-bot-firewall'); ?> 
                            <strong style="color: <?php echo esc_attr($fw_color); ?>"><?php echo esc_html($fw_text); ?></strong>
                        </p>
                    </div>
                </div>
                <div class="botfend-cfb-action">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-firewall')); ?>" class="button button-primary botfend-fw-btn" style="background-color: <?php echo esc_attr($fw_color); ?>; border-color: <?php echo esc_attr($fw_color); ?>;">
                        <?php esc_html_e('Manage Firewall', 'botfend-anti-bot-firewall'); ?>
                    </a>
                </div>
            </div>

            <div class="botfend-protection-card">
                <div class="botfend-protection-header">
                    <span class="dashicons dashicons-shield-alt"></span>
                    <h2><?php echo esc_html__('Protection Health Score', 'botfend-anti-bot-firewall'); ?></h2>
                </div>
                
                <div class="botfend-protection-body">
                    <div class="botfend-score-container">
                        <div class="botfend-score-circle" style="--score: <?php echo esc_attr($protection['score_percent']); ?>">
                            <svg viewBox="0 0 100 100">
                                <circle cx="50" cy="50" r="45" fill="none" stroke="#e5e5e5" stroke-width="8"/>
                                <circle cx="50" cy="50" r="45" fill="none" stroke="<?php echo esc_attr($protection['level_color']); ?>" stroke-width="8" 
                                        stroke-dasharray="283" stroke-dashoffset="<?php echo esc_attr(283 - (283 * $protection['score_percent'] / 100)); ?>" 
                                        stroke-linecap="round" transform="rotate(-90 50 50)"/>
                            </svg>
                            <div class="botfend-score-text">
                                <span class="botfend-score-value"><?php echo esc_html($protection['score_percent']); ?>%</span>
                                <span class="botfend-score-level" style="color: <?php echo esc_attr($protection['level_color']); ?>">
                                    <?php echo esc_html($protection['level_text']); ?>
                                </span>
                            </div>
                        </div>
                        
                        <div class="botfend-score-stats">
                            <div class="botfend-stat-item">
                                <span class="botfend-stat-label"><?php echo esc_html__('Active Features', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="botfend-stat-number"><?php echo esc_html($protection['active_count']); ?> / <?php echo esc_html($protection['total_count']); ?></span>
                            </div>
                            <div class="botfend-stat-item">
                                <span class="botfend-stat-label"><?php echo esc_html__('Weighted Score', 'botfend-anti-bot-firewall'); ?></span>
                                <span class="botfend-stat-number"><?php echo esc_html($protection['earned_weight']); ?> / <?php echo esc_html($protection['total_weight']); ?></span>
                            </div>
                        </div>
                    </div>

                    <div class="botfend-quick-stats">
                        <div class="botfend-quick-stat">
                            <span class="dashicons dashicons-chart-line"></span>
                            <div>
                                <div class="botfend-quick-stat-value"><?php echo esc_html(number_format_i18n($stats['total_requests_7d'] ?? 0)); ?></div>
                                <div class="botfend-quick-stat-label"><?php echo esc_html__('Total Requests (7d)', 'botfend-anti-bot-firewall'); ?></div>
                            </div>
                        </div>
                        <div class="botfend-quick-stat">
                            <span class="dashicons dashicons-shield"></span>
                            <div>
                                <div class="botfend-quick-stat-value"><?php echo esc_html(number_format_i18n($stats['blocked_requests_7d'] ?? 0)); ?></div>
                                <div class="botfend-quick-stat-label"><?php echo esc_html__('Blocked Requests (7d)', 'botfend-anti-bot-firewall'); ?></div>
                            </div>
                        </div>
                        <div class="botfend-quick-stat">
                            <span class="dashicons dashicons-lock"></span>
                            <div>
                                <div class="botfend-quick-stat-value"><?php echo esc_html(number_format_i18n($stats['active_blocks'] ?? 0)); ?></div>
                                <div class="botfend-quick-stat-label"><?php echo esc_html__('Active Blocks', 'botfend-anti-bot-firewall'); ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="botfend-threat-intel-card">
                <div class="botfend-card-header">
                    <span class="dashicons dashicons-hidden"></span>
                    <h3><?php echo esc_html__('TOR Network Detection', 'botfend-anti-bot-firewall'); ?></h3>
                </div>
                <div class="botfend-threat-intel-body">
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px;">
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">
                                <span class="dashicons dashicons-privacy" style="color: #7b4397;"></span>
                                <strong style="font-size: 15px;"><?php echo esc_html__('TOR Exit Nodes', 'botfend-anti-bot-firewall'); ?></strong>
                                <?php if ($tor_status['enabled']): ?>
                                    <?php if ($tor_status['status'] === 'active'): ?>
                                        <span style="margin-left: auto; background: #d4edda; color: #155724; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✓ <?php echo esc_html__('Active', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php elseif ($tor_status['status'] === 'warning'): ?>
                                        <span style="margin-left: auto; background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">⚠ <?php echo esc_html__('No Nodes', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span style="margin-left: auto; background: #f8d7da; color: #721c24; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✗ <?php echo esc_html__('Disabled', 'botfend-anti-bot-firewall'); ?></span>
                                <?php endif; ?>
                            </div>
                            <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                <strong><?php echo esc_html__('Action:', 'botfend-anti-bot-firewall'); ?></strong> 
                                <?php echo esc_html($tor_status['action_label']); ?>
                                <?php if ($tor_status['action'] === 'add_score'): ?>
                                    <span style="color: #2271b1;">(+<?php echo esc_html($tor_status['score']); ?>)</span>
                                <?php endif; ?>
                            </div>
                            <?php if ($tor_status['enabled']): ?>
                                <div style="font-size: 28px; font-weight: 600; color: #7b4397; margin: 12px 0 8px;"><?php echo esc_html(number_format_i18n($tor_status['node_count'])); ?></div>
                                <div style="font-size: 12px; color: #646970; margin-bottom: 8px;"><?php echo esc_html__('Exit nodes loaded', 'botfend-anti-bot-firewall'); ?></div>
                                <div style="font-size: 13px; color: #555;">
                                    <strong><?php echo esc_html__('Last Updated:', 'botfend-anti-bot-firewall'); ?></strong> 
                                    <?php echo esc_html($tor_status['last_update']); ?>
                                </div>
                            <?php endif; ?>
                            <div style="margin-top: 12px;">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=tor_system')); ?>" class="button button-small"><?php echo esc_html__('Configure TOR', 'botfend-anti-bot-firewall'); ?></a>
                                <?php if ($tor_status['enabled'] && $tor_status['node_count'] === 0): ?>
                                    <button type="button" class="button button-small botfend-update-tor-nodes" style="margin-left: 8px;">
                                        <span class="dashicons dashicons-update" style="font-size: 14px; vertical-align: middle;"></span>
                                        <?php echo esc_html__('Load Nodes', 'botfend-anti-bot-firewall'); ?>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">
                                <span class="dashicons dashicons-info" style="color: #2271b1;"></span>
                                <strong style="font-size: 15px;"><?php echo esc_html__('How TOR Detection Works', 'botfend-anti-bot-firewall'); ?></strong>
                            </div>
                            <ul style="margin: 0; padding-left: 20px; color: #555; font-size: 13px; line-height: 1.6;">
                                <li><?php echo esc_html__('Detects traffic from TOR exit nodes', 'botfend-anti-bot-firewall'); ?></li>
                                <li><?php echo esc_html__('Updates from official Tor Project list', 'botfend-anti-bot-firewall'); ?></li>
                                <li><?php echo esc_html__('Configurable action per TOR visitor', 'botfend-anti-bot-firewall'); ?></li>
                                <?php if ($tor_status['action'] === 'challenge'): ?>
                                    <li style="color: #2271b1;">✓ <?php echo esc_html__('Users can verify to bypass', 'botfend-anti-bot-firewall'); ?></li>
                                <?php elseif ($tor_status['action'] === 'block'): ?>
                                    <li style="color: #dc3232;">⛔ <?php echo esc_html__('All TOR traffic is blocked', 'botfend-anti-bot-firewall'); ?></li>
                                <?php elseif ($tor_status['action'] === 'add_score'): ?>
                                    <li style="color: #ffb900;">⚠ <?php echo esc_html__('Adds to threat score', 'botfend-anti-bot-firewall'); ?></li>
                                <?php elseif ($tor_status['action'] === 'log_only'): ?>
                                    <li style="color: #646970;">📋 <?php echo esc_html__('Logging only - no action', 'botfend-anti-bot-firewall'); ?></li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <div class="botfend-threat-intel-card">
                <div class="botfend-card-header">
                    <span class="dashicons dashicons-networking"></span>
                    <h3><?php echo esc_html__('Third-Party Services', 'botfend-anti-bot-firewall'); ?></h3>
                </div>
                <div class="botfend-threat-intel-body">
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px;">
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">
                                <span class="dashicons dashicons-cloud" style="color: #2271b1;"></span>
                                <strong style="font-size: 15px;"><?php echo esc_html__('IPHub.info', 'botfend-anti-bot-firewall'); ?></strong>
                                <?php if ($iphub_status['enabled']): ?>
                                    <?php if ($iphub_status['status'] === 'active'): ?>
                                        <span style="margin-left: auto; background: #d4edda; color: #155724; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✓ <?php echo esc_html__('Active', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php elseif ($iphub_status['status'] === 'warning'): ?>
                                        <span style="margin-left: auto; background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">⚠ <?php echo esc_html__('Needs API Key', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span style="margin-left: auto; background: #f8d7da; color: #721c24; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✗ <?php echo esc_html__('Disabled', 'botfend-anti-bot-firewall'); ?></span>
                                <?php endif; ?>
                            </div>
                            <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                <strong><?php echo esc_html__('Mode:', 'botfend-anti-bot-firewall'); ?></strong> 
                                <?php echo esc_html($iphub_status['mode_description']); ?>
                            </div>
                            <?php if ($iphub_status['enabled'] && $iphub_status['configured']): ?>
                                <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                    <strong><?php echo esc_html__('Blocks:', 'botfend-anti-bot-firewall'); ?></strong> 
                                    <?php echo esc_html(number_format_i18n($iphub_status['total_blocks'])); ?>
                                </div>
                            <?php endif; ?>
                            <div style="margin-top: 12px;">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=third_party')); ?>" class="button button-small"><?php echo esc_html__('Configure', 'botfend-anti-bot-firewall'); ?></a>
                            </div>
                        </div>
                        <div style="background: #f8f9fa; border-radius: 8px; padding: 16px;">
                            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">
                                <span class="dashicons dashicons-shield" style="color: #2271b1;"></span>
                                <strong style="font-size: 15px;"><?php echo esc_html__('AbuseIPDB', 'botfend-anti-bot-firewall'); ?></strong>
                                <?php if ($abuseipdb_status['enabled']): ?>
                                    <?php if ($abuseipdb_status['status'] === 'active'): ?>
                                        <span style="margin-left: auto; background: #d4edda; color: #155724; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✓ <?php echo esc_html__('Active', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php elseif ($abuseipdb_status['status'] === 'suspended'): ?>
                                        <span style="margin-left: auto; background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">⏸ <?php echo esc_html__('Rate Limited', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php elseif ($abuseipdb_status['status'] === 'warning'): ?>
                                        <span style="margin-left: auto; background: #fff3cd; color: #856404; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">⚠ <?php echo esc_html__('Needs API Key', 'botfend-anti-bot-firewall'); ?></span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span style="margin-left: auto; background: #f8d7da; color: #721c24; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">✗ <?php echo esc_html__('Disabled', 'botfend-anti-bot-firewall'); ?></span>
                                <?php endif; ?>
                            </div>
                            <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                <strong><?php echo esc_html__('Threshold:', 'botfend-anti-bot-firewall'); ?></strong> <?php echo esc_html($abuseipdb_status['threshold']); ?>%
                            </div>
                            <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                <strong><?php echo esc_html__('Action:', 'botfend-anti-bot-firewall'); ?></strong> <?php echo esc_html($abuseipdb_status['action_label']); ?>
                            </div>
                            <?php if ($abuseipdb_status['enabled'] && $abuseipdb_status['configured']): ?>
                                <div style="font-size: 13px; color: #555; margin-bottom: 8px;">
                                    <strong><?php echo esc_html__('Blocks:', 'botfend-anti-bot-firewall'); ?></strong> 
                                    <?php echo esc_html(number_format_i18n($abuseipdb_status['total_blocks'])); ?>
                                </div>
                                <?php if ($abuseipdb_status['suspended']): ?>
                                    <div style="font-size: 13px; color: #856404; background: #fff3cd; padding: 6px 10px; border-radius: 4px; margin-top: 8px;">
                                        <span class="dashicons dashicons-clock"></span>
                                        <?php echo esc_html__('Resumes:', 'botfend-anti-bot-firewall'); ?> <?php echo esc_html($abuseipdb_status['suspended_until']); ?>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                            <div style="margin-top: 12px;">
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=third_party')); ?>" class="button button-small"><?php echo esc_html__('Configure', 'botfend-anti-bot-firewall'); ?></a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="botfend-threat-intel-card">
                <div class="botfend-card-header">
                    <span class="dashicons dashicons-visibility"></span>
                    <h3><?php echo esc_html__('Behavioral Analysis (Live Buffer)', 'botfend-anti-bot-firewall'); ?></h3>
                </div>
                <div class="botfend-threat-intel-body">
                    <?php if ($stats_behavior['active_tracking'] > 0 || !empty($stats_behavior['common_patterns'])): ?>
                        <div class="botfend-threat-summary-banner notice-info notice-alt">
                            <p>
                                <?php printf(esc_html__('BotFend is currently analyzing %1$s active sessions in real-time. The average behavioral score is %2$s/10.', 'botfend-anti-bot-firewall'), '<strong>' . esc_html(number_format_i18n($stats_behavior['active_tracking'])) . '</strong>', '<strong>' . esc_html($stats_behavior['avg_behavior_score'] ?? '0') . '</strong>'); ?>
                            </p>
                        </div>
                        <?php if (!empty($stats_behavior['common_patterns'])): ?>
                            <table class="wp-list-table widefat fixed striped">
                                <thead>
                                    <tr><th><?php echo esc_html__('Detected Behavior Pattern', 'botfend-anti-bot-firewall'); ?></th><th><?php echo esc_html__('Live Occurrences', 'botfend-anti-bot-firewall'); ?></th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($stats_behavior['common_patterns'] as $pattern): ?>
                                        <tr><td><code><?php echo esc_html(str_replace('_', ' ', ucfirst($pattern['pattern']))); ?></code></td><td><?php echo esc_html(number_format_i18n($pattern['count'])); ?></td></tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="botfend-threat-summary-banner notice-success notice-alt">
                            <p><?php esc_html_e('No suspicious automated behavior detected in the live buffer. Your site is secure!', 'botfend-anti-bot-firewall'); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="botfend-threat-intel-card">
                <div class="botfend-card-header">
                    <span class="dashicons dashicons-cloud"></span>
                    <h3><?php echo esc_html__('Global Threat Intelligence', 'botfend-anti-bot-firewall'); ?></h3>
                </div>
                <div class="botfend-threat-intel-body">
                    <?php if ($is_ti_enabled): ?>
                        <?php if ($stats_ti['total_entries'] > 0): ?>
                            <div class="botfend-threat-summary-banner notice-success notice-alt" style="border-left-color: #46b450; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px;">
                                <div>
                                    <p style="margin: 0; font-size: 14px;">
                                        <strong><?php echo esc_html(number_format_i18n($stats_ti['total_entries'])); ?></strong> <?php esc_html_e('known malicious IPs loaded in active memory.', 'botfend-anti-bot-firewall'); ?>
                                    </p>
                                </div>
                            </div>
                            <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #e5e5e5; display: flex; align-items: center; flex-wrap: wrap; gap: 10px;">
                                <button type="button" id="botfend-refresh-threat-feeds" class="button button-primary">
                                    <span class="dashicons dashicons-update"></span><?php esc_html_e('Refresh Threat Feeds Now', 'botfend-anti-bot-firewall'); ?>
                                </button>
                                <span id="botfend-threat-feed-status" style="font-weight: 500;"></span>
                            </div>
                        <?php else: ?>
                            <div class="botfend-threat-summary-banner notice-info notice-alt">
                                <p><?php esc_html_e('Global Threat Intelligence is enabled and initializing.', 'botfend-anti-bot-firewall'); ?></p>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="botfend-threat-summary-banner notice-warning notice-alt">
                            <p><?php esc_html_e('Global Threat Intelligence feeds are disabled.', 'botfend-anti-bot-firewall'); ?></p>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=advanced')); ?>" class="button button-small"><?php esc_html_e('Enable Feeds', 'botfend-anti-bot-firewall'); ?></a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="botfend-threat-intel-card">
                <div class="botfend-card-header">
                    <span class="dashicons dashicons-analytics"></span>
                    <h3><?php echo esc_html__('404 Threat Intelligence (24h)', 'botfend-anti-bot-firewall'); ?></h3>
                </div>
                <div class="botfend-threat-intel-body">
                    <?php if ($stats_404['total_404s'] > 0): ?>
                        <div class="botfend-threat-summary-banner notice-warning notice-alt">
                            <p><?php printf(esc_html__('BotFend has protected your site from %1$s malicious 404 probes in the last 24 hours, originating from %2$s unique IP addresses.', 'botfend-anti-bot-firewall'), '<strong>' . esc_html(number_format_i18n($stats_404['total_404s'])) . '</strong>', '<strong>' . esc_html(number_format_i18n($stats_404['unique_ips'])) . '</strong>'); ?></p>
                            <?php if ($crawler_404s > 0): ?>
                                <p style="margin-top: 8px; color: #2271b1;"><?php printf(esc_html__('%s crawler 404s logged (SEO monitoring).', 'botfend-anti-bot-firewall'), '<strong>' . esc_html(number_format_i18n($crawler_404s)) . '</strong>'); ?></p>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <div class="botfend-threat-summary-banner notice-success notice-alt">
                            <p><?php esc_html_e('No malicious 404 probes detected in the last 24 hours. Your site is secure!', 'botfend-anti-bot-firewall'); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="botfend-actions-row">
                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings')); ?>" class="botfend-action-btn"><span class="dashicons dashicons-admin-settings"></span><?php echo esc_html__('Settings', 'botfend-anti-bot-firewall'); ?></a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-blocklist')); ?>" class="botfend-action-btn"><span class="dashicons dashicons-shield"></span><?php echo esc_html__('Blocklist', 'botfend-anti-bot-firewall'); ?></a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-logs')); ?>" class="botfend-action-btn"><span class="dashicons dashicons-media-document"></span><?php echo esc_html__('View Logs', 'botfend-anti-bot-firewall'); ?></a>
                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-unblock-requests')); ?>" class="botfend-action-btn"><span class="dashicons dashicons-flag"></span><?php echo esc_html__('Unblock Requests', 'botfend-anti-bot-firewall'); ?></a>
            </div>

            <?php if (!empty($protection['inactive_features'])): 
                usort($protection['inactive_features'], function($a, $b) { return $b['weight'] - $a['weight']; });
                $top_missing = array_slice($protection['inactive_features'], 0, 6);
            ?>
            <div class="botfend-recommendations-card">
                <div class="botfend-card-header"><span class="dashicons dashicons-megaphone"></span><h3><?php echo esc_html__('Recommendations', 'botfend-anti-bot-firewall'); ?></h3></div>
                <div class="botfend-recommendations-list">
                    <?php foreach ($top_missing as $feature): ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-settings&tab=' . $feature['tab'])); ?>" class="botfend-recommendation-item">
                            <div class="botfend-rec-left"><span class="dashicons dashicons-warning"></span><span class="botfend-rec-label"><?php echo esc_html($feature['label']); ?></span></div>
                            <div class="botfend-rec-right"><span class="botfend-recommendation-weight">+<?php echo esc_html($feature['weight']); ?> pts</span></div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="botfend-tools-card">
                <div class="botfend-card-header"><span class="dashicons dashicons-admin-tools"></span><h3><?php echo esc_html__('Admin Tools', 'botfend-anti-bot-firewall'); ?></h3></div>
                <div class="botfend-tools-list">
                    <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=botfend-blocklist&action=flush'), 'botfend_admin_action')); ?>" class="botfend-tool-item botfend-confirm-action" data-confirm="<?php echo esc_attr__('Flush all temporary blocks?', 'botfend-anti-bot-firewall'); ?>"><span class="dashicons dashicons-trash"></span><?php echo esc_html__('Clear Temp Blocks', 'botfend-anti-bot-firewall'); ?></a>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-logs&action=cleanup')); ?>" class="botfend-tool-item"><span class="dashicons dashicons-update"></span><?php echo esc_html__('Clean Old Logs', 'botfend-anti-bot-firewall'); ?></a>
                </div>
            </div>
        </div>
        <?php
    }
}