<?php
/**
 * Blocklist page handler for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Admin\Pages
 * @version 4.8.3 - Fixed SQL escaping for table names
 */

namespace BotFend\Admin\Pages;

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

defined('ABSPATH') || exit;

class Blocklist {

    private $core;
    private $database;
    private $utilities;
    private $config;
    private $wpdb;
    private $perpetual_enabled;
    private $perpetual_threshold;
    private $perpetual_window;

    const REMOVE_TEMP_ON_PERMANENT = true;
    const SYNC_TO_DATABASE = true;

    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->utilities = $components['utilities'] ?? null;

        $this->perpetual_enabled = $this->get_config_bool('perpetual_enabled', true);
        $this->perpetual_threshold = $this->get_config_int('perpetual_threshold', 3);
        $this->perpetual_window = $this->get_config_int('perpetual_window', 30);

        add_action('admin_init', [$this, 'prevent_autofocus_after_actions']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_blocklist_assets']);
    }

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

        wp_enqueue_style(
            'botfend-blocklist-css', 
            BOTFEND_ASSETS_URL . 'css/botfend-blocklist.css', 
            ['botfend-admin-css'], 
            BOTFEND_VERSION
        );
        
        wp_enqueue_script(
            'botfend-blocklist-js',
            BOTFEND_ASSETS_URL . 'js/blocklist.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );
        
        wp_localize_script('botfend-blocklist-js', 'botfendBlocklist', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('botfend_admin_action'),
            'selectItems' => esc_html__('Please select at least one IP or range to unblock.', 'botfend-anti-bot-firewall'),
            'confirmUnblock' => esc_html__('Are you sure you want to unblock the selected IP(s)/ranges?', 'botfend-anti-bot-firewall'),
            'confirmPermanent' => esc_html__('Make this block permanent? It will never expire.', 'botfend-anti-bot-firewall'),
            'confirmMakePermanent' => esc_html__('Are you sure you want to make this block permanent?', 'botfend-anti-bot-firewall'),
            'unblockSuccess' => esc_html__('IP/range unblocked successfully.', 'botfend-anti-bot-firewall'),
            'unblockError' => esc_html__('Failed to unblock IP/range.', 'botfend-anti-bot-firewall'),
            'permanentSuccess' => esc_html__('Added to permanent blocklist.', 'botfend-anti-bot-firewall'),
            'permanentError' => esc_html__('Failed to add to permanent blocklist.', 'botfend-anti-bot-firewall'),
            'processing' => esc_html__('Processing...', 'botfend-anti-bot-firewall'),
            'preventAutofocus' => get_transient('botfend_prevent_autofocus') ? '1' : '0',
        ]);
    }

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

    private function get_config_int(string $key, int $default = 0): int {
        return $this->config->get_int($key, $default);
    }

    private function get_config_string(string $key, string $default = ''): string {
        return $this->config->get_string($key, $default);
    }

    private function get_block_duration(): int {
        return $this->get_config_int('block_duration', 24);
    }

    public function prevent_autofocus_after_actions(): void {
        if (isset($_GET['page']) && $_GET['page'] === 'botfend-blocklist') {
            if (isset($_GET['action']) || isset($_GET['manual_block']) ||
                (isset($_POST['botfend_bulk_action']) && $_POST['botfend_bulk_action'] === 'unblock')) {
                set_transient('botfend_prevent_autofocus', '1', 30);
            }
        }
    }

    private function is_valid_cidr(string $cidr): bool {
        if (strpos($cidr, '/') === false) return false;
        $parts = explode('/', $cidr);
        if (count($parts) !== 2) return false;
        $ip = $parts[0];
        $mask = intval($parts[1]);
        if (!filter_var($ip, FILTER_VALIDATE_IP)) return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) return $mask >= 0 && $mask <= 32;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) return $mask >= 0 && $mask <= 128;
        return false;
    }

    private function is_perpetual_offender(string $ip): bool {
        if (!$this->perpetual_enabled) return false;
        $blocklist_table = $this->wpdb->prefix . 'botfend_blocklist';
        $escaped_table = esc_sql($blocklist_table);
        $window = gmdate('Y-m-d H:i:s', strtotime('-' . $this->perpetual_window . ' days'));
        $count = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT COUNT(*) FROM `{$escaped_table}` WHERE ip = %s AND created_at >= %s AND type != 'permanent_manual' AND type != 'perpetual_offender'",
            $ip, $window
        ));
        return (int) $count >= $this->perpetual_threshold;
    }

    private function flag_perpetual_offender(string $ip, int $block_id): bool {
        $blocklist_table = $this->wpdb->prefix . 'botfend_blocklist';
        $escaped_table = esc_sql($blocklist_table);
        $already_flagged = $this->wpdb->get_var($this->wpdb->prepare(
            "SELECT is_perpetual_offender FROM `{$escaped_table}` WHERE id = %d", $block_id
        ));
        if ($already_flagged) return false;
        $result = $this->wpdb->update($blocklist_table, [
            'is_perpetual_offender' => 1,
            'type' => 'perpetual_offender',
            'reason' => sprintf(
                /* translators: 1: threshold count, 2: window in days */
                esc_html__('Perpetual offender - blocked %1$d+ times in last %2$d days', 'botfend-anti-bot-firewall'),
                $this->perpetual_threshold,
                $this->perpetual_window
            )
        ], ['id' => $block_id], ['%d', '%s', '%s'], ['%d']);
        return $result !== false;
    }

    private function check_and_flag_perpetual_offender(string $ip, int $block_id): bool {
        if (!$this->perpetual_enabled) return false;
        if ($this->is_perpetual_offender($ip)) return $this->flag_perpetual_offender($ip, $block_id);
        return false;
    }

    private function add_to_permanent_blocklist(string $ip): bool {
        $ip = trim($ip);
        if (empty($ip)) return false;
        $is_valid = filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip);
        if (!$is_valid) return false;
        if (strpos($ip, ':') !== false && strpos($ip, '/') === false) $ip = strtolower($ip);

        $current_list = (string) get_option('botfend_permanent_blocklist', '');
        $lines = [];
        if ('' !== trim($current_list)) {
            $lines = explode("\n", str_replace("\r\n", "\n", $current_list));
            $lines = array_map('trim', $lines);
            $lines = array_filter($lines, function($line) { return '' !== $line && 0 !== strpos($line, '#'); });
            $lines = array_values($lines);
        }
        $option_updated = false;
        if (!in_array($ip, $lines, true)) {
            $lines[] = $ip;
            $lines = array_values(array_unique($lines));
            if (count($lines) > 10000) return false;
            $new_list = implode("\n", $lines);
            $option_updated = update_option('botfend_permanent_blocklist', $new_list, false);
        } else {
            $option_updated = true;
        }

        $blocklist_table = $this->wpdb->prefix . 'botfend_blocklist';
        $escaped_table = esc_sql($blocklist_table);
        $exists = $this->wpdb->get_var($this->wpdb->prepare("SELECT id FROM `{$escaped_table}` WHERE ip = %s", $ip));
        $db_updated = false;
        if ($exists) {
            $result = $this->wpdb->update($blocklist_table, ['type' => 'permanent_manual', 'expires' => null], ['id' => $exists], ['%s', '%s'], ['%d']);
            $db_updated = ($result !== false);
        } else {
            $country = sanitize_text_field($this->utilities->get_country($ip));
            $db_updated = $this->database->block_ip($ip, 'permanent_manual', esc_html__('Permanently blocked by admin', 'botfend-anti-bot-firewall'), 10, 0, $country);
        }
        return $option_updated || $db_updated;
    }

    private function format_block_type(string $type): string {
        $types = [
            'manual' => esc_html__('Manual', 'botfend-anti-bot-firewall'),
            'permanent_manual' => esc_html__('Permanent Manual', 'botfend-anti-bot-firewall'),
            'auto_block' => esc_html__('Auto Block', 'botfend-anti-bot-firewall'),
            'iphub_block' => esc_html__('IPHub', 'botfend-anti-bot-firewall'),
            'abuseipdb_block' => esc_html__('AbuseIPDB', 'botfend-anti-bot-firewall'),
            'honeypot' => esc_html__('Honeypot', 'botfend-anti-bot-firewall'),
            'brute_force' => esc_html__('Brute Force', 'botfend-anti-bot-firewall'),
            '404_attack' => esc_html__('404 Attack', 'botfend-anti-bot-firewall'),
            'advanced_404_block' => esc_html__('Advanced 404 Block', 'botfend-anti-bot-firewall'),
            'perpetual_offender' => esc_html__('Perpetual Offender', 'botfend-anti-bot-firewall'),
        ];
        return $types[$type] ?? ucwords(str_replace('_', ' ', $type));
    }

    private function format_expiry_time(?string $expires): string {
        if (empty($expires) || $expires === '0000-00-00 00:00:00') {
            return '<span class="botfend-permanent">' . esc_html__('Permanent', 'botfend-anti-bot-firewall') . '</span>';
        }
        $expiry_timestamp = strtotime($expires);
        $current_timestamp = current_time('timestamp');
        if ($expiry_timestamp <= $current_timestamp) {
            return '<span style="color: #28a745;">' . esc_html__('Expired', 'botfend-anti-bot-firewall') . '</span>';
        }
        $time_diff = human_time_diff($current_timestamp, $expiry_timestamp);
        if ($expiry_timestamp - $current_timestamp < 24 * 60 * 60) {
            return '<span style="color: #ffc107;">' . sprintf(esc_html__('In %s', 'botfend-anti-bot-firewall'), esc_html($time_diff)) . '</span>';
        }
        return esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), $expiry_timestamp));
    }

    private function get_score_color(int $score): string {
        if ($score >= 8) return '#dc3232';
        if ($score >= 6) return '#f56e28';
        if ($score >= 4) return '#00a0d2';
        return '#46b450';
    }

    private function truncate_text(string $text, int $length = 50): string {
        if (strlen($text) <= $length) return $text;
        return substr($text, 0, $length) . '...';
    }

    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'));
        }
        if (!$this->database || !$this->utilities) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Required components not available.', 'botfend-anti-bot-firewall') . '</p></div>';
            return;
        }

        $duration = $this->get_block_duration();
        $admin_notices = [];

        // Handle Make Permanent action
        if (isset($_GET['action']) && $_GET['action'] === 'make_permanent' && isset($_GET['ip'])) {
            check_admin_referer('botfend_admin_action');
            $ip = sanitize_text_field(wp_unslash($_GET['ip']));
            if (filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip)) {
                $db_result = $this->add_to_permanent_blocklist($ip);
                if ($db_result) {
                    $display_ip = esc_html($ip);
                    $type_label = (strpos($ip, '/') !== false) ? esc_html__('Range', 'botfend-anti-bot-firewall') : esc_html__('IP', 'botfend-anti-bot-firewall');
                    $message = sprintf(esc_html__('%1$s %2$s added to permanent blocklist.', 'botfend-anti-bot-firewall'), $type_label, $display_ip);
                    $admin_notices[] = ['type' => 'success', 'message' => $message . ' <a href="' . esc_url(admin_url('admin.php?page=botfend-settings&tab=paths')) . '">' . esc_html__('View in Paths tab', 'botfend-anti-bot-firewall') . '</a>'];
                } else {
                    $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Failed to make permanent.', 'botfend-anti-bot-firewall')];
                }
            } else {
                $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Invalid IP address or CIDR range provided.', 'botfend-anti-bot-firewall')];
            }
        }

        // Handle manual block
        if (isset($_GET['manual_block']) && !empty($_GET['manual_ip'])) {
            check_admin_referer('botfend_manual_block', 'botfend_manual_nonce');
            $ip = sanitize_text_field(wp_unslash($_GET['manual_ip']));
            
            // Validate IP address
            if (filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip)) {
                $country = sanitize_text_field($this->utilities->get_country($ip));
                $result = $this->database->block_ip($ip, 'manual', esc_html__('Manually blocked by admin', 'botfend-anti-bot-firewall'), 10, $duration, $country);
                
                if ($result) {
                    if (is_numeric($result)) {
                        $this->check_and_flag_perpetual_offender($ip, (int) $result);
                    } elseif ($result === true) {
                        $blocklist_table = $this->wpdb->prefix . 'botfend_blocklist';
                        $escaped_table = esc_sql($blocklist_table);
                        $block_id = $this->wpdb->get_var($this->wpdb->prepare(
                            "SELECT id FROM `{$escaped_table}` WHERE ip = %s ORDER BY created_at DESC LIMIT 1",
                            $ip
                        ));
                        if ($block_id) {
                            $this->check_and_flag_perpetual_offender($ip, (int) $block_id);
                        }
                    }
                    $type_label = (strpos($ip, '/') !== false) ? esc_html__('Range', 'botfend-anti-bot-firewall') : esc_html__('IP', 'botfend-anti-bot-firewall');
                    $admin_notices[] = ['type' => 'success', 'message' => sprintf(esc_html__('%1$s %2$s manually blocked successfully.', 'botfend-anti-bot-firewall'), $type_label, esc_html($ip))];
                } else {
                    $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Failed to block. It may already be blocked.', 'botfend-anti-bot-firewall')];
                }
            } else {
                $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Invalid IP address or CIDR range provided.', 'botfend-anti-bot-firewall')];
            }
        }

        // Handle bulk unblock
        if (isset($_POST['botfend_bulk_action']) && $_POST['botfend_bulk_action'] === 'unblock') {
            check_admin_referer('botfend_bulk_action', 'botfend_bulk_nonce');
            $bulk_ips = isset($_POST['bulk_ips']) ? array_map('sanitize_text_field', (array) wp_unslash($_POST['bulk_ips'])) : [];
            $valid_ips = array_filter($bulk_ips, function($ip) { return filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip); });
            $success = 0; $failed = 0;
            foreach ($valid_ips as $ip) { if ($this->database->unblock_ip($ip)) $success++; else $failed++; }
            if ($success > 0) $admin_notices[] = ['type' => 'success', 'message' => sprintf(esc_html__('%d IP(s)/ranges unblocked successfully.', 'botfend-anti-bot-firewall'), $success)];
            if ($failed > 0) $admin_notices[] = ['type' => 'warning', 'message' => sprintf(esc_html__('%d IP(s)/ranges failed to process.', 'botfend-anti-bot-firewall'), $failed)];
        }

        // Handle quick actions
        if (isset($_GET['action'], $_GET['ip'])) {
            check_admin_referer('botfend_admin_action');
            $ip = sanitize_text_field(wp_unslash($_GET['ip']));
            if ($_GET['action'] === 'unblock' && (filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip))) {
                $this->database->unblock_ip($ip);
                $admin_notices[] = ['type' => 'success', 'message' => esc_html__('IP/range unblocked successfully.', 'botfend-anti-bot-firewall')];
            }
            if ($_GET['action'] === 'block' && (filter_var($ip, FILTER_VALIDATE_IP) || $this->is_valid_cidr($ip))) {
                $country = sanitize_text_field($this->utilities->get_country($ip));
                $result = $this->database->block_ip($ip, 'manual', esc_html__('Manually blocked by admin (Quick Action)', 'botfend-anti-bot-firewall'), 10, $duration, $country);
                if ($result && is_numeric($result)) $this->check_and_flag_perpetual_offender($ip, (int) $result);
                $admin_notices[] = ['type' => 'success', 'message' => esc_html__('IP/range blocked successfully.', 'botfend-anti-bot-firewall')];
            }
        }

        // Filters
        $filters = [];
        if (!empty($_GET['filter_ip'])) $filters['ip'] = sanitize_text_field(wp_unslash($_GET['filter_ip']));
        if (!empty($_GET['filter_type'])) $filters['type'] = sanitize_text_field(wp_unslash($_GET['filter_type']));
        if (!empty($_GET['filter_country'])) $filters['country'] = sanitize_text_field(wp_unslash($_GET['filter_country']));
        if (!empty($_GET['filter_reason'])) $filters['reason'] = sanitize_text_field(wp_unslash($_GET['filter_reason']));

        $blocks = $this->database->get_blocklist($filters, 100);
        $stats = $this->database->get_blocklist_stats();
        $total_blocked = isset($stats['total_blocks']) ? $stats['total_blocks'] : count($blocks);

        $prevent_autofocus = get_transient('botfend_prevent_autofocus');
        if ($prevent_autofocus) delete_transient('botfend_prevent_autofocus');

        foreach ($blocks as $block) {
            $block->last_url = '';
            if (method_exists($this->database, 'get_last_request_uri')) {
                $block->last_url = $this->database->get_last_request_uri($block->ip, $block->created_at);
            }
            $block->detection_factors = $this->get_detection_factors_for_ip($block->ip, $block->created_at, $block->reason);
            $logs = $this->database->get_logs(['ip' => $block->ip, 'min_score' => 0], 1);
            if (!empty($logs)) {
                $log = $logs[0];
                $block->http_method = $log->http_method ?? 'GET';
                $block->request_uri = $log->request_uri ?? '';
                $block->user_agent = $log->user_agent ?? '';
                $block->duplicate_count = $log->duplicate_count ?? 1;
            } else {
                $block->http_method = 'GET'; $block->request_uri = ''; $block->user_agent = ''; $block->duplicate_count = 1;
            }
        }

        $cidr_count = 0; $single_count = 0; $perpetual_count = 0;
        foreach ($blocks as $block) {
            if (strpos($block->ip, '/') !== false) $cidr_count++; else $single_count++;
            if (isset($block->is_perpetual_offender) && $block->is_perpetual_offender) $perpetual_count++;
        }
        ?>

        <div class="wrap botfend-wrap">
            <div class="botfend-header-area">
                <h1 class="wp-heading-inline botfend-page-title"><?php echo esc_html__('Blocklist Management', 'botfend-anti-bot-firewall'); ?></h1>
            </div>

            <?php if (!empty($admin_notices)) : ?>
                <div id="botfend-admin-notices">
                    <?php foreach ($admin_notices as $notice) : ?>
                        <div class="notice notice-<?php echo esc_attr($notice['type']); ?> botfend-notice is-dismissible">
                            <p><?php echo wp_kses_post($notice['message']); ?></p>
                            <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php echo esc_html__('Dismiss this notice.', 'botfend-anti-bot-firewall'); ?></span></button>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <div id="botfend-bulk-action-bar" class="botfend-bulk-action-bar" style="display: none;">
                <div class="botfend-bulk-action-content">
                    <div class="botfend-bulk-action-info">
                        <span class="dashicons dashicons-shield-alt"></span>
                        <span class="botfend-bulk-action-text">
                            <span id="botfend-selected-count">0</span>
                            <?php echo esc_html__('IP(s)/ranges selected for unblocking', 'botfend-anti-bot-firewall'); ?>
                        </span>
                    </div>
                    <div class="botfend-bulk-action-buttons">
                        <button type="button" class="button button-primary botfend-bulk-action-button" id="botfend-apply-bulk-action">
                            <span class="dashicons dashicons-unlock"></span><?php echo esc_html__('Unblock Selected', 'botfend-anti-bot-firewall'); ?>
                        </button>
                        <button type="button" class="button button-secondary botfend-bulk-action-button" id="botfend-cancel-bulk-action">
                            <span class="dashicons dashicons-dismiss"></span><?php echo esc_html__('Clear Selection', 'botfend-anti-bot-firewall'); ?>
                        </button>
                    </div>
                </div>
            </div>

            <div class="botfend-card botfend-statistics-card">
                <details open>
                    <summary class="botfend-section-summary">
                        <span class="dashicons dashicons-chart-bar"></span>
                        <?php echo esc_html__('Overview & Statistics', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content">
                        <div class="botfend-statistics-grid">
                            <div class="botfend-statistic-item">
                                <span class="botfend-statistic-icon dashicons dashicons-lock"></span>
                                <div class="botfend-statistic-content">
                                    <span class="botfend-statistic-number"><?php echo esc_html($total_blocked); ?></span>
                                    <span class="botfend-statistic-label"><?php echo esc_html__('Blocked IPs/Ranges', 'botfend-anti-bot-firewall'); ?></span>
                                </div>
                            </div>
                            <div class="botfend-statistic-item">
                                <span class="botfend-statistic-icon dashicons dashicons-clock"></span>
                                <div class="botfend-statistic-content">
                                    <span class="botfend-statistic-number"><?php echo esc_html($duration); ?></span>
                                    <span class="botfend-statistic-label"><?php echo esc_html__('Default Block Hours', 'botfend-anti-bot-firewall'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </details>
            </div>

            <div class="botfend-card botfend-mb-20">
                <details>
                    <summary class="botfend-section-summary">
                        <span class="dashicons dashicons-filter"></span>
                        <?php echo esc_html__('Search & Filter', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content">
                        <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" class="botfend-filter-form">
                            <?php wp_nonce_field('botfend_admin_action', 'botfend_filter_nonce'); ?>
                            <input type="hidden" name="page" value="botfend-blocklist">
                            <div class="botfend-filter-grid">
                                <div class="botfend-filter-group">
                                    <label for="filter-ip" class="botfend-filter-label"><?php echo esc_html__('IP Address/Range', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="text" id="filter-ip" name="filter_ip" class="botfend-filter-input" placeholder="<?php echo esc_attr__('e.g., 192.168.1.1, 192.168.0.0/24', 'botfend-anti-bot-firewall'); ?>" value="<?php echo isset($_GET['filter_ip']) ? esc_attr(sanitize_text_field(wp_unslash($_GET['filter_ip']))) : ''; ?>">
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-type" class="botfend-filter-label"><?php echo esc_html__('Block Type', 'botfend-anti-bot-firewall'); ?></label>
                                    <select id="filter-type" name="filter_type" class="botfend-filter-select">
                                        <option value=""><?php echo esc_html__('All Types', 'botfend-anti-bot-firewall'); ?></option>
                                        <?php
                                        $valid_types = ['manual', 'auto_block', 'iphub_block', 'abuseipdb_block', 'honeypot', 'brute_force', '404_attack', 'advanced_404_block', 'permanent_manual', 'perpetual_offender'];
                                        $type_labels = [
                                            'manual' => esc_html__('Manual Block', 'botfend-anti-bot-firewall'),
                                            'auto_block' => esc_html__('Auto Block', 'botfend-anti-bot-firewall'),
                                            'iphub_block' => esc_html__('IPHub Block', 'botfend-anti-bot-firewall'),
                                            'abuseipdb_block' => esc_html__('AbuseIPDB Block', 'botfend-anti-bot-firewall'),
                                            'honeypot' => esc_html__('Honeypot', 'botfend-anti-bot-firewall'),
                                            'brute_force' => esc_html__('Brute Force', 'botfend-anti-bot-firewall'),
                                            '404_attack' => esc_html__('404 Attack', 'botfend-anti-bot-firewall'),
                                            'advanced_404_block' => esc_html__('Advanced 404 Block', 'botfend-anti-bot-firewall'),
                                            'permanent_manual' => esc_html__('Permanent Block', 'botfend-anti-bot-firewall'),
                                            'perpetual_offender' => esc_html__('Perpetual Offender', 'botfend-anti-bot-firewall'),
                                        ];
                                        $current_type = isset($_GET['filter_type']) ? sanitize_text_field(wp_unslash($_GET['filter_type'])) : '';
                                        foreach ($valid_types as $type) {
                                            printf('<option value="%s" %s>%s</option>', esc_attr($type), selected($current_type, $type, false), esc_html($type_labels[$type] ?? ucwords(str_replace('_', ' ', $type))));
                                        }
                                        ?>
                                    </select>
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-country" class="botfend-filter-label"><?php echo esc_html__('Country Code', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="text" id="filter-country" name="filter_country" class="botfend-filter-input" placeholder="<?php echo esc_attr__('e.g., US, GB, DE', 'botfend-anti-bot-firewall'); ?>" value="<?php echo isset($_GET['filter_country']) ? esc_attr(sanitize_text_field(wp_unslash($_GET['filter_country']))) : ''; ?>" pattern="[A-Z]{2}" maxlength="2">
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-reason" class="botfend-filter-label"><?php echo esc_html__('Reason', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="text" id="filter-reason" name="filter_reason" class="botfend-filter-input" placeholder="<?php echo esc_attr__('Search in reasons', 'botfend-anti-bot-firewall'); ?>" value="<?php echo isset($_GET['filter_reason']) ? esc_attr(sanitize_text_field(wp_unslash($_GET['filter_reason']))) : ''; ?>">
                                </div>
                            </div>
                            <div class="botfend-filter-actions">
                                <button type="submit" class="button button-primary"><?php echo esc_html__('Apply Filters', 'botfend-anti-bot-firewall'); ?></button>
                                <a href="<?php echo esc_url(admin_url('admin.php?page=botfend-blocklist')); ?>" class="button"><?php echo esc_html__('Reset', 'botfend-anti-bot-firewall'); ?></a>
                            </div>
                        </form>
                    </div>
                </details>
            </div>

            <div class="botfend-card" style="padding: 0;">
                <details open>
                    <summary class="botfend-section-summary">
                        <span class="dashicons dashicons-list-view"></span>
                        <?php echo esc_html__('Blocked IP Addresses & Ranges', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content">
                        <?php if (empty($blocks)): ?>
                            <div class="botfend-empty-state" style="padding: 40px 20px;">
                                <span class="dashicons dashicons-shield-alt"></span>
                                <h3><?php echo esc_html__('No blocked IPs or ranges found', 'botfend-anti-bot-firewall'); ?></h3>
                                <p><?php echo esc_html__('Try adjusting your filters.', 'botfend-anti-bot-firewall'); ?></p>
                            </div>
                        <?php else: ?>
                            <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=botfend-blocklist')); ?>" id="botfend-blocklist-form">
                                <?php wp_nonce_field('botfend_bulk_action', 'botfend_bulk_nonce'); ?>
                                <input type="hidden" name="botfend_bulk_action" value="unblock">
                                <div class="botfend-table-responsive" style="padding-top: 15px;">
                                    <table class="wp-list-table widefat fixed striped botfend-blocklist-table">
                                        <thead>
                                            <tr>
                                                <th class="botfend-col-select manage-column column-cb check-column"><input type="checkbox" id="select-all-logs"></th>
                                                <th class="botfend-col-ip"><?php echo esc_html__('IP Address/Range', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-country"><?php echo esc_html__('Location', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-type"><?php echo esc_html__('Type', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-score"><?php echo esc_html__('Score', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-expires"><?php echo esc_html__('Expires', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-context" style="text-align: right;"><?php echo esc_html__('Context', 'botfend-anti-bot-firewall'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($blocks as $block):
                                                $is_cidr = strpos($block->ip, '/') !== false;
                                                $is_perpetual = isset($block->is_perpetual_offender) && $block->is_perpetual_offender;
                                                $unblock_url = wp_nonce_url(admin_url('admin.php?page=botfend-blocklist&action=unblock&ip=' . rawurlencode($block->ip)), 'botfend_admin_action');
                                                $log_url = esc_url(add_query_arg('ip', rawurlencode($block->ip), admin_url('admin.php?page=botfend-logs')));
                                                $permanent_url = wp_nonce_url(admin_url('admin.php?page=botfend-blocklist&action=make_permanent&ip=' . rawurlencode($block->ip)), 'botfend_admin_action');
                                                $is_permanent = empty($block->expires) || $block->expires === '0000-00-00 00:00:00' || $block->type === 'permanent_manual' || $block->type === 'perpetual_offender';
                                                $block_until = !$is_permanent ? $this->format_expiry_time($block->expires) : '<span class="botfend-permanent">' . esc_html__('Permanent', 'botfend-anti-bot-firewall') . '</span>';
                                                $type_class = 'botfend-type-' . sanitize_html_class($block->type);
                                                $score = absint($block->score);
                                                $score_color = $this->get_score_color($score);
                                            ?>
                                            <tr class="botfend-block-row">
                                                <td class="botfend-col-select check-column" data-label="<?php esc_attr_e('Select', 'botfend-anti-bot-firewall'); ?>">
                                                    <input type="checkbox" id="ip-<?php echo esc_attr($block->id); ?>" class="log-checkbox" name="bulk_ips[]" value="<?php echo esc_attr($block->ip); ?>">
                                                </td>
                                                <td class="botfend-col-ip" data-label="<?php esc_attr_e('IP Address/Range', 'botfend-anti-bot-firewall'); ?>">
                                                    <div class="botfend-ip-cell">
                                                        <code class="botfend-ip-address"><?php echo esc_html($block->ip); ?></code>
                                                        <?php if ($is_cidr): ?><span class="botfend-cidr-badge">CIDR</span><?php endif; ?>
                                                        <?php if ($is_perpetual): ?><span class="botfend-perpetual-badge" title="<?php esc_attr_e('Perpetual Offender', 'botfend-anti-bot-firewall'); ?>">⚠️ <?php echo esc_html__('Repeat', 'botfend-anti-bot-firewall'); ?></span><?php endif; ?>
                                                    </div>
                                                </td>
                                                <td class="botfend-col-country" data-label="<?php esc_attr_e('Location', 'botfend-anti-bot-firewall'); ?>">
                                                    <?php if (!empty($block->country) && $block->country !== 'N/A'): ?>
                                                        <span class="botfend-country-flag"><?php echo esc_html($block->country); ?></span>
                                                    <?php else: ?>
                                                        <span class="botfend-unknown">—</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="botfend-col-type" data-label="<?php esc_attr_e('Type', 'botfend-anti-bot-firewall'); ?>">
                                                    <span class="botfend-type-badge <?php echo esc_attr($type_class); ?>"><?php echo esc_html($this->format_block_type($block->type)); ?></span>
                                                </td>
                                                <td class="botfend-col-score" data-label="<?php esc_attr_e('Score', 'botfend-anti-bot-firewall'); ?>">
                                                    <div class="botfend-score-badge" style="--score-color: <?php echo esc_attr($score_color); ?>" title="<?php esc_attr_e('Threat Score out of 10', 'botfend-anti-bot-firewall'); ?>"><?php echo esc_html($score); ?></div>
                                                </td>
                                                <td class="botfend-col-expires" data-label="<?php esc_attr_e('Expires', 'botfend-anti-bot-firewall'); ?>">
                                                    <div class="botfend-expiry-cell">
                                                        <?php echo $block_until; ?>
                                                        <?php if (!empty($block->created_at)): ?>
                                                            <div class="botfend-created-at">
                                                                <?php
                                                                /* translators: %s: date and time */
                                                                printf(esc_html__('Blocked: %s', 'botfend-anti-bot-firewall'), esc_html($block->created_at));
                                                                ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                                <td class="botfend-col-context" data-label="<?php esc_attr_e('Context', 'botfend-anti-bot-firewall'); ?>" style="text-align: right;">
                                                    <div class="botfend-details-dropdown">
                                                        <button type="button" class="button botfend-details-toggle" aria-label="<?php esc_attr_e('Show details', 'botfend-anti-bot-firewall'); ?>" data-block-id="<?php echo esc_attr($block->id); ?>">
                                                            <span class="dashicons dashicons-ellipsis"></span>
                                                        </button>
                                                        <div class="botfend-details-content" id="details-<?php echo esc_attr($block->id); ?>" style="display: none;">
                                                            <div class="botfend-details-grid">
                                                                <div class="botfend-detail-item"><span class="botfend-detail-label"><?php esc_html_e('Method:', 'botfend-anti-bot-firewall'); ?></span><span class="botfend-detail-value badge-method"><?php echo esc_html($block->http_method); ?></span></div>
                                                                <div class="botfend-detail-item"><span class="botfend-detail-label"><?php esc_html_e('Last URL:', 'botfend-anti-bot-firewall'); ?></span><span class="botfend-detail-value code-path" title="<?php echo esc_attr($block->last_url ?: $block->request_uri); ?>"><?php echo esc_html($this->truncate_text($block->last_url ?: $block->request_uri, 50)); ?></span></div>
                                                                <div class="botfend-detail-item"><span class="botfend-detail-label"><?php esc_html_e('Agent:', 'botfend-anti-bot-firewall'); ?></span><span class="botfend-detail-value" title="<?php echo esc_attr($block->user_agent); ?>"><?php echo esc_html($this->truncate_text($block->user_agent, 40)); ?></span></div>
                                                                <?php if ($block->duplicate_count > 1): ?>
                                                                <div class="botfend-detail-item"><span class="botfend-detail-label"><?php esc_html_e('Duplicates:', 'botfend-anti-bot-firewall'); ?></span><span class="botfend-detail-value badge-count"><?php echo esc_html($block->duplicate_count); ?></span></div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div class="botfend-actions-row">
                                                                <button type="button" class="button botfend-action-button botfend-factors-button" data-factors='<?php echo esc_attr(wp_json_encode($block->detection_factors, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP)); ?>'><?php echo esc_html__('View Details', 'botfend-anti-bot-firewall'); ?></button>
                                                                <a href="<?php echo esc_url($log_url); ?>" class="button botfend-action-button"><?php echo esc_html__('View Logs', 'botfend-anti-bot-firewall'); ?></a>
                                                                <a href="<?php echo esc_url($unblock_url); ?>" class="button botfend-action-button botfend-action-unblock" onclick="return confirm('<?php echo esc_js(esc_html__('Are you sure you want to unblock this IP/range?', 'botfend-anti-bot-firewall')); ?>')"><?php echo esc_html__('Unblock', 'botfend-anti-bot-firewall'); ?></a>
                                                                <?php if (!$is_permanent): ?>
                                                                <a href="<?php echo esc_url($permanent_url); ?>" class="button botfend-action-button botfend-action-permanent" onclick="return confirm('<?php echo esc_js(esc_html__('Make this block permanent? It will never expire.', 'botfend-anti-bot-firewall')); ?>')"><?php echo esc_html__('Make Permanent', 'botfend-anti-bot-firewall'); ?></a>
                                                                <?php else: ?>
                                                                <span class="botfend-badge-permanent" title="<?php esc_attr_e('Already permanent', 'botfend-anti-bot-firewall'); ?>"><span class="dashicons dashicons-saved"></span></span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <div class="botfend-summary-stats" style="margin: 15px 20px 20px 20px; padding: 15px; background: #f0f0f1; border-left: 4px solid #2271b1; border-radius: 4px;">
                                    <span class="dashicons dashicons-chart-pie" style="color: #2271b1; margin-right: 5px;"></span>
                                    <strong><?php echo esc_html__('Summary:', 'botfend-anti-bot-firewall'); ?></strong>
                                    <?php
                                    /* translators: 1: total entries, 2: CIDR range count, 3: single IP count, 4: perpetual offenders */
                                    printf(
                                        esc_html__('Total: %1$d entries (%2$d CIDR ranges, %3$d single IPs, %4$d perpetual offenders flagged)', 'botfend-anti-bot-firewall'),
                                        count($blocks), $cidr_count, $single_count, $perpetual_count
                                    );
                                    ?>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </details>
            </div>

            <div class="botfend-card">
                <details>
                    <summary class="botfend-section-summary">
                        <span class="dashicons dashicons-plus"></span>
                        <?php echo esc_html__('Quick Block IP/Range', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content">
                        <p class="botfend-card-description" style="margin-top: 15px;">
                            <?php echo esc_html__('Manually block an IP address or CIDR range. Block duration can be configured in settings.', 'botfend-anti-bot-firewall'); ?>
                        </p>
                        <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" class="botfend-quick-block-form">
                            <?php wp_nonce_field('botfend_manual_block', 'botfend_manual_nonce'); ?>
                            <input type="hidden" name="page" value="botfend-blocklist">
                            <div class="botfend-quick-block-grid">
                                <div class="botfend-quick-block-input-group">
                                    <label for="manual-ip" class="botfend-input-label"><?php echo esc_html__('IP Address or CIDR Range', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="text" id="manual-ip" name="manual_ip" class="botfend-quick-block-input" placeholder="<?php echo esc_attr__('e.g., 192.168.1.1, 2001:db8::1, or 192.168.0.0/24', 'botfend-anti-bot-firewall'); ?>" required pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$|^([0-9a-fA-F:]+)$|^([0-9]{1,3}\.){3}[0-9]{1,3}\/[0-9]{1,2}$|^([0-9a-fA-F:]+)\/[0-9]{1,3}$" title="<?php echo esc_attr__('Enter valid IPv4, IPv6, or CIDR range', 'botfend-anti-bot-firewall'); ?>">
                                    <p class="botfend-input-description"><?php echo esc_html__('Enter a valid IPv4, IPv6 address, or CIDR range (e.g., 192.168.1.0/24)', 'botfend-anti-bot-firewall'); ?></p>
                                </div>
                                <div class="botfend-quick-block-actions">
                                    <input type="submit" name="manual_block" class="button button-primary botfend-quick-block-button" value="<?php echo esc_attr__('Block IP/Range', 'botfend-anti-bot-firewall'); ?>" onclick="return confirm('<?php echo esc_js(esc_html__('Are you sure you want to block this IP/range?', 'botfend-anti-bot-firewall')); ?>')">
                                </div>
                            </div>
                        </form>
                    </div>
                </details>
            </div>
        </div>

        <div id="botfend-factors-modal" class="botfend-modal" style="display: none;">
            <div class="botfend-modal-backdrop"></div>
            <div class="botfend-modal-content">
                <div class="botfend-modal-header">
                    <h3><?php echo esc_html__('Detection Factors Analysis', 'botfend-anti-bot-firewall'); ?></h3>
                    <button type="button" class="botfend-modal-close-icon" aria-label="<?php esc_attr_e('Close', 'botfend-anti-bot-firewall'); ?>">
                        <span class="dashicons dashicons-no-alt"></span>
                    </button>
                </div>
                <div class="botfend-modal-body">
                    <div id="botfend-factors-content" class="botfend-json-view"></div>
                </div>
            </div>
        </div>
        <?php
    }

    private function get_detection_factors_for_ip(string $ip, ?string $before_time = null, string $block_reason = ''): array {
        $factors = [];
        if (method_exists($this->database, 'get_logs')) {
            $filters = ['ip' => $ip, 'min_score' => 6];
            if ($before_time) $filters['date_to'] = gmdate('Y-m-d', strtotime($before_time));
            $logs = $this->database->get_logs($filters, 5);
            foreach ($logs as $log) {
                if (!empty($log->factors)) {
                    try {
                        $log_factors = json_decode($log->factors, true);
                        if ($log_factors) {
                            if (is_array($log_factors)) {
                                foreach ($log_factors as $factor) {
                                    if (is_string($factor)) {
                                        $factors[] = ['type' => 'detection', 'description' => $factor, 'severity' => $log->score >= 8 ? 'critical' : ($log->score >= 6 ? 'warning' : 'info'), 'timestamp' => $log->created_at, 'score' => $log->score];
                                    } elseif (is_array($factor)) {
                                        $factor['timestamp'] = $log->created_at;
                                        $factor['score'] = $log->score;
                                        if (!isset($factor['severity'])) $factor['severity'] = $log->score >= 8 ? 'critical' : ($log->score >= 6 ? 'warning' : 'info');
                                        $factors[] = $factor;
                                    }
                                }
                            } else {
                                $factors[] = ['type' => 'detection', 'description' => $log_factors, 'severity' => $log->score >= 8 ? 'critical' : ($log->score >= 6 ? 'warning' : 'info'), 'timestamp' => $log->created_at, 'score' => $log->score];
                            }
                        }
                    } catch (\Exception $e) {
                        $factors[] = ['type' => 'detection', 'description' => $log->factors, 'severity' => $log->score >= 8 ? 'critical' : ($log->score >= 6 ? 'warning' : 'info'), 'timestamp' => $log->created_at, 'score' => $log->score];
                    }
                }
            }
        }
        if (empty($factors) && !empty($block_reason)) {
            $factors[] = ['type' => 'block_reason', 'description' => $block_reason, 'severity' => 'critical', 'timestamp' => $before_time ?: current_time('mysql'), 'score' => 10];
        }
        return $factors;
    }
}