<?php
/**
 * Logs page handler for BotFend Anti-Bot Firewall
 *
 * @package BotFend\Admin\Pages
 * @version 5.0.7 - External JavaScript enqueued, CSS extracted, Refresh button added
 */

namespace BotFend\Admin\Pages;

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

defined('ABSPATH') || exit;

class Logs {

    private $core;
    private $database;
    private $config;

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

        $components = $core->get_components();
        $this->database = $components['database'] ?? null;

        add_action('admin_enqueue_scripts', [$this, 'enqueue_logs_assets']);
        add_action('wp_ajax_botfend_refresh_logs', [$this, 'ajax_refresh_logs']);
    }

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

        wp_enqueue_style(
            'botfend-logs-css', 
            BOTFEND_ASSETS_URL . 'css/botfend-logs.css', 
            ['botfend-admin-css'],
            BOTFEND_VERSION
        );

        wp_enqueue_script(
            'botfend-logs-js',
            BOTFEND_ASSETS_URL . 'js/logs.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );

        $auto_refresh = $this->get_config_bool('logs_auto_refresh', false);
        $refresh_interval = $this->get_config_int('logs_refresh_interval', 30000);

        wp_localize_script('botfend-logs-js', 'botfendLogs', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('botfend_admin_action'),
            'refreshNonce' => wp_create_nonce('botfend_logs_refresh'),
            'autoRefresh' => $auto_refresh,
            'refreshInterval' => $refresh_interval,
            'clearSuccessUrl' => admin_url('admin.php?page=botfend-logs&clear_success=1'),
            'aggregateClearSuccessUrl' => admin_url('admin.php?page=botfend-logs&aggregate_clear_success=1'),
            'refreshText' => esc_html__('Refresh Data', 'botfend-anti-bot-firewall'),
            'refreshingText' => esc_html__('Refreshing...', 'botfend-anti-bot-firewall'),
            'refreshSuccess' => esc_html__('Logs refreshed successfully!', 'botfend-anti-bot-firewall'),
            'refreshFailed' => esc_html__('Failed to refresh logs.', 'botfend-anti-bot-firewall'),
            'i18n' => [
                'selectItems' => esc_html__('Please select at least one item.', 'botfend-anti-bot-firewall'),
                'selectAction' => esc_html__('Please select an action.', 'botfend-anti-bot-firewall'),
                'blocking' => esc_html__('Blocking', 'botfend-anti-bot-firewall'),
                'whitelisting' => esc_html__('Whitelisting', 'botfend-anti-bot-firewall'),
                'deleting' => esc_html__('Deleting', 'botfend-anti-bot-firewall'),
                'processing' => esc_html__('Processing', 'botfend-anti-bot-firewall'),
                'confirmAction' => esc_html__('Are you sure you want to', 'botfend-anti-bot-firewall'),
                'items' => esc_html__('items?', 'botfend-anti-bot-firewall'),
                'errorBulk' => esc_html__('Error processing bulk action.', 'botfend-anti-bot-firewall'),
                'confirmClearLogs' => esc_html__('WARNING: Are you sure you want to clear ALL security logs? This action is permanent and cannot be undone.', 'botfend-anti-bot-firewall'),
                'confirmClearAggregates' => esc_html__('Are you sure you want to clear ALL aggregated log data? This action cannot be undone.', 'botfend-anti-bot-firewall'),
                'clearingLogs' => esc_html__('Clearing Logs...', 'botfend-anti-bot-firewall'),
                'clearingAggregates' => esc_html__('Clearing Aggregates...', 'botfend-anti-bot-firewall'),
                'errorClearLogs' => esc_html__('Error clearing logs.', 'botfend-anti-bot-firewall'),
                'errorClearAggregates' => esc_html__('Error clearing aggregated data.', '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_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 verify_nonce_or_die(): void {
        $nonce = isset($_REQUEST['_wpnonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'botfend_admin_action')) {
            wp_die(esc_html__('Security check failed.', 'botfend-anti-bot-firewall'));
        }
    }

    private function validate_filters(array $filters): array {
        $validated = [];

        if (!empty($filters['ip'])) {
            $ip = sanitize_text_field($filters['ip']);
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                $validated['ip'] = $ip;
            }
        }

        if (!empty($filters['action'])) {
            $action = sanitize_text_field($filters['action']);
            $known_actions = $this->database->get_distinct_actions();
            if (in_array($action, $known_actions, true)) {
                $validated['action'] = $action;
            }
        }

        if (!empty($filters['min_score'])) {
            $score = absint($filters['min_score']);
            if ($score >= 0 && $score <= 10) {
                $validated['min_score'] = $score;
            }
        }

        if (!empty($filters['country'])) {
            $country = strtoupper(sanitize_text_field($filters['country']));
            if (preg_match('/^[A-Z]{2}$/', $country)) {
                $validated['country'] = $country;
            }
        }

        if (!empty($filters['date_from'])) {
            $date = sanitize_text_field($filters['date_from']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $validated['date_from'] = $date;
            }
        }

        if (!empty($filters['date_to'])) {
            $date = sanitize_text_field($filters['date_to']);
            if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $validated['date_to'] = $date;
            }
        }

        return $validated;
    }

    private function add_to_whitelist(string $ip): bool {
        $ip = trim($ip);
        if (empty($ip) || false === filter_var($ip, FILTER_VALIDATE_IP)) {
            return false;
        }
        if (str_contains($ip, ':')) {
            $ip = strtolower($ip);
        }
        return $this->database->add_to_whitelist($ip);
    }

    private function get_cached_logs(array $filters, int $limit, int $hours, int $offset = 0): array {
        $cache_key = 'botfend_logs_' . md5(serialize([$filters, $limit, $hours, $offset]));
        $cached = wp_cache_get($cache_key, 'botfend_logs');
        if ($cached !== false) {
            return $cached;
        }
        $logs = $this->database->get_logs_deduplicated($filters, $limit, $hours);
        wp_cache_set($cache_key, $logs, 'botfend_logs', 300);
        return $logs;
    }

    private function handle_bulk_actions() {
        if (isset($_POST['apply_bulk_action']) && isset($_POST['bulk_action']) && !empty($_POST['selected_ips'])) {
            $this->verify_nonce_or_die();
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'botfend-anti-bot-firewall'));
            }
            $action = sanitize_text_field(wp_unslash($_POST['bulk_action']));
            $selected_ips = json_decode(stripslashes(sanitize_text_field(wp_unslash($_POST['selected_ips']))), true);
            if (!is_array($selected_ips)) {
                return false;
            }
            $processed = 0;
            $valid_ips = [];
            foreach ($selected_ips as $ip) {
                $ip = sanitize_text_field($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP)) {
                    $valid_ips[] = $ip;
                }
            }
            if (empty($valid_ips)) {
                return 0;
            }
            switch ($action) {
                case 'block_selected':
                    foreach ($valid_ips as $ip) {
                        $this->database->block_ip($ip, 'manual', esc_html__('Bulk action from logs', 'botfend-anti-bot-firewall'), 10, 24, null);
                        $processed++;
                    }
                    break;
                case 'whitelist_selected':
                    foreach ($valid_ips as $ip) {
                        $this->database->add_to_whitelist($ip);
                        $processed++;
                    }
                    break;
                case 'delete_selected':
                    $processed = $this->database->bulk_delete_logs_by_ips($valid_ips);
                    break;
            }
            return $processed;
        }
        return false;
    }

    private function get_action_label(string $action): string {
        $labels = [
            'blocked' => esc_html__('Blocked', 'botfend-anti-bot-firewall'),
            'iphub_block' => esc_html__('IPHub Block', 'botfend-anti-bot-firewall'),
            'abuseipdb_block' => esc_html__('AbuseIPDB Block', 'botfend-anti-bot-firewall'),
            'challenged' => esc_html__('Challenged', 'botfend-anti-bot-firewall'),
            '404_abuse' => esc_html__('404 Abuse', 'botfend-anti-bot-firewall'),
            'honeypot_triggered' => esc_html__('Honeypot', 'botfend-anti-bot-firewall'),
            'js_challenge' => esc_html__('JS Challenge', 'botfend-anti-bot-firewall'),
            'google_crawler' => esc_html__('Google Crawler', 'botfend-anti-bot-firewall'),
            'allowed' => esc_html__('Allowed', 'botfend-anti-bot-firewall'),
            'sampled' => esc_html__('Sampled', 'botfend-anti-bot-firewall'),
            'rate_limited' => esc_html__('Rate Limited', 'botfend-anti-bot-firewall'),
        ];
        return $labels[$action] ?? ucwords(str_replace('_', ' ', $action));
    }

    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 format_datetime(string $datetime, string $date_format = '', string $time_format = ''): string {
        if (empty($datetime)) return '-';
        if (empty($date_format)) $date_format = get_option('date_format');
        if (empty($time_format)) $time_format = get_option('time_format');
        $timestamp = strtotime($datetime . ' UTC');
        if ($timestamp === false) return $datetime;
        return wp_date($date_format . ' ' . $time_format, $timestamp);
    }

    private function format_action(string $action): string {
        $action_map = [
            'blocked' => ['label' => esc_html__('Blocked', 'botfend-anti-bot-firewall'), 'color' => '#dc3232'],
            'challenged' => ['label' => esc_html__('Challenged', 'botfend-anti-bot-firewall'), 'color' => '#f56e28'],
            '404_abuse' => ['label' => esc_html__('404 Abuse', 'botfend-anti-bot-firewall'), 'color' => '#00a0d2'],
            'honeypot_triggered' => ['label' => esc_html__('Honeypot', 'botfend-anti-bot-firewall'), 'color' => '#8224e3'],
            'js_challenge' => ['label' => esc_html__('JS Challenge', 'botfend-anti-bot-firewall'), 'color' => '#20c997'],
            'google_crawler' => ['label' => esc_html__('Google Crawler', 'botfend-anti-bot-firewall'), 'color' => '#46b450'],
            'allowed' => ['label' => esc_html__('Allowed', 'botfend-anti-bot-firewall'), 'color' => '#646970'],
            'sampled' => ['label' => esc_html__('Sampled', 'botfend-anti-bot-firewall'), 'color' => '#646970'],
            'rate_limited' => ['label' => esc_html__('Rate Limited', 'botfend-anti-bot-firewall'), 'color' => '#d63638'],
        ];

        if (isset($action_map[$action])) {
            $config = $action_map[$action];
            return sprintf(
                '<span class="botfend-action-label" style="--action-color: %s">%s</span>',
                esc_attr($config['color']),
                esc_html($config['label'])
            );
        }

        return '<span class="botfend-action-label" style="--action-color: #646970">' . esc_html($this->get_action_label($action)) . '</span>';
    }

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

    private function format_factors_for_display(string $factors): string {
        if (empty($factors)) return '';
        $decoded = json_decode($factors, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return wp_json_encode($decoded, JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
        }
        return wp_json_encode($factors, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
    }

    /**
     * AJAX refresh logs
     */
    public function ajax_refresh_logs(): void {
        check_ajax_referer('botfend_logs_refresh', 'nonce');

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

        wp_send_json_success([
            'message' => esc_html__('Logs refreshed', 'botfend-anti-bot-firewall'),
            'timestamp' => current_time('mysql'),
        ]);
    }

    public function render(): void {
        if (!current_user_can('manage_options')) return;

        if (!$this->database) {
            echo '<div class="notice notice-error"><p>' . esc_html__('Database component not available.', 'botfend-anti-bot-firewall') . '</p></div>';
            return;
        }

        $bulk_processed = $this->handle_bulk_actions();
        $admin_notices = [];

        if ($bulk_processed !== false) {
            $admin_notices[] = [
                'type' => 'success',
                'message' => sprintf(esc_html__('Bulk action completed: %d items processed.', 'botfend-anti-bot-firewall'), $bulk_processed)
            ];
        }

        $items_per_page = $this->get_config_int('logs_items_per_page', 100);
        $enable_smart_aggregation = $this->get_config_bool('enable_smart_aggregation', true);
        $max_detailed_logs = $this->get_config_int('max_detailed_logs', 300);
        $log_sampling_rate = $this->get_config_int('log_sampling_rate', 10);
        $aggregate_after_hours = $this->get_config_int('aggregate_after_hours', 24);
        $date_format = $this->get_config_string('date_format', get_option('date_format'));
        $time_format = $this->get_config_string('time_format', get_option('time_format'));
        $auto_refresh = $this->get_config_bool('logs_auto_refresh', false);
        $refresh_interval = $this->get_config_int('logs_refresh_interval', 30000);

        if (isset($_GET['clear_logs']) && $_GET['clear_logs'] === 'true') {
            $this->verify_nonce_or_die();
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'botfend-anti-bot-firewall'));
            }
            $result = $this->database->clear_logs();
            if ($result) {
                $admin_notices[] = ['type' => 'success', 'message' => esc_html__('Security logs cleared successfully.', 'botfend-anti-bot-firewall')];
            } else {
                $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Failed to clear security logs.', 'botfend-anti-bot-firewall')];
            }
        }

        if (isset($_GET['clear_aggregates']) && $_GET['clear_aggregates'] === 'true') {
            $this->verify_nonce_or_die();
            if (!current_user_can('manage_options')) {
                wp_die(esc_html__('Insufficient permissions.', 'botfend-anti-bot-firewall'));
            }
            if (method_exists($this->database, 'clear_aggregated_data')) {
                $result = $this->database->clear_aggregated_data();
                if ($result) {
                    $admin_notices[] = ['type' => 'success', 'message' => esc_html__('Aggregated log data cleared successfully.', 'botfend-anti-bot-firewall')];
                } else {
                    $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Failed to clear aggregated log data.', 'botfend-anti-bot-firewall')];
                }
            }
        }

        if (isset($_GET['action']) && $_GET['action'] === 'whitelist' && isset($_GET['ip'])) {
            check_admin_referer('botfend_admin_action');
            $ip = sanitize_text_field(wp_unslash($_GET['ip']));
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                $result = $this->add_to_whitelist($ip);
                if ($result) {
                    $admin_notices[] = ['type' => 'success', 'message' => sprintf(esc_html__('IP %s added to whitelist.', 'botfend-anti-bot-firewall'), esc_html($ip)) . ' <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' => sprintf(esc_html__('Failed to add IP %s to whitelist.', 'botfend-anti-bot-firewall'), esc_html($ip))];
                }
            }
        }

        $distinct_actions = $this->database->get_distinct_actions();

        $raw_filters = [];
        if (!empty($_GET['ip'])) $raw_filters['ip'] = sanitize_text_field(wp_unslash($_GET['ip']));
        if (!empty($_GET['action'])) $raw_filters['action'] = sanitize_text_field(wp_unslash($_GET['action']));
        if (!empty($_GET['min_score'])) $raw_filters['min_score'] = absint(wp_unslash($_GET['min_score']));
        if (!empty($_GET['country'])) $raw_filters['country'] = sanitize_text_field(wp_unslash($_GET['country']));
        if (!empty($_GET['date_from'])) $raw_filters['date_from'] = sanitize_text_field(wp_unslash($_GET['date_from']));
        if (!empty($_GET['date_to'])) $raw_filters['date_to'] = sanitize_text_field(wp_unslash($_GET['date_to']));

        $filters = $this->validate_filters($raw_filters);
        $current_page = isset($_GET['paged']) ? max(1, absint($_GET['paged'])) : 1;
        $offset = ($current_page - 1) * $items_per_page;

        try {
            $logs = $this->get_cached_logs($filters, $items_per_page, 24, $offset);
            if (method_exists($this->database, 'get_logs_count')) {
                $total_items = $this->database->get_logs_count($filters);
            } else {
                $all_logs = $this->database->get_logs_deduplicated($filters, 10000, 24);
                $total_items = count($all_logs);
            }
            $total_pages = ceil($total_items / $items_per_page);
        } catch (\Exception $e) {
            $admin_notices[] = ['type' => 'error', 'message' => esc_html__('Error loading logs: ', 'botfend-anti-bot-firewall') . $e->getMessage()];
            $logs = [];
            $total_items = 0;
            $total_pages = 0;
        }

        $clear_aggregates_url = wp_nonce_url(admin_url('admin.php?page=botfend-logs&clear_aggregates=true'), 'botfend_admin_action', '_wpnonce');
        $clear_logs_url = wp_nonce_url(admin_url('admin.php?page=botfend-logs&clear_logs=true'), 'botfend_admin_action', '_wpnonce');

        $bulk_actions = [
            'block_selected' => esc_html__('Block Selected IPs', 'botfend-anti-bot-firewall'),
            'whitelist_selected' => esc_html__('Whitelist Selected IPs', 'botfend-anti-bot-firewall'),
            'delete_selected' => esc_html__('Delete Selected', 'botfend-anti-bot-firewall'),
        ];
        ?>
        
        
        
<div class="wrap botfend-wrap">
    <div class="botfend-header-area">
        <h1 class="wp-heading-inline botfend-page-title">
            <?php echo esc_html__('Security Logs', 'botfend-anti-bot-firewall'); ?>
            <?php if ($auto_refresh): ?>
                <span class="botfend-badge botfend-badge-info"><span class="dashicons dashicons-update"></span> <?php esc_html_e('Auto-refresh active', 'botfend-anti-bot-firewall'); ?></span>
            <?php endif; ?>
        </h1>
        
        <div class="botfend-header-actions">
            <a href="#" class="button botfend-btn-danger" id="clear-logs-btn" data-url="<?php echo esc_url($clear_logs_url); ?>">
                <span class="dashicons dashicons-trash"></span> <?php echo esc_html__('Clear All Logs', 'botfend-anti-bot-firewall'); ?>
            </a>
            <a href="#" class="button" id="clear-aggregates-btn" data-url="<?php echo esc_url($clear_aggregates_url); ?>">
                <span class="dashicons dashicons-chart-area"></span> <?php echo esc_html__('Clear Aggregated Data', 'botfend-anti-bot-firewall'); ?>
            </a>
        </div>
    </div>
    
    <!-- Refresh bar - separate line -->
    <div class="botfend-refresh-bar" style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px; padding: 10px 15px; background: #f0f6fc; border: 1px solid #c8d8e8; border-radius: 6px;">
        <button type="button" class="button botfend-refresh-logs">
            <span class="dashicons dashicons-update"></span>
            <?php esc_html_e('Refresh Data', 'botfend-anti-bot-firewall'); ?>
        </button>
        <span style="color: #50575e; font-size: 12px;">
            <?php esc_html_e('Click to reload the latest security logs', 'botfend-anti-bot-firewall'); ?>
        </span>
    </div>
    
    <hr class="wp-header-end">
    <!-- rest of the page continues... -->

            
            
            
            
            
            <?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; ?>

            <?php if ($enable_smart_aggregation): ?>
                <?php
                $stats = $this->database->get_dashboard_stats();
                $detailed_count = $stats['detailed_logs_count'] ?? 0;
                $aggregated_count = $stats['aggregated_logs_count'] ?? 0;
                ?>
                <div class="botfend-smart-agg-notice">
                    <div class="botfend-agg-header">
                        <span class="dashicons dashicons-shield"></span>
                        <strong><?php echo esc_html__('Smart Aggregation Active', 'botfend-anti-bot-firewall'); ?></strong>
                    </div>
                    <div class="botfend-smart-agg-stats">
                        <div class="botfend-smart-agg-stat">
                            <span class="dashicons dashicons-database"></span>
                            <span>
                                <?php
                                printf(
                                    esc_html__('Detailed logs: %1$d (max: %2$d) • Aggregated: %3$d', 'botfend-anti-bot-firewall'),
                                    absint($detailed_count),
                                    absint($max_detailed_logs),
                                    absint($aggregated_count)
                                );
                                ?>
                            </span>
                        </div>
                        <div class="botfend-smart-agg-stat">
                            <span class="dashicons dashicons-admin-settings"></span>
                            <span>
                                <?php
                                printf(
                                    esc_html__('Sampling rate: %1$d%% • Aggregating after %2$d hours', 'botfend-anti-bot-firewall'),
                                    absint($log_sampling_rate),
                                    absint($aggregate_after_hours)
                                );
                                ?>
                            </span>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <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 Logs', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content" style="padding-top: 15px;">
                        <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>" class="botfend-filter-form">
                            <input type="hidden" name="page" value="botfend-logs">
                            <input type="hidden" name="paged" value="1">
                            <div class="botfend-filter-grid">
                                <div class="botfend-filter-group">
                                    <label for="filter-ip" class="botfend-filter-label"><?php echo esc_html__('IP Address', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="text" id="filter-ip" name="ip" class="botfend-filter-input" placeholder="<?php echo esc_attr__('e.g., 192.168.1.1', 'botfend-anti-bot-firewall'); ?>" value="<?php echo isset($filters['ip']) ? esc_attr($filters['ip']) : ''; ?>">
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-action" class="botfend-filter-label"><?php echo esc_html__('Action Taken', 'botfend-anti-bot-firewall'); ?></label>
                                    <select id="filter-action" name="action" class="botfend-filter-select">
                                        <option value=""><?php echo esc_html__('All Actions', 'botfend-anti-bot-firewall'); ?></option>
                                        <?php foreach ($distinct_actions as $action): ?>
                                            <option value="<?php echo esc_attr($action); ?>" <?php selected(isset($filters['action']) ? $filters['action'] : '', $action); ?>>
                                                <?php echo esc_html($this->get_action_label($action)); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-min-score" class="botfend-filter-label"><?php echo esc_html__('Min Threat Score', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="number" id="filter-min-score" name="min_score" class="botfend-filter-input" placeholder="0 - 10" min="0" max="10" value="<?php echo isset($filters['min_score']) ? esc_attr($filters['min_score']) : ''; ?>">
                                </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="country" class="botfend-filter-input" placeholder="<?php echo esc_attr__('e.g., US, NG', 'botfend-anti-bot-firewall'); ?>" value="<?php echo isset($filters['country']) ? esc_attr($filters['country']) : ''; ?>" pattern="[A-Z]{2}" maxlength="2">
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-date-from" class="botfend-filter-label"><?php echo esc_html__('From Date', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="date" id="filter-date-from" name="date_from" class="botfend-filter-input" value="<?php echo isset($filters['date_from']) ? esc_attr($filters['date_from']) : ''; ?>" max="<?php echo esc_attr(gmdate('Y-m-d')); ?>">
                                </div>
                                <div class="botfend-filter-group">
                                    <label for="filter-date-to" class="botfend-filter-label"><?php echo esc_html__('To Date', 'botfend-anti-bot-firewall'); ?></label>
                                    <input type="date" id="filter-date-to" name="date_to" class="botfend-filter-input" value="<?php echo isset($filters['date_to']) ? esc_attr($filters['date_to']) : ''; ?>" max="<?php echo esc_attr(gmdate('Y-m-d')); ?>">
                                </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-logs')); ?>" class="button botfend-btn-outline"><?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__('Traffic Log Results', 'botfend-anti-bot-firewall'); ?>
                    </summary>
                    <div class="botfend-section-content" style="padding: 20px;">
                        <?php if (empty($logs)): ?>
                            <div class="botfend-empty-state">
                                <span class="dashicons dashicons-shield-alt"></span>
                                <h3><?php echo esc_html__('No security logs found', 'botfend-anti-bot-firewall'); ?></h3>
                                <p><?php echo esc_html__('Everything looks secure. Try adjusting your filters.', 'botfend-anti-bot-firewall'); ?></p>
                            </div>
                        <?php else: ?>
                            <form method="post" action="" id="botfend-logs-form">
                                <?php wp_nonce_field('botfend_admin_action'); ?>
                                <input type="hidden" name="selected_ips" id="selected-ips" value="">
                                
                                <div class="botfend-table-toolbar">
                                    <div class="botfend-bulk-actions">
                                        <select name="bulk_action" id="bulk-action-selector">
                                            <option value=""><?php esc_html_e('Bulk Actions', 'botfend-anti-bot-firewall'); ?></option>
                                            <?php foreach ($bulk_actions as $value => $label): ?>
                                                <option value="<?php echo esc_attr($value); ?>"><?php echo esc_html($label); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="submit" class="button" name="apply_bulk_action" id="bulk-action-button" disabled><?php esc_html_e('Apply', 'botfend-anti-bot-firewall'); ?></button>
                                    </div>
                                    <div class="botfend-log-stats">
                                        <?php printf(esc_html__('Showing %1$d of %2$d logs', 'botfend-anti-bot-firewall'), count($logs), absint($total_items)); ?>
                                    </div>
                                </div>

                                <div class="botfend-table-responsive" style="margin-top: 15px;">
                                    <table class="wp-list-table widefat fixed striped botfend-logs-table">
                                        <thead>
                                            <tr>
                                                <th class="botfend-col-checkbox manage-column column-cb check-column"><input type="checkbox" id="select-all-logs"></th>
                                                <th class="botfend-col-time"><?php echo esc_html__('Time', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-ip"><?php echo esc_html__('IP Address', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-country"><?php echo esc_html__('Location', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-score"><?php echo esc_html__('Score', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-action"><?php echo esc_html__('Result', 'botfend-anti-bot-firewall'); ?></th>
                                                <th class="botfend-col-details" style="text-align: right;"><?php echo esc_html__('Context', 'botfend-anti-bot-firewall'); ?></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $block_url_base = admin_url('admin.php?page=botfend-blocklist&action=block&ip=');
                                            $filter_url_base = admin_url('admin.php?page=botfend-logs&ip=');

                                            foreach ($logs as $log):
                                                $block_url = wp_nonce_url($block_url_base . rawurlencode(sanitize_text_field($log->ip)), 'botfend_admin_action', '_wpnonce');
                                                $filter_url = add_query_arg('ip', rawurlencode(sanitize_text_field($log->ip)), admin_url('admin.php?page=botfend-logs'));
                                                $whitelist_url = wp_nonce_url(admin_url('admin.php?page=botfend-logs&action=whitelist&ip=' . rawurlencode($log->ip)), 'botfend_admin_action');
                                            ?>
                                            <tr class="botfend-log-row">
                                                <td class="botfend-col-checkbox check-column" data-label="<?php esc_attr_e('Select', 'botfend-anti-bot-firewall'); ?>">
                                                    <input type="checkbox" name="log_checkbox[]" value="<?php echo esc_attr($log->ip); ?>" class="log-checkbox">
                                                </td>
                                                <td class="botfend-col-time" data-label="<?php esc_attr_e('Time', 'botfend-anti-bot-firewall'); ?>">
                                                    <span class="botfend-time-cell"><?php echo esc_html($this->format_datetime($log->created_at, $date_format, $time_format)); ?></span>
                                                </td>
                                                <td class="botfend-col-ip" data-label="<?php esc_attr_e('IP Address', 'botfend-anti-bot-firewall'); ?>">
                                                    <div class="botfend-ip-cell">
                                                        <code class="botfend-ip-address"><?php echo esc_html($log->ip); ?></code>
                                                        <?php if ($this->database->is_ip_blocked($log->ip)): ?>
                                                            <span class="dashicons dashicons-lock botfend-blocked-icon" title="<?php esc_attr_e('Currently blocked', '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($log->country)): ?>
                                                        <div class="botfend-country-cell"><span class="botfend-country-flag"><?php echo esc_html($log->country); ?></span></div>
                                                    <?php else: ?>
                                                        <span class="botfend-unknown">—</span>
                                                    <?php endif; ?>
                                                </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($this->get_score_color(absint($log->score))); ?>" title="<?php esc_attr_e('Threat Score out of 10', 'botfend-anti-bot-firewall'); ?>"><?php echo esc_html($log->score); ?></div>
                                                </td>
                                                <td class="botfend-col-action" data-label="<?php esc_attr_e('Result', 'botfend-anti-bot-firewall'); ?>"><?php echo $this->format_action($log->action); ?></td>
                                                <td class="botfend-col-details" 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-log-id="<?php echo esc_attr($log->id); ?>">
                                                            <span class="dashicons dashicons-ellipsis"></span>
                                                        </button>
                                                        <div class="botfend-details-content" id="details-<?php echo esc_attr($log->id); ?>">
                                                            <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($log->http_method ?? 'GET'); ?></span></div>
                                                                <div class="botfend-detail-item"><span class="botfend-detail-label"><?php esc_html_e('Path:', 'botfend-anti-bot-firewall'); ?></span><span class="botfend-detail-value code-path" title="<?php echo esc_attr($log->request_uri ?? ''); ?>"><?php echo esc_html($this->truncate_text($log->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($log->user_agent ?? ''); ?>"><?php echo esc_html($this->truncate_text($log->user_agent ?? '', 40)); ?></span></div>
                                                                <?php if (!empty($log->duplicate_count) && $log->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($log->duplicate_count); ?></span></div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div class="botfend-actions-row">
                                                                <?php if (!empty($log->factors)): ?>
                                                                    <button type="button" class="button botfend-action-button botfend-factors-button" data-factors='<?php echo esc_attr($this->format_factors_for_display($log->factors)); ?>'><?php echo esc_html__('View Analysis JSON', 'botfend-anti-bot-firewall'); ?></button>
                                                                <?php endif; ?>
                                                                <a href="<?php echo esc_url($filter_url); ?>" class="button botfend-action-button"><?php echo esc_html__('Filter IP', 'botfend-anti-bot-firewall'); ?></a>
                                                                <a href="<?php echo esc_url($whitelist_url); ?>" class="button botfend-action-button botfend-btn-success" onclick="return confirm('<?php echo esc_js(sprintf(esc_html__('Add IP %s to whitelist?', 'botfend-anti-bot-firewall'), $log->ip)); ?>');"><?php echo esc_html__('Whitelist IP', 'botfend-anti-bot-firewall'); ?></a>
                                                                <a href="<?php echo esc_url($block_url); ?>" class="button botfend-action-button botfend-btn-danger" onclick="return confirm('<?php echo esc_js(sprintf(esc_html__('Block IP address %s?', 'botfend-anti-bot-firewall'), $log->ip)); ?>');"><?php echo esc_html__('Block IP', 'botfend-anti-bot-firewall'); ?></a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </form>

                            <?php if ($total_pages > 1): ?>
                            <div class="botfend-pagination-wrapper">
                                <div class="botfend-pagination-links">
                                    <?php
                                    echo paginate_links([
                                        'base' => add_query_arg('paged', '%#%'),
                                        'format' => '',
                                        'prev_text' => '<span class="dashicons dashicons-arrow-left-alt2"></span>',
                                        'next_text' => '<span class="dashicons dashicons-arrow-right-alt2"></span>',
                                        'total' => $total_pages,
                                        'current' => $current_page,
                                        'add_args' => array_filter(['ip' => $filters['ip'] ?? null, 'action' => $filters['action'] ?? null, 'min_score' => $filters['min_score'] ?? null, 'country' => $filters['country'] ?? null, 'date_from' => $filters['date_from'] ?? null, 'date_to' => $filters['date_to'] ?? null])
                                    ]);
                                    ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </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>

        <div class="clearing-progress" id="clearing-progress">
            <span class="spinner is-active" style="float:none; margin-right: 10px;"></span>
            <h3><?php esc_html_e('Processing...', 'botfend-anti-bot-firewall'); ?></h3>
            <p><?php esc_html_e('Please wait while your request is processed.', 'botfend-anti-bot-firewall'); ?></p>
        </div>
        <?php
    }
}