<?php

/**
 * Guard Dog Activity Log Page
 * 
 * Enhanced activity log management with comprehensive event tracking,
 * inspired by the proven Elementor Activity Log plugin.
 *
 * @package GuardDog
 * @since 1.8.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class Guard_Dog_Activity_Log_Page {

    /**
     * Shared handle used by the admin asset loader for this page script.
     */
    private const PAGE_ASSET_HANDLE = 'guard-dog-guard-dog-logs';

    /**
     * Query arg used for the Activity Log tabs.
     */
    private const TAB_QUERY_ARG = 'activity_log_tab';

    /**
     * Feature instances
     * @var array
     */
    private $features;

    /**
     * Current active tab
     * @var string
     */
    private $current_tab;

    /**
     * Available tabs configuration
     * @var array
     */
    private $tabs;

    /**
     * Constructor
     *
     * @param array $features Feature class instances
     */
    public function __construct(array $features = []) {
        $this->features = $features;
        $this->initialize_tabs();
        $this->determine_current_tab();
    }

    /**
     * Initialize tabs configuration
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'logs' => [
                'label' => __('Activity Logs', 'guard-dog'),
                'icon' => 'dashicons-list-view'
            ],
            'settings' => [
                'label' => __('Event Settings', 'guard-dog'),
                'icon' => 'dashicons-admin-settings'
            ],
            'export' => [
                'label' => __('Export & Cleanup', 'guard-dog'),
                'icon' => 'dashicons-admin-tools'
            ]
        ];
    }

    /**
     * Get relevant POST keys for activity log debug logging (only activity log-specific fields)
     *
     * @return array Array of relevant POST keys
     */
    private function get_relevant_activity_log_post_keys(): array {
        $relevant_keys = [];
        $expected_keys = ['_wpnonce', 'action', 'cleanup_days', 'cleanup_event_types', 'cleanup_logs_nonce', 'auto_cleanup_nonce', 'execute_cleanup_nonce'];
        
        foreach ($expected_keys as $key) {
            if (isset($_POST[$key])) {
                $relevant_keys[] = $key;
            }
        }
        
        return $relevant_keys;
    }

    /**
     * Determine the current active tab
     */
    private function determine_current_tab(): void {
        // Default tab
        $this->current_tab = 'logs';

        $tab_param = $this->get_requested_tab();
        if ($tab_param && array_key_exists($tab_param, $this->tabs)) {
            $this->current_tab = $tab_param;
        }
    }

    /**
     * Get the requested Activity Log tab from the current request.
     *
     * Supports the new dedicated query arg and the legacy nonce-protected tab
     * links so older URLs continue to work during the transition.
     */
    private function get_requested_tab(): string {
        if (isset($_GET[self::TAB_QUERY_ARG])) {
            return sanitize_text_field(wp_unslash($_GET[self::TAB_QUERY_ARG]));
        }

        if (isset($_GET['tab']) && isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'guard_dog_activity_log_tab')) {
            return sanitize_text_field(wp_unslash($_GET['tab']));
        }

        return '';
    }

    /**
     * Build an Activity Log admin URL with the new tab query arg.
     *
     * @param array $args Additional query args.
     * @return string
     */
    private static function build_activity_log_url(array $args = []): string {
        return add_query_arg(
            array_merge(['page' => 'guard-dog-logs'], $args),
            admin_url('admin.php')
        );
    }

    /**
     * Build a URL for a specific Activity Log tab.
     *
     * @param string $tab_id Tab identifier.
     * @param array  $extra_args Extra query args to append.
     * @return string
     */
    private function get_tab_url(string $tab_id, array $extra_args = []): string {
        return self::build_activity_log_url(
            array_merge(
                [self::TAB_QUERY_ARG => $tab_id],
                $extra_args
            )
        );
    }

    /**
     * Render the activity log page
     */
    public function render(): void {
        // Enqueue assets
        $this->enqueue_assets();
        
        // Prepare data for partials
        $this->prepare_page_data();
        
        // Render main page with integrated tabs
        $this->render_page_with_tabs();
    }

    /**
     * Render the page with integrated tabbed interface
     */
    private function render_page_with_tabs(): void {
        // Get data from global variables
        $activity_log_data = $GLOBALS['guard_dog_activity_log_data'] ?? [];
        
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-list-view"></span>
                <?php esc_html_e('Activity Log', 'guard-dog'); ?>
            </h1>
            
            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Comprehensive security and activity monitoring for your WordPress site.', 'guard-dog'); ?>
            </p>

            <div class="guard-dog-admin-grid">
                <div class="guard-dog-main-content">
                    <!-- Integrated Tabbed Interface -->
                    <div class="guard-dog-tabbed-interface">
                        <nav class="guard-dog-tab-nav">
                            <?php foreach ($this->tabs as $tab_id => $tab_config): ?>
                                <a href="<?php echo esc_url($this->get_tab_url($tab_id)); ?>" 
                                   class="guard-dog-tab-link<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>" 
                                   data-tab="<?php echo esc_attr($tab_id); ?>"
                                   data-storage-key="guard_dog_activity_log_active_tab"
                                   data-query-param="<?php echo esc_attr(self::TAB_QUERY_ARG); ?>">
                                    <?php if (isset($tab_config['icon'])): ?>
                                        <span class="dashicons <?php echo esc_attr($tab_config['icon']); ?>"></span>
                                    <?php endif; ?>
                                    <?php echo esc_html($tab_config['label']); ?>
                                </a>
                            <?php endforeach; ?>
                        </nav>

                        <div class="guard-dog-tab-content">
                            <?php foreach ($this->tabs as $tab_id => $tab_config): ?>
                                <div id="<?php echo esc_attr($tab_id); ?>" 
                                     class="guard-dog-tab-panel<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>">
                                    <?php $this->render_tab_content($tab_id, $activity_log_data); ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="guard-dog-sidebar">
                    <?php $this->render_activity_stats($activity_log_data['stats'] ?? [], $activity_log_data['filter_days'] ?? 30); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render content for a specific tab
     *
     * @param string $tab_id The tab identifier
     * @param array $data The page data
     */
    private function render_tab_content(string $tab_id, array $data): void {
        switch ($tab_id) {
            case 'logs':
                $this->render_logs_tab($data);
                break;
            case 'settings':
                $this->render_settings_tab($data);
                break;
            case 'export':
                $this->render_export_tab($data);
                break;
            default:
                ?>
                <p><?php esc_html_e('Invalid tab selected.', 'guard-dog'); ?></p>
                <?php
                break;
        }
    }

    /**
     * Render the logs tab content
     *
     * @param array $data The page data
     */
    private function render_logs_tab(array $data): void {
        $filter_type = $data['filter_type'] ?? 'all';
        $filter_user = $data['filter_user'] ?? '';
        $filter_days = $data['filter_days'] ?? 30;
        $search = $data['search'] ?? '';
        $page = $data['page'] ?? 1;
        $logs = $data['logs'] ?? [];
        $stats = $data['stats'] ?? [];
        $pagination = $data['pagination'] ?? [];
        
        ?>
        <h3>
            <span class="dashicons dashicons-list-view"></span>
            <?php esc_html_e('Activity Logs', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('View and filter security events and user activity on your WordPress site.', 'guard-dog'); ?></p>

        <?php $this->render_activity_filters($filter_type, $filter_user, $filter_days, $search); ?>

        <?php $this->render_activity_table($logs, $page); ?>
        
        <?php if (!empty($pagination) && $pagination['total_pages'] > 1): ?>
            <?php $this->render_pagination($pagination); ?>
        <?php endif; ?>
        <?php
    }

    /**
     * Render the settings tab content
     *
     * @param array $data The page data
     */
    private function render_settings_tab(array $data): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-settings"></span>
            <?php esc_html_e('Event Logging Settings', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure how activity logs are stored and managed on your WordPress site.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-activity-log-settings-form">
            <?php 
            settings_fields('guard_dog_activity_log_settings_group');
            do_settings_sections('guard_dog_activity_log_settings_group');
            ?>
            <?php submit_button(__('Save Settings', 'guard-dog')); ?>
        </form>

        <div class="guard-dog-settings-section">
            <h3><?php esc_html_e('Event Type Configuration', 'guard-dog'); ?></h3>
            <p><?php esc_html_e('Select which types of events should be logged:', 'guard-dog'); ?></p>
            
            <form method="post" action="options.php" class="guard-dog-event-types-form">
                <?php 
                settings_fields('guard_dog_event_types_group');
                do_settings_sections('guard_dog_event_types_group');
                ?>
                <?php submit_button(__('Save Event Types', 'guard-dog')); ?>
            </form>
        </div>
        <?php
    }

    /**
     * Render the export tab content
     *
     * @param array $data The page data
     */
    private function render_export_tab(array $data): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-tools"></span>
            <?php esc_html_e('Export & Cleanup', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Export your activity logs for backup or analysis, and clean up old logs to free up database space.', 'guard-dog'); ?></p>

        <div class="guard-dog-export-section">
            <h3><?php esc_html_e('Export Activity Logs', 'guard-dog'); ?></h3>
            
            <p><?php esc_html_e('Export your activity logs for backup or analysis purposes:', 'guard-dog'); ?></p>
            
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="guard-dog-export-form">
                <input type="hidden" name="action" value="guard_dog_export_logs">
                <?php wp_nonce_field('guard_dog_export_logs', 'export_logs_nonce'); ?>
                
                <table class="guard-dog-form-table">
                    <tr>
                        <th scope="row">
                            <label for="export_format"><?php esc_html_e('Export Format', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <select name="export_format" id="export_format">
                                <option value="csv"><?php esc_html_e('CSV (Comma Separated Values)', 'guard-dog'); ?></option>
                                <option value="json"><?php esc_html_e('JSON (JavaScript Object Notation)', 'guard-dog'); ?></option>
                                <option value="xml"><?php esc_html_e('XML (Extensible Markup Language)', 'guard-dog'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Choose the format for your exported data.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="export_date_range"><?php esc_html_e('Date Range', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <select name="export_date_range" id="export_date_range">
                                <option value="all"><?php esc_html_e('All logs', 'guard-dog'); ?></option>
                                <option value="today"><?php esc_html_e('Today', 'guard-dog'); ?></option>
                                <option value="yesterday"><?php esc_html_e('Yesterday', 'guard-dog'); ?></option>
                                <option value="last_7_days"><?php esc_html_e('Last 7 days', 'guard-dog'); ?></option>
                                <option value="last_30_days"><?php esc_html_e('Last 30 days', 'guard-dog'); ?></option>
                                <option value="last_90_days"><?php esc_html_e('Last 90 days', 'guard-dog'); ?></option>
                                <option value="custom"><?php esc_html_e('Custom range', 'guard-dog'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Select the time period for your export.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr class="custom-date-range guard-dog-custom-date-range">
                        <th scope="row">
                            <label for="export_start_date"><?php esc_html_e('Start Date', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="date" name="export_start_date" id="export_start_date" />
                            <p class="description"><?php esc_html_e('Start date for custom range (inclusive).', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr class="custom-date-range guard-dog-custom-date-range">
                        <th scope="row">
                            <label for="export_end_date"><?php esc_html_e('End Date', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="date" name="export_end_date" id="export_end_date" />
                            <p class="description"><?php esc_html_e('End date for custom range (inclusive).', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="export_event_types"><?php esc_html_e('Event Types', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <select name="export_event_types[]" id="export_event_types" multiple="multiple" size="6">
                                <option value="all" selected><?php esc_html_e('All event types', 'guard-dog'); ?></option>
                                <option value="security"><?php esc_html_e('Security Events', 'guard-dog'); ?></option>
                                <option value="users"><?php esc_html_e('User Events', 'guard-dog'); ?></option>
                                <option value="content"><?php esc_html_e('Content Events', 'guard-dog'); ?></option>
                                <option value="system"><?php esc_html_e('System Events', 'guard-dog'); ?></option>
                                <?php if (class_exists('WooCommerce')): ?>
                                <option value="woocommerce"><?php esc_html_e('WooCommerce Events', 'guard-dog'); ?></option>
                                <?php endif; ?>
                            </select>
                            <p class="description"><?php esc_html_e('Hold Ctrl/Cmd to select multiple event types.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="export_include_details"><?php esc_html_e('Include Details', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="export_include_details" value="1" checked />
                                <?php esc_html_e('Include detailed event information', 'guard-dog'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('Include additional context and metadata for each event.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button(__('Export Logs', 'guard-dog')); ?>
            </form>
        </div>

        <div class="guard-dog-auto-cleanup-section">
            <h3><?php esc_html_e('Automatic Cleanup', 'guard-dog'); ?></h3>
            
            <p><?php esc_html_e('Trigger automatic cleanup based on your configured retention and maximum entry settings:', 'guard-dog'); ?></p>
            
            <form method="post" action="" class="guard-dog-auto-cleanup-form">
                <?php wp_nonce_field('guard_dog_auto_cleanup', 'auto_cleanup_nonce'); ?>
                <input type="hidden" name="action" value="auto_cleanup_now" />
                
                <p class="description">
                    <?php esc_html_e('This will apply your configured retention period and maximum entries limit settings.', 'guard-dog'); ?>
                </p>
                
                <?php submit_button(__('Run Automatic Cleanup Now', 'guard-dog'), 'secondary', 'submit', false); ?>
            </form>
        </div>

        <div class="guard-dog-cleanup-section">
            <h3><?php esc_html_e('Manual Cleanup', 'guard-dog'); ?></h3>
            
            <p><?php esc_html_e('Remove old activity logs manually with custom parameters:', 'guard-dog'); ?></p>
            
            <form method="post" action="" class="guard-dog-cleanup-form">
                <?php wp_nonce_field('guard_dog_cleanup_logs', 'cleanup_logs_nonce'); ?>
                
                <table class="guard-dog-form-table">
                    <tr>
                        <th scope="row">
                            <label for="cleanup_days"><?php esc_html_e('Delete Logs Older Than', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <select name="cleanup_days" id="cleanup_days">
                                <option value="0"><?php esc_html_e('All entries', 'guard-dog'); ?></option>
                                <option value="30" selected><?php esc_html_e('30 days', 'guard-dog'); ?></option>
                                <option value="60"><?php esc_html_e('60 days', 'guard-dog'); ?></option>
                                <option value="90"><?php esc_html_e('90 days', 'guard-dog'); ?></option>
                                <option value="180"><?php esc_html_e('6 months', 'guard-dog'); ?></option>
                                <option value="365"><?php esc_html_e('1 year', 'guard-dog'); ?></option>
                            </select>
                            <p class="description"><?php esc_html_e('Select age criteria for logs to delete. "All entries" will delete ALL activity logs permanently.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="cleanup_event_types"><?php esc_html_e('Event Types to Cleanup', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <!-- Hidden input as fallback to ensure we always get a value -->
                            <input type="hidden" name="cleanup_event_types[]" value="all" id="cleanup_fallback" />
                            <select name="cleanup_event_types[]" id="cleanup_event_types" multiple="multiple" size="6">
                                <option value="all" selected><?php esc_html_e('All event types', 'guard-dog'); ?></option>
                                <option value="security"><?php esc_html_e('Security Events', 'guard-dog'); ?></option>
                                <option value="users"><?php esc_html_e('User Events', 'guard-dog'); ?></option>
                                <option value="content"><?php esc_html_e('Content Events', 'guard-dog'); ?></option>
                                <option value="system"><?php esc_html_e('System Events', 'guard-dog'); ?></option>
                                <?php if (class_exists('WooCommerce')): ?>
                                <option value="woocommerce"><?php esc_html_e('WooCommerce Events', 'guard-dog'); ?></option>
                                <?php endif; ?>
                            </select>
                            <p class="description"><?php esc_html_e('Hold Ctrl/Cmd to select multiple event types.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="cleanup_preview"><?php esc_html_e('Preview Before Deletion', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <label>
                                <input type="checkbox" name="cleanup_preview" value="1" checked />
                                <?php esc_html_e('Show preview of logs that will be deleted', 'guard-dog'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('Review the logs before confirming deletion.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                </table>
                
                <input type="hidden" name="action" value="preview_cleanup" />
                <?php submit_button(__('Preview Cleanup', 'guard-dog'), 'secondary'); ?>
            </form>
        </div>

        <?php $this->render_cleanup_preview(); ?>

        <div class="guard-dog-stats-section">
            <h3><?php esc_html_e('Current Log Statistics', 'guard-dog'); ?></h3>
            
            <table class="guard-dog-form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Total Log Entries', 'guard-dog'); ?></th>
                    <td><?php echo esc_html(Guard_Dog()->activity_log->get_total_logs_count()); ?></td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Oldest Log Entry', 'guard-dog'); ?></th>
                    <td><?php 
                        $oldest_log = Guard_Dog()->activity_log->get_oldest_log();
                        if ($oldest_log) {
                            echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($oldest_log['timestamp'])));
                        } else {
                            esc_html_e('No logs found', 'guard-dog');
                        }
                    ?></td>
                </tr>
                <tr>
                    <th scope="row"><?php esc_html_e('Database Size', 'guard-dog'); ?></th>
                    <td><?php 
                        $table_size = Guard_Dog()->activity_log->get_table_size();
                        echo esc_html(size_format($table_size));
                    ?></td>
                </tr>
            </table>
        </div>
        <?php
    }



    /**
     * Enqueue CSS and JavaScript assets
     */
    private function enqueue_assets(): void {
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            Guard_Dog()->debug->debug('Enqueuing activity log page assets');
        }

        if (!wp_style_is(self::PAGE_ASSET_HANDLE, 'enqueued') && !wp_style_is('guard-dog-activity-log-page', 'enqueued')) {
            wp_enqueue_style(
                'guard-dog-activity-log-page',
                GUARD_DOG_URL . 'assets/css/guard-dog-activity-log-page.css',
                ['guard-dog-admin'],
                GUARD_DOG_VERSION
            );
        }

        $script_handle = self::PAGE_ASSET_HANDLE;

        if (!wp_script_is($script_handle, 'enqueued') && !wp_script_is('guard-dog-activity-log-page', 'enqueued')) {
            $script_handle = 'guard-dog-activity-log-page';
            wp_enqueue_script(
                $script_handle,
                GUARD_DOG_URL . 'assets/js/guard-dog-activity-log-page.js',
                ['jquery', 'guard-dog-admin'],
                GUARD_DOG_VERSION,
                true
            );
        } elseif (!wp_script_is($script_handle, 'enqueued')) {
            $script_handle = 'guard-dog-activity-log-page';
        }

        wp_localize_script($script_handle, 'guard_dog_activity_log', [
            'nonce' => wp_create_nonce('guard_dog_activity_log_nonce'),
            'adminNonce' => wp_create_nonce('guard_dog_admin'),
            'ajaxurl' => admin_url('admin-ajax.php'),
            'strings' => [
                'checking' => __('Checking IP reputation...', 'guard-dog'),
                'error' => __('An error occurred while checking IP reputation.', 'guard-dog'),
                'addToBlacklist' => __('Add to Blacklist', 'guard-dog'),
                'adding' => __('Adding...', 'guard-dog'),
                'addedToBlacklist' => __('IP address has been added to the blacklist.', 'guard-dog'),
                'alreadyInBlacklist' => __('This IP address is already in the blacklist.', 'guard-dog'),
                'close' => __('Close', 'guard-dog'),
                'expirationDays' => __('Expiration (days)', 'guard-dog'),
                'defaultExpiration' => 30,
                'ipReputationCheck' => __('IP Reputation Check', 'guard-dog'),
                'ipAddress' => __('IP Address', 'guard-dog'),
                'abuseConfidence' => __('Abuse Confidence', 'guard-dog'),
                'totalReports' => __('Total Reports', 'guard-dog'),
                'reportedBy' => __('Reported By', 'guard-dog'),
                'users' => __('users', 'guard-dog'),
                'country' => __('Country', 'guard-dog'),
                'isp' => __('ISP', 'guard-dog'),
                'threatIndicators' => __('Threat Indicators', 'guard-dog'),
                'noThreats' => __('No known threats detected.', 'guard-dog'),
                'reputationInfo' => __('Reputation Information', 'guard-dog'),
                'locationInfo' => __('Location Information', 'guard-dog'),
                'networkInfo' => __('Network Information', 'guard-dog'),
                'reverseDns' => __('Reverse DNS', 'guard-dog'),
                'lastReported' => __('Last Reported', 'guard-dog'),
                'continent' => __('Continent', 'guard-dog'),
                'region' => __('Region', 'guard-dog'),
                'city' => __('City', 'guard-dog'),
                'timezone' => __('Timezone', 'guard-dog'),
                'organization' => __('Organization', 'guard-dog'),
                'asNumber' => __('AS Number', 'guard-dog'),
                'usageType' => __('Usage Type', 'guard-dog'),
                'networkType' => __('Network Type', 'guard-dog'),
                'proxy' => __('Proxy/VPN', 'guard-dog'),
                'hosting' => __('Hosting', 'guard-dog'),
                'mobile' => __('Mobile', 'guard-dog'),
            ]
        ]);
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            Guard_Dog()->debug->debug('Activity log page assets enqueued');
        }
    }

    /**
     * Safely extract GET parameters for display-only filtering
     * These parameters are used for URL-based navigation and filtering, not for security-sensitive operations
     *
     * @return array Sanitized GET parameters
     */
    private function get_safe_get_parameters(): array {
        $params = [];
        
        // Only extract specific parameters we need for filtering and pagination
        $allowed_params = [self::TAB_QUERY_ARG, 'filter_category', 'filter_user', 'filter_days', 'search', 'paged'];
        
        foreach ($allowed_params as $param) {
            if (isset($_GET[$param])) {
                switch ($param) {
                    case 'filter_days':
                    case 'paged':
                        $params[$param] = intval(wp_unslash($_GET[$param]));
                        break;
                    default:
                        $params[$param] = sanitize_text_field(wp_unslash($_GET[$param]));
                        break;
                }
            }
        }
        
        return $params;
    }

    /**
     * Prepare data for page partials
     */
    private function prepare_page_data(): void {
        // Handle POST form submissions first
        $this->handle_form_submissions();
        
        // Safely extract GET parameters for display-only filtering
        $get_params = $this->get_safe_get_parameters();
        
        // Get current tab from URL or default to 'logs'
        $current_tab = $this->get_requested_tab() ?: 'logs';
        
        // Get filter parameters (display-only GET parameters, no security risk)
        $filter_category = $get_params['filter_category'] ?? 'all';
        $filter_user = $get_params['filter_user'] ?? '';
        $filter_days = $get_params['filter_days'] ?? 30;
        $search = $get_params['search'] ?? '';
        $page = $get_params['paged'] ?? 1;
        
        // Get activity logs for logs tab
        if ($current_tab === 'logs') {
            $activity_log = new Guard_Dog_Activity_Log();
            // Get per-page setting from screen options (WordPress uses get_user_option for screen options)
            $per_page = (int) get_user_option('guard_dog_activity_logs_per_page');
            if (empty($per_page) || $per_page < 1) {
                $per_page = 20; // Default fallback
            }
            $filters = [
                'category' => $filter_category !== 'all' ? $filter_category : '',
                'search' => $search,
                'date_from' => gmdate('Y-m-d', strtotime("-{$filter_days} days")),
                'page' => $page,
                'per_page' => $per_page
            ];
            
            $logs = $activity_log->get_logs($filters);
            $stats = $activity_log->get_statistics($filter_days);
            
            // Get filtered count for pagination (reflects current filters)
            $total_items = $activity_log->get_filtered_logs_count($filters);
            $total_pages = ceil($total_items / $per_page);
            
            // Calculate pagination data
            $pagination = [
                'current_page' => $page,
                'total_pages' => $total_pages,
                'total_items' => $total_items,
                'per_page' => $per_page,
                'has_prev' => $page > 1,
                'has_next' => $page < $total_pages,
                'prev_page' => max(1, $page - 1),
                'next_page' => min($total_pages, $page + 1)
            ];
        } else {
            $logs = [];
            $stats = [];
            $pagination = [];
        }
        
        // Pass data to partials via global variables
        $GLOBALS['guard_dog_activity_log_data'] = [
            'current_tab' => $current_tab,
            'filter_type' => $filter_category, // Add filter_type for template compatibility
            'filter_category' => $filter_category,
            'filter_user' => $filter_user,
            'filter_days' => $filter_days,
            'search' => $search,
            'page' => $page,
            'logs' => $logs,
            'stats' => $stats,
            'pagination' => $pagination,
        ];
    }

    /**
     * Handle form submissions for cleanup actions
     */
    private function handle_form_submissions(): void {
        // Debug: Log that we're in the handler
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('handle_form_submissions called', 'activity_log');
        }
        // Handle auto cleanup form
        if (isset($_POST['action']) && $_POST['action'] === 'auto_cleanup_now') {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['auto_cleanup_nonce'] ?? '')), 'guard_dog_auto_cleanup')) {
                add_settings_error('guard_dog_activity_log', 'nonce_error', __('Security check failed. Please try again.', 'guard-dog'), 'error');
                return;
            }

            // Check user permissions
            if (!current_user_can('manage_options')) {
                add_settings_error('guard_dog_activity_log', 'permission_error', __('You do not have permission to perform this action.', 'guard-dog'), 'error');
                return;
            }

            // Trigger cleanup
            $activity_log = new Guard_Dog_Activity_Log();
            
            // Get current count before cleanup
            $before_count = $activity_log->get_total_logs_count();
            
            // Run the cleanup
            $activity_log->cleanup_old_logs();
            
            // Get count after cleanup
            $after_count = $activity_log->get_total_logs_count();
            $deleted_count = $before_count - $after_count;
            
            if ($deleted_count > 0) {
                add_settings_error('guard_dog_activity_log', 'cleanup_success', 
                    // Translators: %1$d is the number of deleted log entries, %2$d is the total number of entries after cleanup.
                    sprintf(esc_html__('Automatic cleanup completed successfully. Deleted %1$d log entries. Total entries now: %2$d', 'guard-dog'), 
                    esc_html($deleted_count), esc_html($after_count)), 'updated');
            } else {
                add_settings_error('guard_dog_activity_log', 'cleanup_nothing', 
                    __('Cleanup completed. No entries needed to be deleted based on your current settings.', 'guard-dog'), 'updated');
            }
        }

        // Handle preview cleanup form
        if (isset($_POST['action']) && $_POST['action'] === 'preview_cleanup') {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                Guard_Dog()->debug->debug('Preview form condition matched', 'activity_log', ['relevant_post_keys' => $this->get_relevant_activity_log_post_keys()]);
            }
            
            // Verify nonce
            $nonce = sanitize_text_field(wp_unslash($_POST['cleanup_logs_nonce'] ?? ''));
            if (!wp_verify_nonce($nonce, 'guard_dog_cleanup_logs')) {
                if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                    Guard_Dog()->debug->error('Nonce verification failed for preview cleanup', 'activity_log', ['nonce' => $nonce]);
                }
                add_settings_error('guard_dog_activity_log', 'nonce_error', __('Security check failed. Please try again.', 'guard-dog'), 'error');
                return;
            }

            // Check user permissions
            if (!current_user_can('manage_options')) {
                if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                    Guard_Dog()->debug->error('User permission check failed for preview cleanup', 'activity_log');
                }
                add_settings_error('guard_dog_activity_log', 'permission_error', __('You do not have permission to perform this action.', 'guard-dog'), 'error');
                return;
            }

            // Get form parameters
            $cleanup_days = isset($_POST['cleanup_days']) ? intval($_POST['cleanup_days']) : 30;
            
            // Handle cleanup_event_types - more robust handling
            $cleanup_event_types = [];
            if (isset($_POST['cleanup_event_types'])) {
                $raw_event_types = wp_unslash($_POST['cleanup_event_types']);
                if (is_array($raw_event_types) && !empty($raw_event_types)) {
                    $cleanup_event_types = array_map('sanitize_text_field', $raw_event_types);
                } else if (!is_array($raw_event_types) && !empty($raw_event_types)) {
                    $cleanup_event_types = [sanitize_text_field($raw_event_types)];
                }
            }
            
            // If still empty, default to 'all'
            if (empty($cleanup_event_types)) {
                $cleanup_event_types = ['all'];
            }
            
            if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                Guard_Dog()->debug->debug('Form parameters extracted', 'activity_log', [
                    'cleanup_days' => $cleanup_days,
                    'cleanup_event_types_raw' => isset($_POST['cleanup_event_types']) ? (is_array($raw_event_types) ? 'ARRAY' : sanitize_text_field($raw_event_types)) : 'NOT_SET',
                    'cleanup_event_types_is_array' => isset($_POST['cleanup_event_types']) && is_array($raw_event_types),
                    'cleanup_event_types_count' => isset($_POST['cleanup_event_types']) && is_array($raw_event_types) ? count($raw_event_types) : 0,
                    'cleanup_event_types_processed' => $cleanup_event_types,
                    'relevant_post_keys' => $this->get_relevant_activity_log_post_keys()
                ]);
                
                Guard_Dog()->debug->debug('Calling generate_cleanup_preview', 'activity_log', [
                    'cleanup_days' => $cleanup_days,
                    'event_types' => $cleanup_event_types
                ]);
            }
            
            // Generate preview
            $this->generate_cleanup_preview($cleanup_days, $cleanup_event_types);
        }

        // Handle manual cleanup execution
        if (isset($_POST['action']) && $_POST['action'] === 'execute_manual_cleanup') {
            // Verify nonce
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['execute_cleanup_nonce'] ?? '')), 'guard_dog_execute_cleanup')) {
                add_settings_error('guard_dog_activity_log', 'nonce_error', __('Security check failed. Please try again.', 'guard-dog'), 'error');
                return;
            }

            // Check user permissions
            if (!current_user_can('manage_options')) {
                add_settings_error('guard_dog_activity_log', 'permission_error', __('You do not have permission to perform this action.', 'guard-dog'), 'error');
                return;
            }

            // Get form parameters
            $cleanup_days = isset($_POST['cleanup_days']) ? intval(sanitize_text_field(wp_unslash($_POST['cleanup_days']))) : 30;
            $cleanup_event_types = isset($_POST['cleanup_event_types']) ? array_map('sanitize_text_field', wp_unslash($_POST['cleanup_event_types'])) : ['all'];
            
            // Execute manual cleanup
            $this->execute_manual_cleanup($cleanup_days, $cleanup_event_types);
        }
    }

    /**
     * Generate cleanup preview showing what logs would be deleted
     *
     * @param int $cleanup_days Number of days for retention
     * @param array $cleanup_event_types Event types to clean up
     */
    private function generate_cleanup_preview(int $cleanup_days, array $cleanup_event_types): void {
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('generate_cleanup_preview called', 'activity_log', ['cleanup_days' => $cleanup_days]);
        }
        
        global $wpdb;
        
        $activity_log = new Guard_Dog_Activity_Log();
        
        // Handle "All entries" case (cleanup_days = 0)
        if ($cleanup_days === 0) {
            $cutoff_date = null; // No date restriction
        } else {
            $cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$cleanup_days} days"));
        }
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('Cutoff date calculated', 'activity_log', [
                'cleanup_days' => $cleanup_days,
                'cutoff_date' => $cutoff_date,
                'all_entries_mode' => $cleanup_days === 0
            ]);
        }
        
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        // Direct database queries are necessary for preview functionality
        
        // Debug: Get some database info first
        $total_entries = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs");
        $oldest_entry = $wpdb->get_var("SELECT MIN(timestamp) FROM {$wpdb->prefix}guard_dog_logs");
        $newest_entry = $wpdb->get_var("SELECT MAX(timestamp) FROM {$wpdb->prefix}guard_dog_logs");
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('Database info for cleanup preview', 'activity_log', [
                'total_entries' => $total_entries,
                'oldest_entry' => $oldest_entry,
                'newest_entry' => $newest_entry,
                'cutoff_date' => $cutoff_date
            ]);
        }

        // Build query based on category selection
        if (in_array('all', $cleanup_event_types, true)) {
            // All event types
            if ($cutoff_date === null) {
                // Delete all entries regardless of age
                $count_to_delete = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs");
                
                $sample_entries = $wpdb->get_results(
                    "SELECT id, timestamp, event_type, username, ip_address 
                     FROM {$wpdb->prefix}guard_dog_logs 
                     ORDER BY timestamp DESC 
                     LIMIT 10",
                    ARRAY_A
                );
            } else {
                // Delete entries older than cutoff date
                $count_to_delete = $wpdb->get_var($wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s",
                    $cutoff_date
                ));
                
                $sample_entries = $wpdb->get_results($wpdb->prepare(
                    "SELECT id, timestamp, event_type, username, ip_address 
                     FROM {$wpdb->prefix}guard_dog_logs 
                     WHERE timestamp < %s
                     ORDER BY timestamp DESC 
                     LIMIT 10",
                    $cutoff_date
                ), ARRAY_A);
            }
        } else {
            // Get event types for selected categories
            $event_types_to_clean = $this->get_event_types_by_categories($cleanup_event_types);
            
            if (empty($event_types_to_clean)) {
                // No valid categories selected
                $count_to_delete = 0;
                $sample_entries = [];
            } else {
                // Build static queries based on event type count to avoid dynamic placeholders
                $event_count = count($event_types_to_clean);
                
                if ($cutoff_date === null) {
                    // Delete all entries of selected types regardless of age
                    if ($event_count === 1) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE event_type = %s",
                            $event_types_to_clean[0]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE event_type = %s
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $event_types_to_clean[0]
                        ), ARRAY_A);
                    } elseif ($event_count === 2) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE event_type IN (%s, %s)",
                            $event_types_to_clean[0], $event_types_to_clean[1]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE event_type IN (%s, %s)
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $event_types_to_clean[0], $event_types_to_clean[1]
                        ), ARRAY_A);
                    } elseif ($event_count === 3) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE event_type IN (%s, %s, %s)",
                            $event_types_to_clean[0], $event_types_to_clean[1], $event_types_to_clean[2]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE event_type IN (%s, %s, %s)
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $event_types_to_clean[0], $event_types_to_clean[1], $event_types_to_clean[2]
                        ), ARRAY_A);
                    } else {
                        // For more than 3 event types, use individual queries to avoid dynamic placeholders
                        $count_to_delete = 0;
                        $sample_entries = [];
                        
                        foreach ($event_types_to_clean as $event_type) {
                            $count = $wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE event_type = %s",
                                $event_type
                            ));
                            $count_to_delete += intval($count);
                            
                            // Get sample entries for this event type
                            $entries = $wpdb->get_results($wpdb->prepare(
                                "SELECT id, timestamp, event_type, username, ip_address 
                                 FROM {$wpdb->prefix}guard_dog_logs 
                                 WHERE event_type = %s
                                 ORDER BY timestamp DESC 
                                 LIMIT 3",
                                $event_type
                            ), ARRAY_A);
                            
                            $sample_entries = array_merge($sample_entries, $entries);
                        }
                        
                        // Sort and limit sample entries
                        usort($sample_entries, function($a, $b) {
                            return strtotime($b['timestamp']) - strtotime($a['timestamp']);
                        });
                        $sample_entries = array_slice($sample_entries, 0, 10);
                    }
                } else {
                    // Delete entries of selected types older than cutoff date
                    if ($event_count === 1) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type = %s",
                            $cutoff_date, $event_types_to_clean[0]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE timestamp < %s AND event_type = %s
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $cutoff_date, $event_types_to_clean[0]
                        ), ARRAY_A);
                    } elseif ($event_count === 2) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type IN (%s, %s)",
                            $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE timestamp < %s AND event_type IN (%s, %s)
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1]
                        ), ARRAY_A);
                    } elseif ($event_count === 3) {
                        $count_to_delete = $wpdb->get_var($wpdb->prepare(
                            "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type IN (%s, %s, %s)",
                            $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1], $event_types_to_clean[2]
                        ));
                        
                        $sample_entries = $wpdb->get_results($wpdb->prepare(
                            "SELECT id, timestamp, event_type, username, ip_address 
                             FROM {$wpdb->prefix}guard_dog_logs 
                             WHERE timestamp < %s AND event_type IN (%s, %s, %s)
                             ORDER BY timestamp DESC 
                             LIMIT 10",
                            $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1], $event_types_to_clean[2]
                        ), ARRAY_A);
                    } else {
                        // For more than 3 event types, use individual queries to avoid dynamic placeholders
                        $count_to_delete = 0;
                        $sample_entries = [];
                        
                        foreach ($event_types_to_clean as $event_type) {
                            $count = $wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type = %s",
                                $cutoff_date, $event_type
                            ));
                            $count_to_delete += intval($count);
                            
                            // Get sample entries for this event type
                            $entries = $wpdb->get_results($wpdb->prepare(
                                "SELECT id, timestamp, event_type, username, ip_address 
                                 FROM {$wpdb->prefix}guard_dog_logs 
                                 WHERE timestamp < %s AND event_type = %s
                                 ORDER BY timestamp DESC 
                                 LIMIT 3",
                                $cutoff_date, $event_type
                            ), ARRAY_A);
                            
                            $sample_entries = array_merge($sample_entries, $entries);
                        }
                        
                        // Sort and limit sample entries
                        usort($sample_entries, function($a, $b) {
                            return strtotime($b['timestamp']) - strtotime($a['timestamp']);
                        });
                        $sample_entries = array_slice($sample_entries, 0, 10);
                    }
                }
            }
        }
        
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        
        // Store preview data in global for display
        $GLOBALS['guard_dog_cleanup_preview'] = [
            'count_to_delete' => intval($count_to_delete),
            'cleanup_days' => $cleanup_days,
            'cutoff_date' => $cutoff_date,
            'sample_entries' => $sample_entries,
            'event_types' => $cleanup_event_types
        ];
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('Preview generation completed', 'activity_log', [
                'count_to_delete' => $count_to_delete,
                'sample_entries_count' => count($sample_entries),
                'global_data_set' => isset($GLOBALS['guard_dog_cleanup_preview'])
            ]);
        }
        
        // Add success message
        if ($count_to_delete > 0) {
            add_settings_error('guard_dog_activity_log', 'preview_success', 
                // Translators: %d is the number of log entries that would be deleted.
                sprintf(esc_html__('Preview generated: %d log entries would be deleted (showing sample of up to 10 below).', 'guard-dog'), 
                esc_html($count_to_delete)), 'updated');
        } else {
            add_settings_error('guard_dog_activity_log', 'preview_nothing', 
                __('No log entries match the selected cleanup criteria.', 'guard-dog'), 'updated');
        }
    }

    /**
     * Render cleanup preview if preview data exists
     */
    private function render_cleanup_preview(): void {
        $preview_data = $GLOBALS['guard_dog_cleanup_preview'] ?? null;
        
        if (!$preview_data) {
            return;
        }
        
        ?>
        <div class="guard-dog-preview-section">
            <h3><?php esc_html_e('Cleanup Preview', 'guard-dog'); ?></h3>
            
            <div class="guard-dog-preview-summary">
                <p><strong><?php 
                    if ($preview_data['cleanup_days'] == 0) {
                        esc_html_e('Cleanup criteria: All entries (regardless of age)', 'guard-dog');
                    } else {
                        // Translators: %d is the number of days for cleanup criteria.
                        printf(esc_html__(
                            'Cleanup criteria: Entries older than %d days', 'guard-dog'), 
                            esc_html($preview_data['cleanup_days'])); 
                    }
                ?></strong></p>
                <p><strong><?php 
                    // Translators: %d is the number of entries that would be deleted.
                    printf(esc_html__(
                        'Total entries that would be deleted: %d', 'guard-dog'), 
                        esc_html($preview_data['count_to_delete']));
                ?></strong></p>
                <?php if ($preview_data['cleanup_days'] > 0 && $preview_data['cutoff_date']): ?>
                    <p><em><?php 
                        // Translators: %s is the formatted date and time for cutoff date.
                        printf(esc_html__('Cutoff date: %s', 'guard-dog'), 
                        esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($preview_data['cutoff_date'])))); 
                    ?></em></p>
                <?php endif; ?>
                
                <?php if ($preview_data['count_to_delete'] == 0): ?>
                    <div class="notice notice-info inline">
                        <p><?php esc_html_e('No log entries found matching the cleanup criteria. All logs are newer than the specified time period.', 'guard-dog'); ?></p>
                    </div>
                <?php endif; ?>
            </div>
            
            <?php if (!empty($preview_data['sample_entries'])): ?>
                <h4><?php esc_html_e('Sample entries that would be deleted:', 'guard-dog'); ?></h4>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('ID', 'guard-dog'); ?></th>
                            <th><?php esc_html_e('Date/Time', 'guard-dog'); ?></th>
                            <th><?php esc_html_e('Event Type', 'guard-dog'); ?></th>
                            <th><?php esc_html_e('Username', 'guard-dog'); ?></th>
                            <th><?php esc_html_e('IP Address', 'guard-dog'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($preview_data['sample_entries'] as $entry): ?>
                            <tr>
                                <td><?php echo esc_html($entry['id']); ?></td>
                                <td><?php echo esc_html(date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($entry['timestamp']))); ?></td>
                                <td><?php echo esc_html($this->get_event_title($entry['event_type'])); ?></td>
                                <td><?php echo esc_html($entry['username'] ?: __('System', 'guard-dog')); ?></td>
                                <td><?php echo esc_html($entry['ip_address'] ?: __('N/A', 'guard-dog')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                
                <?php if ($preview_data['count_to_delete'] > 10): ?>
                    <p><em><?php 
                        // Translators: %d is the number of additional entries beyond the 10 shown.
                        printf(esc_html__('...and %d more entries', 'guard-dog'), 
                        esc_html($preview_data['count_to_delete'] - 10)); 
                    ?></em></p>
                <?php endif; ?>
                
                <div class="guard-dog-preview-actions">
                    <p><strong><?php esc_html_e('Warning:', 'guard-dog'); ?></strong> 
                       <?php esc_html_e('This action cannot be undone. Please review the entries above before proceeding.', 'guard-dog'); ?>
                    </p>
                    
                    <form method="post" action="" class="guard-dog-export-form">
                        <?php wp_nonce_field('guard_dog_execute_cleanup', 'execute_cleanup_nonce'); ?>
                        <input type="hidden" name="action" value="execute_manual_cleanup" />
                        <input type="hidden" name="cleanup_days" value="<?php echo esc_attr($preview_data['cleanup_days']); ?>" />
                        <?php foreach ($preview_data['event_types'] as $event_type): ?>
                            <input type="hidden" name="cleanup_event_types[]" value="<?php echo esc_attr($event_type); ?>" />
                        <?php endforeach; ?>
                        
                        <?php submit_button(__('Confirm and Execute Cleanup', 'guard-dog'), 'delete', 'submit', false, [
                            'onclick' => 'return confirm("' . esc_js(__('Are you sure you want to permanently delete these log entries? This action cannot be undone.', 'guard-dog')) . '");'
                        ]); ?>
                    </form>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Get event types that belong to specified categories
     *
     * @param array $categories Array of category names
     * @return array Array of event type names
     */
    private function get_event_types_by_categories(array $categories): array {
        $activity_log = new Guard_Dog_Activity_Log();
        $all_event_types = $activity_log->get_event_types();
        $event_types_to_clean = [];
        
        foreach ($all_event_types as $event_type => $config) {
            if (in_array($config['category'], $categories, true)) {
                $event_types_to_clean[] = $event_type;
            }
        }
        
        if (function_exists('Guard_Dog') && Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
            Guard_Dog()->debug->debug('Event types mapped from categories', 'activity_log', [
                'categories' => $categories,
                'event_types_found' => $event_types_to_clean
            ]);
        }
        
        return $event_types_to_clean;
    }

    /**
     * Execute manual cleanup with specific parameters
     *
     * @param int $cleanup_days Number of days for retention
     * @param array $cleanup_event_types Event types to clean up
     */
    private function execute_manual_cleanup(int $cleanup_days, array $cleanup_event_types): void {
        global $wpdb;
        
        $cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$cleanup_days} days"));
        
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        // Direct database queries are necessary for cleanup operations to ensure immediate data removal
        // Caching is not appropriate for cleanup operations as they modify the database
        
        // Execute deletion based on category selection
        if (in_array('all', $cleanup_event_types, true)) {
            // Delete all event types older than cutoff date
            $deleted = $wpdb->query($wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s",
                $cutoff_date
            ));
        } else {
            // Get event types for selected categories
            $event_types_to_clean = $this->get_event_types_by_categories($cleanup_event_types);
            
            if (empty($event_types_to_clean)) {
                // No valid categories selected
                $deleted = 0;
            } else {
                // Delete specific event types older than cutoff date
                $event_count = count($event_types_to_clean);
                
                if ($event_count === 1) {
                    $deleted = $wpdb->query($wpdb->prepare(
                        "DELETE FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type = %s",
                        $cutoff_date, $event_types_to_clean[0]
                    ));
                } elseif ($event_count === 2) {
                    $deleted = $wpdb->query($wpdb->prepare(
                        "DELETE FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type IN (%s, %s)",
                        $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1]
                    ));
                } elseif ($event_count === 3) {
                    $deleted = $wpdb->query($wpdb->prepare(
                        "DELETE FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type IN (%s, %s, %s)",
                        $cutoff_date, $event_types_to_clean[0], $event_types_to_clean[1], $event_types_to_clean[2]
                    ));
                } else {
                    // For more than 3 event types, use individual queries to avoid dynamic placeholders
                    $deleted = 0;
                    
                    foreach ($event_types_to_clean as $event_type) {
                        $result = $wpdb->query($wpdb->prepare(
                            "DELETE FROM {$wpdb->prefix}guard_dog_logs WHERE timestamp < %s AND event_type = %s",
                            $cutoff_date, $event_type
                        ));
                        if ($result !== false) {
                            $deleted += intval($result);
                        }
                    }
                }
            }
        }
        
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        
        // Clear preview data since cleanup is complete
        unset($GLOBALS['guard_dog_cleanup_preview']);
        
        // Show results
        if ($deleted !== false && $deleted > 0) {
            add_settings_error('guard_dog_activity_log', 'manual_cleanup_success', 
                // Translators: %1$d is the number of deleted log entries, %2$d is the number of days for cleanup criteria.
                sprintf(esc_html__('Manual cleanup completed successfully. Deleted %1$d log entries older than %2$d days.', 'guard-dog'), 
                esc_html($deleted), esc_html($cleanup_days)), 'updated');
        } elseif ($deleted === 0) {
            add_settings_error('guard_dog_activity_log', 'manual_cleanup_nothing', 
                __('No log entries matched the specified cleanup criteria.', 'guard-dog'), 'updated');
        } else {
            add_settings_error('guard_dog_activity_log', 'manual_cleanup_error', 
                __('An error occurred during cleanup. Please try again.', 'guard-dog'), 'error');
        }
    }

    /**
     * Get event severity
     */
    private function get_event_severity(string $event_type): string {
        $severities = [
            'login' => 'medium',
            'security' => 'high',
            'captcha' => 'low',
            'two_factor' => 'medium',
            'access' => 'medium',
        ];
        
        return $severities[$event_type] ?? 'low';
    }

    /**
     * Get event title (human-readable label) for an event type.
     *
     * Delegates to Guard_Dog_Activity_Log::get_event_label() so the canonical
     * event types from the Activity Log are the single source of truth.
     *
     * @param string $event_type The event type slug.
     * @return string The translated event title.
     */
    private function get_event_title(string $event_type): string {
        return Guard_Dog_Activity_Log::get_event_label( $event_type );
    }

        /**
     * Get event icon for display
     *
     * @param string $event_type The event type
     * @return string The icon class
     */
    private static function get_event_icon(string $event_type): string {
        $icons = [
            // Login events
            'login_successful' => 'dashicons-admin-users',
            'login_failed' => 'dashicons-admin-users',
            'login_blocked' => 'dashicons-admin-users',
            'login_attempt_during_lockout' => 'dashicons-admin-users',
            'login_lockout_initiated' => 'dashicons-admin-users',
            'login_access_denied' => 'dashicons-admin-users',
            'login_blocked_ip_reputation' => 'dashicons-shield',

            // Two-factor events
            '2fa_successful' => 'dashicons-smartphone',
            '2fa_failed' => 'dashicons-smartphone',
            '2fa_enabled' => 'dashicons-smartphone',
            '2fa_disabled' => 'dashicons-smartphone',

            // Passkey (WebAuthn) events
            'passkey_registered' => 'dashicons-admin-network',
            'passkey_deleted' => 'dashicons-admin-network',
            'passkey_login_success' => 'dashicons-admin-network',
            'passkey_login_failed' => 'dashicons-admin-network',

            // Session management events
            'session_created' => 'dashicons-visibility',
            'session_terminated' => 'dashicons-visibility',
            'session_terminated_limit' => 'dashicons-visibility',
            'session_expired' => 'dashicons-visibility',
            'session_ip_shift' => 'dashicons-visibility',
            'session_geo_anomaly' => 'dashicons-visibility',
            'session_terminated_ip_reputation' => 'dashicons-visibility',

            // Security events
            'ip_blocked' => 'dashicons-shield',
            'user_locked' => 'dashicons-shield',
            'suspicious_activity' => 'dashicons-shield',
            'temp_access_created' => 'dashicons-shield',
            'temp_access_used' => 'dashicons-shield',
            'site_access_denied' => 'dashicons-shield-alt',
            'not_in_whitelist' => 'dashicons-shield-alt',
            'user_blacklist' => 'dashicons-shield-alt',
            'ip_blacklist' => 'dashicons-shield-alt',
            'ip_added_to_blacklist' => 'dashicons-shield',
            'ip_removed_from_blacklist' => 'dashicons-shield',

            // CAPTCHA events
            'captcha_verification' => 'dashicons-yes-alt',
            'captcha_failed' => 'dashicons-yes-alt',

            // User management
            'user_created' => 'dashicons-admin-users',
            'user_deleted' => 'dashicons-admin-users',
            'user_updated' => 'dashicons-admin-users',
            'user_role_changed' => 'dashicons-admin-users',
            'profile_updated' => 'dashicons-admin-users',
            'password_reset' => 'dashicons-admin-users',

            // Content events
            'post_created' => 'dashicons-admin-post',
            'post_updated' => 'dashicons-admin-post',
            'post_deleted' => 'dashicons-admin-post',
            'post_status_changed' => 'dashicons-admin-post',
            'post_trashed' => 'dashicons-admin-post',

            // System events
            'plugin_activated' => 'dashicons-admin-plugins',
            'plugin_deactivated' => 'dashicons-admin-plugins',
            'plugin_installed' => 'dashicons-admin-plugins',
            'plugin_deleted' => 'dashicons-admin-plugins',
            'theme_switched' => 'dashicons-admin-appearance',
            'theme_installed' => 'dashicons-admin-appearance',
            'theme_deleted' => 'dashicons-admin-appearance',
            'core_updated' => 'dashicons-admin-generic',
            'settings_updated' => 'dashicons-admin-settings',

            // Comment events
            'comment_created' => 'dashicons-admin-comments',
            'comment_approved' => 'dashicons-admin-comments',
            'comment_spam' => 'dashicons-admin-comments',
            'comment_deleted' => 'dashicons-admin-comments',
        ];

        return $icons[ $event_type ] ?? 'dashicons-admin-generic';
    }

    /**
     * Save settings
     */
    private function save_settings(): void {
        // Settings save logic
        add_settings_error('guard_dog_activity_log', 'settings_updated', __('Activity log settings saved successfully.', 'guard-dog'), 'updated');
    }

    /**
     * Handle export
     */
    private function handle_export(): void {
        // Export logic
    }

    /**
     * Handle bulk delete
     */
    private function handle_bulk_delete(): void {
        // Bulk delete logic
        add_settings_error('guard_dog_activity_log', 'logs_deleted', __('Selected logs deleted successfully.', 'guard-dog'), 'updated');
    }

    /**
     * Register settings
     */
    public static function register_settings(): void {
        // Register activity log settings group
        register_setting('guard_dog_activity_log_settings_group', 'guard_dog_log_retention_days', [
            'type' => 'integer',
            'default' => 30,
            'sanitize_callback' => 'absint'
        ]);

        register_setting('guard_dog_activity_log_settings_group', 'guard_dog_max_log_entries', [
            'type' => 'integer',
            'default' => 10000,
            'sanitize_callback' => 'absint'
        ]);

        register_setting('guard_dog_activity_log_settings_group', 'guard_dog_log_ip_addresses', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        register_setting('guard_dog_activity_log_settings_group', 'guard_dog_log_user_agents', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        // Register event types settings group
        register_setting('guard_dog_event_types_group', 'guard_dog_activity_log_settings', [
            'type' => 'array',
            'default' => [],
            'sanitize_callback' => function($input) {
                // Ensure a stable, explicit structure for settings
                $clean = [];

                if (!is_array($input)) {
                    return $clean;
                }

                // Sanitize nested events map. Missing checkboxes must be saved as disabled (false)
                $clean['events'] = [];
                if (class_exists('Guard_Dog_Activity_Log')) {
                    $event_types = Guard_Dog_Activity_Log::get_event_types();
                    foreach ($event_types as $event_key => $info) {
                        $clean['events'][$event_key] = (!empty($input['events'][$event_key])) ? 1 : 0;
                    }
                } else {
                    // Fallback: if class unavailable, just pass through provided keys safely
                    if (isset($input['events']) && is_array($input['events'])) {
                        foreach ($input['events'] as $event_key => $value) {
                            $clean['events'][sanitize_key((string) $event_key)] = !empty($value) ? 1 : 0;
                        }
                    }
                }

                // Preserve future options while sanitizing primitives if they are present
                if (isset($input['enable_batch_logging'])) {
                    $clean['enable_batch_logging'] = (bool) $input['enable_batch_logging'];
                }

                return $clean;
            }
        ]);

        // Add settings sections
        add_settings_section(
            'guard_dog_activity_log_general',
            __('General Settings', 'guard-dog'),
            null,
            'guard_dog_activity_log_settings_group'
        );

        add_settings_section(
            'guard_dog_event_types_section',
            __('Event Types', 'guard-dog'),
            null,
            'guard_dog_event_types_group'
        );

        // Add settings fields for activity log settings
        add_settings_field(
            'guard_dog_log_retention_days',
            __('Log Retention Period', 'guard-dog'),
            [self::class, 'render_retention_days_field'],
            'guard_dog_activity_log_settings_group',
            'guard_dog_activity_log_general'
        );

        add_settings_field(
            'guard_dog_max_log_entries',
            __('Maximum Log Entries', 'guard-dog'),
            [self::class, 'render_max_entries_field'],
            'guard_dog_activity_log_settings_group',
            'guard_dog_activity_log_general'
        );

        add_settings_field(
            'guard_dog_log_ip_addresses',
            __('Log IP Addresses', 'guard-dog'),
            [self::class, 'render_ip_addresses_field'],
            'guard_dog_activity_log_settings_group',
            'guard_dog_activity_log_general'
        );

        add_settings_field(
            'guard_dog_log_user_agents',
            __('Log User Agents', 'guard-dog'),
            [self::class, 'render_user_agents_field'],
            'guard_dog_activity_log_settings_group',
            'guard_dog_activity_log_general'
        );

        // Add settings field for event types
        add_settings_field(
            'guard_dog_logged_event_types',
            __('Event Types to Log', 'guard-dog'),
            [self::class, 'render_event_types_field'],
            'guard_dog_event_types_group',
            'guard_dog_event_types_section'
        );
    }

    /**
     * Render retention days field
     */
    public static function render_retention_days_field(): void {
        $value = get_option('guard_dog_log_retention_days', 30);
        ?>
        <select name="guard_dog_log_retention_days" id="log_retention_days">
            <option value="30" <?php selected($value, 30); ?>><?php esc_html_e('30 days', 'guard-dog'); ?></option>
            <option value="60" <?php selected($value, 60); ?>><?php esc_html_e('60 days', 'guard-dog'); ?></option>
            <option value="90" <?php selected($value, 90); ?>><?php esc_html_e('90 days', 'guard-dog'); ?></option>
            <option value="180" <?php selected($value, 180); ?>><?php esc_html_e('6 months', 'guard-dog'); ?></option>
            <option value="365" <?php selected($value, 365); ?>><?php esc_html_e('1 year', 'guard-dog'); ?></option>
            <option value="0" <?php selected($value, 0); ?>><?php esc_html_e('Never (manual cleanup only)', 'guard-dog'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('How long to keep activity logs before automatic cleanup.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render max entries field
     */
    public static function render_max_entries_field(): void {
        $value = get_option('guard_dog_max_log_entries', 10000);
        ?>
        <input type="number" name="guard_dog_max_log_entries" id="max_log_entries" value="<?php echo esc_attr($value); ?>" min="1000" max="100000" step="1000" />
        <p class="description"><?php esc_html_e('Maximum number of log entries to store (older entries will be deleted first).', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render IP addresses field
     */
    public static function render_ip_addresses_field(): void {
        $value = get_option('guard_dog_log_ip_addresses', true);
        ?>
        <label>
            <input type="checkbox" name="guard_dog_log_ip_addresses" value="1" <?php checked($value, true); ?> />
            <?php esc_html_e('Store IP addresses in activity logs', 'guard-dog'); ?>
        </label>
        <p class="description"><?php esc_html_e('Disable this if you have privacy concerns about storing IP addresses.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render user agents field
     */
    public static function render_user_agents_field(): void {
        $value = get_option('guard_dog_log_user_agents', false);
        ?>
        <label>
            <input type="checkbox" name="guard_dog_log_user_agents" value="1" <?php checked($value, true); ?> />
            <?php esc_html_e('Store user agent strings in activity logs', 'guard-dog'); ?>
        </label>
        <p class="description"><?php esc_html_e('User agent strings can help identify suspicious activity patterns.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render event types field
     */
    public static function render_event_types_field(): void {
        if (!class_exists('Guard_Dog_Activity_Log')) {
            ?>
            <p><?php esc_html_e('Event type configuration is unavailable. Please ensure the Guard Dog Activity Log feature is active.', 'guard-dog'); ?></p>
            <?php
            return;
        }

        $event_types = Guard_Dog_Activity_Log::get_available_event_types();
        $categories = [];
        foreach ($event_types as $key => $info) {
            $categories[$info['category']][$key] = $info;
        }

        // Get enabled event types from options (fallback to defaults)
        $settings = get_option('guard_dog_activity_log_settings', []);
        $saved_events = $settings['events'] ?? [];
        
        // If no saved events, use defaults
        if (empty($saved_events)) {
            foreach ($event_types as $key => $info) {
                if ($info['default']) $saved_events[$key] = true;
            }
        }

        foreach ($categories as $cat => $events): ?>
            <div class="guard-dog-event-category">
                <h4><?php echo esc_html(ucwords($cat) . ' Events'); ?></h4>
                <?php foreach ($events as $event_key => $event_info): ?>
                    <label>
                        <input type="checkbox" name="guard_dog_activity_log_settings[events][<?php echo esc_attr($event_key); ?>]" value="1" <?php checked(isset($saved_events[$event_key]) && $saved_events[$event_key], true); ?> />
                        <?php echo esc_html($event_info['name']); ?>
                    </label><br>
                <?php endforeach; ?>
            </div>
        <?php endforeach;
    }

    public static function handle_export_logs() {
        // Verify capability first
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to export logs.', 'guard-dog'), esc_html__('Permission Denied', 'guard-dog'), ['response' => 403]);
        }

        // Verify nonce first before any $_POST access
        if (!isset($_POST['export_logs_nonce']) || 
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['export_logs_nonce'])), 'guard_dog_export_logs')) {
            wp_safe_redirect(self::build_activity_log_url([self::TAB_QUERY_ARG => 'export', 'error' => 'nonce_failed']));
            exit;
        }

        // Now safe to access $_POST data after nonce verification
        $format = isset($_POST['export_format']) ? sanitize_text_field(wp_unslash($_POST['export_format'])) : 'csv';
        $date_range = isset($_POST['export_date_range']) ? sanitize_text_field(wp_unslash($_POST['export_date_range'])) : 'all';
        $start_date = isset($_POST['export_start_date']) ? sanitize_text_field(wp_unslash($_POST['export_start_date'])) : '';
        $end_date = isset($_POST['export_end_date']) ? sanitize_text_field(wp_unslash($_POST['export_end_date'])) : '';
        $event_types = isset($_POST['export_event_types']) ? array_map('sanitize_text_field', wp_unslash((array)$_POST['export_event_types'])) : ['all'];
        $include_details = !empty($_POST['export_include_details']);

        // Build filters
        $filters = [];
        // Date range logic
        if ($date_range === 'today') {
            $filters['date_from'] = gmdate('Y-m-d');
            $filters['date_to'] = gmdate('Y-m-d');
        } elseif ($date_range === 'yesterday') {
            $filters['date_from'] = gmdate('Y-m-d', strtotime('-1 day'));
            $filters['date_to'] = gmdate('Y-m-d', strtotime('-1 day'));
        } elseif ($date_range === 'last_7_days') {
            $filters['date_from'] = gmdate('Y-m-d', strtotime('-7 days'));
        } elseif ($date_range === 'last_30_days') {
            $filters['date_from'] = gmdate('Y-m-d', strtotime('-30 days'));
        } elseif ($date_range === 'last_90_days') {
            $filters['date_from'] = gmdate('Y-m-d', strtotime('-90 days'));
        } elseif ($date_range === 'custom' && $start_date && $end_date) {
            $filters['date_from'] = $start_date;
            $filters['date_to'] = $end_date;
        }
        // Event type/category logic
        if (!in_array('all', $event_types, true)) {
            $filters['categories'] = $event_types; // array of categories
        }
        $filters['include_details'] = $include_details;
        $filters['per_page'] = 10000;
        $filters['page'] = 1;

        $activity_log = new Guard_Dog_Activity_Log();
        if ($format === 'csv') {
            while (ob_get_level()) { ob_end_clean(); }
            $csv = $activity_log->export_to_csv($filters);
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="guard-dog-activity-log.csv"');
            header('Pragma: no-cache');
            header('Expires: 0');

            // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
            // CSV content is properly escaped in export_to_csv() method which handles
            // CSV field escaping (quotes, commas, newlines) according to RFC 4180.
            // The CSV format requires specific escaping rules that are handled by the export method.
            echo $csv;
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
            exit;
        } elseif ($format === 'json') {
            while (ob_get_level()) { ob_end_clean(); }
            $logs = $activity_log->get_logs($filters);
            header('Content-Type: application/json; charset=utf-8');
            header('Content-Disposition: attachment; filename="guard-dog-activity-log.json"');

            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            // wp_json_encode() properly escapes JSON output and prevents XSS
            echo wp_json_encode($logs, JSON_PRETTY_PRINT);
            exit;
        } elseif ($format === 'xml') {
            while (ob_get_level()) { ob_end_clean(); }
            $logs = $activity_log->get_logs($filters);
            header('Content-Type: application/xml');
            header('Content-Disposition: attachment; filename="guard-dog-activity-log.xml"');
            // Simple XML output
            $xml = new SimpleXMLElement('<logs/>' );
            foreach ($logs as $log) {
                $entry = $xml->addChild('log');
                foreach ($log as $key => $value) {
                    $entry->addChild($key, htmlspecialchars((string)$value));
                }
            }

            echo esc_xml($xml->asXML());
            exit;
        }
        
        // If not valid, redirect back with error
        wp_safe_redirect(self::build_activity_log_url([self::TAB_QUERY_ARG => 'export']));
        exit;
    }

    /**
     * Render activity statistics sidebar
     *
     * @param array $stats The statistics data
     * @param int $filter_days The filter days
     */
    private function render_activity_stats(array $stats, int $filter_days): void {
        ?>
        <div class="guard-dog-activity-stats">
            <h3>
                <span class="dashicons dashicons-chart-bar"></span>
                <?php esc_html_e('Activity Statistics', 'guard-dog'); ?>
            </h3>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('Total Events', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($stats['total_events'] ?? 0); ?></span>
            </div>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('User Events', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($stats['login_events'] ?? 0); ?></span>
            </div>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('Security Events', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($stats['security_events'] ?? 0); ?></span>
            </div>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('Content Events', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($stats['content_events'] ?? 0); ?></span>
            </div>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('System Events', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($stats['system_events'] ?? 0); ?></span>
            </div>
            
            <div class="guard-dog-stat-item">
                <span class="guard-dog-stat-label"><?php esc_html_e('Time Period', 'guard-dog'); ?></span>
                <span class="guard-dog-stat-value"><?php echo esc_html($filter_days); ?> <?php esc_html_e('days', 'guard-dog'); ?></span>
            </div>
        </div>
        <?php
    }

    /**
     * Render activity filters
     *
     * @param string $filter_category The filter category
     * @param string $filter_user The filter user
     * @param int $filter_days The filter days
     * @param string $search The search term
     */
    private function render_activity_filters(string $filter_category, string $filter_user, int $filter_days, string $search): void {
        ?>
        <div class="guard-dog-activity-filters">
            <form method="get" action="" class="guard-dog-filters-form">
                <input type="hidden" name="page" value="guard-dog-logs">
                <input type="hidden" name="<?php echo esc_attr(self::TAB_QUERY_ARG); ?>" value="logs">
                
                <div class="guard-dog-filters-row">
                    <div class="guard-dog-filter-group">
                        <label for="filter_category"><?php esc_html_e('Event Category:', 'guard-dog'); ?></label>
                        <select name="filter_category" id="filter_category">
                            <option value="all" <?php selected($filter_category, 'all'); ?>><?php esc_html_e('All Events', 'guard-dog'); ?></option>
                            <option value="security" <?php selected($filter_category, 'security'); ?>><?php esc_html_e('Security Events', 'guard-dog'); ?></option>
                            <option value="users" <?php selected($filter_category, 'users'); ?>><?php esc_html_e('User Events', 'guard-dog'); ?></option>
                            <option value="content" <?php selected($filter_category, 'content'); ?>><?php esc_html_e('Content Events', 'guard-dog'); ?></option>
                            <option value="system" <?php selected($filter_category, 'system'); ?>><?php esc_html_e('System Events', 'guard-dog'); ?></option>
                        </select>
                    </div>
                    
                    <div class="guard-dog-filter-group">
                        <label for="filter_days"><?php esc_html_e('Time Period:', 'guard-dog'); ?></label>
                        <select name="filter_days" id="filter_days">
                            <option value="1" <?php selected($filter_days, 1); ?>><?php esc_html_e('Last 24 hours', 'guard-dog'); ?></option>
                            <option value="7" <?php selected($filter_days, 7); ?>><?php esc_html_e('Last 7 days', 'guard-dog'); ?></option>
                            <option value="30" <?php selected($filter_days, 30); ?>><?php esc_html_e('Last 30 days', 'guard-dog'); ?></option>
                            <option value="90" <?php selected($filter_days, 90); ?>><?php esc_html_e('Last 90 days', 'guard-dog'); ?></option>
                            <option value="365" <?php selected($filter_days, 365); ?>><?php esc_html_e('Last year', 'guard-dog'); ?></option>
                        </select>
                    </div>
                    
                    <div class="guard-dog-filter-group">
                        <label for="search"><?php esc_html_e('Search:', 'guard-dog'); ?></label>
                        <input type="text" name="search" id="search" value="<?php echo esc_attr($search); ?>" placeholder="<?php esc_attr_e('Search events...', 'guard-dog'); ?>" class="guard-dog-search-input">
                    </div>
                </div>

                <div class="guard-dog-filter-actions">
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Apply Filters', 'guard-dog'); ?>
                    </button>

                    <a href="<?php echo esc_url($this->get_tab_url('logs')); ?>" class="button button-secondary">
                        <?php esc_html_e('Clear Filters', 'guard-dog'); ?>
                    </a>
                </div>
            </form>
        </div>
        <?php
    }

    /**
     * Render activity table
     *
     * @param array $logs The logs data
     * @param int $page The current page
     */
    private function render_activity_table(array $logs, int $page): void {
        ?>
        <div class="guard-dog-activity-table-wrapper">
            <?php if (empty($logs)): ?>
                <div class="guard-dog-no-logs">
                    <p><?php esc_html_e('No activity logs found for the selected criteria.', 'guard-dog'); ?></p>
                </div>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped guard-dog-activity-table">
                    <thead>
                        <tr>
                            <th scope="col"><?php esc_html_e('Event', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('User', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('IP Address', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Date/Time', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Details', 'guard-dog'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): ?>
                            <tr>
                                <td>
                                    <span class="dashicons <?php echo esc_attr($this->get_event_icon($log['event_type'] ?? '')); ?>"></span>
                                    <?php echo esc_html($this->get_event_title($log['event_type'] ?? '')); ?>
                                </td>
                                <td><?php echo esc_html($log['username'] ?? __('System', 'guard-dog')); ?></td>
                                <td class="guard-dog-ip-address-cell">
                                    <?php 
                                    $ip_address = $log['ip_address'] ?? '';
                                    if (!empty($ip_address) && $ip_address !== 'N/A' && filter_var($ip_address, FILTER_VALIDATE_IP)): 
                                    ?>
                                        <span class="guard-dog-ip-address"><?php echo esc_html($ip_address); ?></span>
                                        <button type="button" 
                                                class="guard-dog-check-ip-reputation" 
                                                data-ip="<?php echo esc_attr($ip_address); ?>"
                                                title="<?php esc_attr_e('Check IP Reputation', 'guard-dog'); ?>"
                                                aria-label="<?php esc_attr_e('Check IP Reputation', 'guard-dog'); ?>">
                                            <span class="dashicons dashicons-search"></span>
                                        </button>
                                    <?php else: ?>
                                        <?php echo esc_html($ip_address ?: __('N/A', 'guard-dog')); ?>
                                    <?php endif; ?>
                                </td>
                                <td><?php 
                                    $timestamp = $log['timestamp'] ?? $log['created_at'] ?? null;
                                    if ($timestamp) {
                                        echo esc_html(wp_date('Y-m-d H:i:s', strtotime($timestamp)));
                                    } else {
                                        echo esc_html(__('N/A', 'guard-dog'));
                                    }
                                ?></td>
                                <td><?php echo esc_html($log['details'] ?? $log['description'] ?? ''); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render pagination controls for activity log table
     *
     * @param array $pagination Pagination data
     */
    private function render_pagination(array $pagination): void {
        $current_page = $pagination['current_page'] ?? 1;
        $total_pages = $pagination['total_pages'] ?? 1;
        $total_items = $pagination['total_items'] ?? 0;
        $per_page = $pagination['per_page'] ?? 20;
        
        if ($total_pages <= 1) {
            return;
        }

        // Build current URL with existing parameters
        $base_url = $this->get_tab_url('logs');
        
        // Safely extract current parameters for pagination
        $get_params = $this->get_safe_get_parameters();
        $current_params = [
            'filter_category' => $get_params['filter_category'] ?? 'all',
            'filter_days' => $get_params['filter_days'] ?? 30,
            'search' => $get_params['search'] ?? '',
        ];
        
        ?>
        <div class="guard-dog-pagination-wrapper">
            <div class="tablenav">
                <div class="tablenav-pages">
                    <span class="displaying-num"><?php
                        // Translators: %s is the number of items.
                        echo esc_html(sprintf(_n('%s item', '%s items', $total_items, 'guard-dog'), number_format_i18n($total_items))); 
                    ?></span>
                    
                    <?php if ($total_pages > 1): ?>
                        <span class="pagination-links">
                            <?php if ($current_page > 1): ?>
                                <a class="first-page button" href="<?php echo esc_url(add_query_arg(array_merge($current_params, ['paged' => 1]), $base_url)); ?>">
                                    <span class="screen-reader-text"><?php esc_html_e('First page', 'guard-dog'); ?></span>
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                                <a class="prev-page button" href="<?php echo esc_url(add_query_arg(array_merge($current_params, ['paged' => $current_page - 1]), $base_url)); ?>">
                                    <span class="screen-reader-text"><?php esc_html_e('Previous page', 'guard-dog'); ?></span>
                                    <span aria-hidden="true">&lsaquo;</span>
                                </a>
                            <?php else: ?>
                                <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&laquo;</span>
                                <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&lsaquo;</span>
                            <?php endif; ?>
                            
                            <span class="paging-input">
                                <label for="current-page-selector" class="screen-reader-text"><?php esc_html_e('Current Page', 'guard-dog'); ?></label>
                                <input class="current-page" id="current-page-selector" type="text" 
                                       name="paged" value="<?php echo esc_attr($current_page); ?>" size="<?php 
                                       echo esc_attr((string) strlen((string) $total_pages));
                                       ?>"
                                       aria-describedby="table-paging" />
                                <span class="tablenav-paging-text">
                                    <?php 
                                    // Translators: %s is the total number of pages.
                                    printf(esc_html__('of %s', 'guard-dog'), '<span class="total-pages">' . esc_html(number_format_i18n($total_pages)) . '</span>'); 
                                    ?>
                                </span>
                            </span>
                            
                            <?php if ($current_page < $total_pages): ?>
                                <a class="next-page button" href="<?php echo esc_url(add_query_arg(array_merge($current_params, ['paged' => $current_page + 1]), $base_url)); ?>">
                                    <span class="screen-reader-text"><?php esc_html_e('Next page', 'guard-dog'); ?></span>
                                    <span aria-hidden="true">&rsaquo;</span>
                                </a>
                                <a class="last-page button" href="<?php echo esc_url(add_query_arg(array_merge($current_params, ['paged' => $total_pages]), $base_url)); ?>">
                                    <span class="screen-reader-text"><?php esc_html_e('Last page', 'guard-dog'); ?></span>
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            <?php else: ?>
                                <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&rsaquo;</span>
                                <span class="tablenav-pages-navspan button disabled" aria-hidden="true">&raquo;</span>
                            <?php endif; ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    }


} 
