<?php

error_log('SENTINEL ADMIN CLASS LOADED');

/**
 * Sentinel Admin Class
 */
class Sentinel_Admin {

    /**
     * Singleton instance
     */
    private static $instance = null;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Initialize admin functionality
     */
    public function init() {
        add_action('admin_menu', array($this, 'init_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        add_action('admin_init', array($this, 'handle_admin_actions'));
        add_action('wp_ajax_sentinel_export_logs', array($this, 'handle_export_logs'));
        add_action('wp_ajax_sentinel_clear_old_logs', array($this, 'handle_clear_old_logs'));
        add_action('wp_ajax_sentinel_generate_test_data', array($this, 'handle_generate_test_data'));
        add_action('wp_ajax_sentinel_export_logs_json', array($this, 'ajax_export_logs_json'));
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        // Load on Sentinel pages OR dashboard page (for widget)
        if (strpos($hook, 'sentinel') === false && $hook !== 'index.php') {
            return;
        }

        // Enqueue CSS
        wp_enqueue_style(
            'sentinel-admin',
            plugin_dir_url(__FILE__) . 'css/sentinel-admin.css',
            array(),
            SENTINEL_VERSION
        );

        // Enqueue Chart.js
        wp_enqueue_script(
            'chart-js',
            'https://cdn.jsdelivr.net/npm/chart.js',
            array(),
            '3.9.1',
            true
        );

        // Enqueue main admin JS
        wp_enqueue_script(
            'sentinel-admin',
            plugin_dir_url(__FILE__) . 'js/sentinel-admin.js',
            array('jquery'),
            SENTINEL_VERSION,
            true
        );

        // Enqueue dashboard JS
        wp_enqueue_script(
            'sentinel-dashboard',
            plugin_dir_url(__FILE__) . 'js/sentinel-dashboard.js',
            array('jquery', 'chart-js'),
            SENTINEL_VERSION,
            true
        );

        // Enqueue settings JS on all Sentinel pages (it's lightweight and handles its own initialization)
        wp_enqueue_script(
            'sentinel-settings',
            plugin_dir_url(__FILE__) . 'js/sentinel-settings.js',
            array('jquery'),
            SENTINEL_VERSION,
            true
        );
    }

    /**
     * Initialize admin menu
     */
    public function init_menu() {
        // Check if user can access Sentinel (admins or editors)
        $can_access = current_user_can('manage_options') || current_user_can('edit_published_posts');
        
        if (!$can_access) {
            return;
        }
        
        add_menu_page(
            'Sentinel',
            'Sentinel',
            'edit_published_posts',
            'sentinel-dashboard',
            array($this, 'render_dashboard'),
            'dashicons-shield',
            30
        );

        add_submenu_page(
            'sentinel-dashboard',
            'Dashboard',
            'Dashboard',
            'edit_published_posts',
            'sentinel-dashboard',
            array($this, 'render_dashboard')
        );

        add_submenu_page(
            'sentinel-dashboard',
            'Activity Logs',
            'Activity Logs',
            'edit_published_posts',
            'sentinel-logs',
            array($this, 'render_logs_page')
        );

        // Event Registry - only for admins
        if (current_user_can('manage_options')) {
            add_submenu_page(
                'sentinel-dashboard',
                'Event Registry',
                'Event Registry',
                'manage_options',
                'sentinel-events',
                array($this, 'render_events_page')
            );
        }

        // Settings page - only for admins
        if (current_user_can('manage_options')) {
            add_submenu_page(
                'sentinel-dashboard',
                'Settings',
                'Settings',
                'manage_options',
                'sentinel-settings',
                array($this, 'settings_page')
            );
        }
    }

    /**
     * Render the dashboard
     */
    public function render_dashboard() {
        include plugin_dir_path(__FILE__) . 'views/admin-page.php';
    }

    /**
     * Render the logs page
     */
    public function render_logs_page() {
        include plugin_dir_path(__FILE__) . 'views/logs.php';
    }

    /**
     * Render the events page
     */
    public function render_events_page() {
        include plugin_dir_path(__FILE__) . 'views/events-page.php';
    }

    /**
     * Render the settings page
     */
    public function settings_page() {
        include plugin_dir_path(__FILE__) . 'views/settings-page.php';
    }

    /**
     * Get activity icon for event type
     */
    public function get_activity_icon($event_key) {
        $icons = array(
            'user_login' => 'admin-users',
            'user_logout' => 'exit',
            'user_registered' => 'admin-users',
            'profile_updated' => 'admin-users',
            'post_published' => 'admin-post',
            'post_updated' => 'edit',
            'post_deleted' => 'trash',
            'comment_posted' => 'admin-comments',
            'comment_approved' => 'yes',
            'comment_deleted' => 'trash',
            'plugin_activated' => 'admin-plugins',
            'plugin_deactivated' => 'admin-plugins',
            'logs_cleaned' => 'database',
            'tables_optimized' => 'performance',

            // Error events
            'php_fatal_error' => 'dismiss',
            'php_warning' => 'warning',
            'php_notice' => 'info',
            'php_deprecated' => 'clock',
            'wp_database_error' => 'database',
            'wp_memory_error' => 'admin-page',
            'wp_permission_error' => 'lock',
            'wp_config_error' => 'admin-tools',
            'login_failed' => 'no-alt',
            'auth_cookie_bad' => 'shield-alt',
            'nonce_verification_failed' => 'shield',
            'permission_denied' => 'lock',
            'http_404_error' => 'search',
            'http_500_error' => 'warning',
            'wp_remote_error' => 'admin-links',
            'wp_cron_error' => 'clock',
            'plugin_error' => 'admin-plugins',
            'theme_error' => 'admin-appearance',
            'plugin_activation_error' => 'admin-plugins',
            'file_upload_error' => 'upload',
            'file_permission_error' => 'media-document'
        );

        return isset($icons[$event_key]) ? $icons[$event_key] : 'admin-generic';
    }

    /**
     * Format activity message for display
     */
    public function format_activity_message($activity, $usernames) {
        $username = isset($usernames[$activity->user_id]) ? $usernames[$activity->user_id] : 'Unknown User';
        $data = json_decode($activity->data, true);

        switch ($activity->event_key) {
            case 'user_login':
                return sprintf('%s logged in', $username);
            
            case 'user_logout':
                return sprintf('%s logged out', $username);
            
            case 'user_registered':
                return sprintf('New user %s registered', $username);
            
            case 'profile_updated':
                return sprintf('%s updated their profile', $username);
            
            case 'post_published':
                $post_type = isset($data['post_type']) ? $data['post_type'] : 'post';
                return sprintf('%s published a %s', $username, $post_type);
            
            case 'post_updated':
                $post_type = isset($data['post_type']) ? $data['post_type'] : 'post';
                return sprintf('%s updated a %s', $username, $post_type);
            
            case 'post_deleted':
                $post_type = isset($data['post_type']) ? $data['post_type'] : 'post';
                return sprintf('%s deleted a %s', $username, $post_type);
            
            case 'comment_posted':
                return sprintf('%s posted a comment', $username);
            
            case 'comment_approved':
                return sprintf('Comment by %s was approved', $username);
            
            case 'comment_deleted':
                return sprintf('Comment by %s was deleted', $username);
            
            case 'plugin_activated':
                $plugin = isset($data['plugin']) ? $data['plugin'] : 'Unknown Plugin';
                return sprintf('Plugin %s was activated', $plugin);
            
            case 'plugin_deactivated':
                $plugin = isset($data['plugin']) ? $data['plugin'] : 'Unknown Plugin';
                return sprintf('Plugin %s was deactivated', $plugin);
            
            case 'logs_cleaned':
                $deleted_count = isset($data['deleted_count']) ? $data['deleted_count'] : 0;
                return sprintf('System cleaned up %d old log entries', $deleted_count);
            
            case 'tables_optimized':
                $tables_count = isset($data['tables_optimized']) ? $data['tables_optimized'] : 0;
                return sprintf('System optimized %d database tables', $tables_count);
            

            default:
                // If the data contains a stack trace or fatal error, show a summary instead of the full dump
                $raw_data = is_string($activity->data) ? $activity->data : '';
                if (stripos($raw_data, 'Fatal error') !== false || stripos($raw_data, 'Stack trace') !== false) {
                    return $username . ' triggered a fatal error. See details.';
                }
                return sprintf('%s performed %s', $username, $activity->event_key);
        }
    }

    /**
     * Constructor
     */
    public function __construct() {
        // Constructor is called when we get the instance
    }

    /**
     * Handle log export
     */
    public function handle_export_logs() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }

        if (!wp_verify_nonce($_GET['nonce'], 'sentinel_export')) {
            wp_die('Invalid nonce');
        }

        global $wpdb;
        $table = $wpdb->prefix . 'sentinel_logs';

        // Get all logs
        $logs = $wpdb->get_results("SELECT * FROM $table ORDER BY created_at DESC");

        // Set headers for CSV download
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="sentinel-logs-' . date('Y-m-d') . '.csv"');

        // Create CSV output
        $output = fopen('php://output', 'w');

        // Add headers
        fputcsv($output, array('ID', 'Event Key', 'Category', 'Priority', 'User ID', 'IP Address', 'User Agent', 'URL', 'Data', 'Created At'));

        // Add data
        foreach ($logs as $log) {
            fputcsv($output, array(
                $log->id,
                $log->event_key,
                $log->category,
                $log->priority,
                $log->user_id,
                $log->ip_address,
                $log->user_agent,
                $log->url,
                $log->data,
                $log->created_at
            ));
        }

        fclose($output);
        exit;
    }

    /**
     * Handle clearing old logs
     */
    public function handle_clear_old_logs() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }

        if (!wp_verify_nonce($_GET['nonce'], 'sentinel_clear')) {
            wp_die('Invalid nonce');
        }

        // Use the cleanup class to handle log cleanup
        $result = Sentinel_Cleanup::manual_cleanup(30);
        $deleted = $result['deleted_logs'];

        // Redirect back with success message
        wp_redirect(admin_url('admin.php?page=sentinel-dashboard&logs_cleared=' . $deleted));
        exit;
    }

    /**
     * Handle test data generation
     */
    public function handle_generate_test_data() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized');
        }

        if (!wp_verify_nonce($_GET['nonce'], 'sentinel_test_data')) {
            wp_die('Invalid nonce');
        }

        // Generate 20 sample log entries
        $events = array(
            'user_login' => array('category' => 'authentication', 'priority' => 'info'),
            'user_logout' => array('category' => 'authentication', 'priority' => 'info'),
            'post_published' => array('category' => 'content', 'priority' => 'info'),
            'comment_posted' => array('category' => 'social', 'priority' => 'info'),
            'bounty_uploaded' => array('category' => 'bounty', 'priority' => 'info'),
            'user_followed' => array('category' => 'social', 'priority' => 'info'),
            'game_added' => array('category' => 'collection', 'priority' => 'info'),
            'difficulty_rated' => array('category' => 'rating', 'priority' => 'info')
        );

        $users = get_users(array('number' => 5, 'fields' => 'ID'));
        $user_agents = array(
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
        );

        for ($i = 0; $i < 20; $i++) {
            $event_key = array_rand($events);
            $event_data = $events[$event_key];
            $user_id = !empty($users) ? $users[array_rand($users)] : 0;
            
            $data = array();
            switch ($event_key) {
                case 'bounty_uploaded':
                    $data = array(
                        'trophy_name' => 'Sample Trophy ' . rand(1, 100),
                        'bounty_value' => rand(100, 1000),
                        'auto_approved' => rand(0, 1)
                    );
                    break;
                case 'user_followed':
                    $data = array(
                        'follower_id' => $user_id,
                        'followed_id' => !empty($users) ? $users[array_rand($users)] : 0
                    );
                    break;
                case 'game_added':
                    $data = array(
                        'game_name' => 'Sample Game ' . rand(1, 50)
                    );
                    break;
                case 'difficulty_rated':
                    $data = array(
                        'rating' => rand(1, 10)
                    );
                    break;
            }

            sentinel_log_event($event_key, $data);
        }

        // Generate some test error data to demonstrate error categorization
        $error_events = array(
            'php_warning' => array(
                'error_message' => 'Undefined variable: test_var',
                'error_file' => '/wp-content/themes/example/functions.php',
                'error_line' => 42,
                'url' => '/sample-page'
            ),
            'login_failed' => array(
                'username' => 'test_user_' . rand(1, 5),
                'ip_address' => '192.168.1.' . rand(1, 255),
                'user_agent' => 'Mozilla/5.0 (Test Browser)'
            ),
            'http_404_error' => array(
                'requested_url' => '/non-existent-page-' . rand(1, 10),
                'referer' => '/sample-page',
                'user_agent' => 'Mozilla/5.0 (Test Browser)'
            ),
            'file_upload_error' => array(
                'filename' => 'test_file_' . rand(1, 10) . '.jpg',
                'error_code' => 1,
                'error_message' => 'File exceeds upload_max_filesize'
            ),
            'wp_database_error' => array(
                'error_message' => 'Table \'wp_test\' doesn\'t exist',
                'last_query' => 'SELECT * FROM wp_test WHERE id = 1',
                'context' => 'test_query'
            )
        );
        
        // Add a few error events to the mix
        foreach ($error_events as $error_key => $error_data) {
            if (rand(0, 1)) { // 50% chance to add each error type
                sentinel_log_event($error_key, $error_data);
            }
        }

        // Redirect back with success message
        wp_redirect(admin_url('admin.php?page=sentinel-dashboard&test_data_generated=20'));
        exit;
    }

    // --- BEGIN MERGE: Methods from includes/class-sentinel-admin.php ---
    // (If a method already exists, the imported one is renamed with _alt)

    // Copied from includes/class-sentinel-admin.php
    public function add_admin_menu() {
        // Add main menu item
        add_menu_page(
            'Sentinel Activity Logger',           // Page title (shown in browser tab)
            'Sentinel',                           // Menu title (shown in sidebar)
            'manage_options',                     // Capability required (admin only)
            'sentinel',                           // Menu slug (used in URLs)
            array($this, 'admin_page'),           // Callback function to display page
            'dashicons-shield-alt',               // Icon (WordPress dashicons)
            30                                    // Position in menu (lower = higher up)
        );
        
        // Add submenu items
        add_submenu_page(
            'sentinel',                           // Parent slug
            'Activity Logs',                      // Page title
            'Activity Logs',                      // Menu title
            'manage_options',                     // Capability
            'sentinel-logs',                      // Menu slug
            array($this, 'logs_page')             // Callback
        );
        
        add_submenu_page(
            'sentinel',                           // Parent slug
            'Settings',                           // Page title
            'Settings',                           // Menu title
            'manage_options',                     // Capability
            'sentinel-settings',                  // Menu slug
            array($this, 'settings_page')         // Callback
        );
        
        add_submenu_page(
            'sentinel',                           // Parent slug
            'Event Registry',                     // Page title
            'Event Registry',                     // Menu title
            'manage_options',                     // Capability
            'sentinel-events',                    // Menu slug
            array($this, 'events_page')           // Callback
        );
        

    }

    public function admin_notices() {
        // Check if we have any notices to show
        if (isset($_GET['page']) && strpos($_GET['page'], 'sentinel') !== false) {
            // Example notice - we'll expand this later
            if (isset($_GET['sentinel_notice'])) {
                $notice_type = sanitize_text_field($_GET['sentinel_notice']);
                $message = '';
                
                switch ($notice_type) {
                    case 'activated':
                        $message = 'Sentinel plugin activated successfully!';
                        $class = 'notice-success';
                        break;
                    case 'error':
                        $message = 'An error occurred with Sentinel.';
                        $class = 'notice-error';
                        break;
                    default:
                        return;
                }
                
                if ($message) {
                    echo '<div class="notice ' . esc_attr($class) . ' is-dismissible">';
                    echo '<p>' . esc_html($message) . '</p>';
                    echo '</div>';
                }
            }
        }
    }
    
    public function handle_admin_actions() {
        error_log('[Sentinel Admin] handle_admin_actions() called');
        // Only handle our pages
        if (!isset($_GET['page']) || strpos($_GET['page'], 'sentinel') === false) {
            return;
        }
        
        // Check for actions in both GET and POST
        if (!isset($_GET['action']) && !isset($_POST['action'])) {
            return;
        }
        
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : sanitize_text_field($_POST['action']);
        
        // Verify user permissions
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
        
        // Verify nonce for POST actions
        if (isset($_POST['action'])) {
            $nonce_actions = array(
                'process_queue_now' => 'sentinel_process_queue',
                'cron_diagnostics' => 'sentinel_cron_diagnostics'
            );
            
            if (isset($nonce_actions[$action])) {
                if (!wp_verify_nonce($_POST['sentinel_nonce'], $nonce_actions[$action])) {
                    wp_die('Security check failed');
                }
            }
        }
        
        switch ($action) {
            case 'test_logging':
                $this->handle_test_logging();
                break;
                

                
            case 'cleanup_now':
                $this->handle_manual_cleanup();
                break;
                
            case 'optimize_now':
                $this->handle_manual_optimization();
                break;
                
            case 'process_queue_now':
                $this->handle_process_queue_now();
                break;
                
            case 'cron_diagnostics':
                $this->handle_cron_diagnostics();
                break;
                
            case 'anonymize_logs':
                $this->handle_anonymize_logs();
                break;

        }
    }

    public function admin_page() {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Include the admin page view
        include SENTINEL_PLUGIN_DIR . 'admin/views/admin-page.php';
    }

    public function logs_page() {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        // Include the log viewer view
        include SENTINEL_PLUGIN_DIR . 'admin/views/logs.php';
    }

    // --- BEGIN PRIVATE METHODS from includes/class-sentinel-admin.php ---
    private function handle_test_logging() {
        // Test basic logging
        $test_result = sentinel_log_event('admin_test', array(
            'message' => 'Test log entry created from settings page',
            'timestamp' => current_time('mysql'),
            'user_id' => get_current_user_id()
        ));
        
        // Test error logging
        error_log('Sentinel Test: Manual test log entry created - Result: ' . ($test_result ? 'SUCCESS' : 'FAILED'));
        
        // Redirect with result
        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'test_logging',
            'result' => $test_result ? 'success' : 'failed'
        ), admin_url('admin.php')));
        exit;
    }

    private function handle_manual_cleanup() {
        error_log('[Sentinel Admin] handle_manual_cleanup() called');
        if (!class_exists('Sentinel_Cleanup')) {
            wp_redirect(add_query_arg(array(
                'page' => 'sentinel-settings',
                'message' => 'cleanup_error'
            ), admin_url('admin.php')));
            exit;
        }
        
        $cleanup = new Sentinel_Cleanup();
        $archived_count = $cleanup->cleanup_logs(true); // TRUE = manual override
        
        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'cleanup_success',
            'count' => $archived_count
        ), admin_url('admin.php')));
        exit;
    }

    private function handle_manual_optimization() {
        if (!class_exists('Sentinel_Cleanup')) {
            wp_redirect(add_query_arg(array(
                'page' => 'sentinel-settings',
                'message' => 'optimize_error'
            ), admin_url('admin.php')));
            exit;
        }
        
        $cleanup = new Sentinel_Cleanup();
        $results = $cleanup->optimize_database();
        
        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'optimize_success',
            'main_table' => $results['main_table'],
            'archive_table' => $results['archive_table'],
            'space_saved' => $results['space_saved']
        ), admin_url('admin.php')));
        exit;
    }

    private function handle_process_queue_now() {
        if (!class_exists('Sentinel_Logger')) {
            wp_redirect(add_query_arg(array(
                'page' => 'sentinel-settings',
                'message' => 'process_queue_error'
            ), admin_url('admin.php')));
            exit;
        }
        
        $logger = new Sentinel_Logger();
        $processed_count = $logger->process_queue();
        
        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'process_queue_success',
            'count' => $processed_count
        ), admin_url('admin.php')));
        exit;
    }

    private function handle_cron_diagnostics() {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.'));
        }
        
        // Start output
        echo '<div class="wrap">';
        echo '<h1>🔍 WordPress Cron Diagnostics</h1>';
        
        // 1. Check if WP-Cron is disabled
        echo '<h2>1. WP-Cron Configuration</h2>';
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            echo '<div style="background: #ffebe9; padding: 10px; border-left: 4px solid #d63638; margin: 10px 0;">';
            echo '<strong>❌ WP-Cron is DISABLED</strong><br>';
            echo 'DISABLE_WP_CRON is set to true in wp-config.php. This prevents automatic cron execution.';
            echo '</div>';
        } else {
            echo '<div style="background: #edfaed; padding: 10px; border-left: 4px solid #00a32a; margin: 10px 0;">';
            echo '<strong>✅ WP-Cron is ENABLED</strong><br>';
            echo 'DISABLE_WP_CRON is not set or is false.';
            echo '</div>';
        }
        
        // 2. Check current cron jobs
        echo '<h2>2. Current Cron Jobs</h2>';
        $cron_jobs = wp_get_ready_cron_jobs();
        echo '<p><strong>Ready to run:</strong> ' . count($cron_jobs) . ' jobs</p>';
        
        $all_crons = get_option('cron');
        $sentinel_crons = array();
        if (is_array($all_crons)) {
            foreach ($all_crons as $timestamp => $cron_array) {
                if (is_array($cron_array)) {
                    foreach ($cron_array as $hook => $args) {
                        if (strpos($hook, 'sentinel') !== false) {
                            $sentinel_crons[] = array(
                                'hook' => $hook,
                                'timestamp' => $timestamp,
                                'time' => date('Y-m-d H:i:s', $timestamp),
                                'args' => $args
                            );
                        }
                    }
                }
            }
        }
        
        echo '<h3>Sentinel Cron Jobs:</h3>';
        if (empty($sentinel_crons)) {
            echo '<p>❌ No Sentinel cron jobs found</p>';
        } else {
            echo '<table border="1" cellpadding="5" style="border-collapse: collapse;">';
            echo '<tr><th>Hook</th><th>Scheduled Time</th><th>Status</th></tr>';
            foreach ($sentinel_crons as $cron) {
                $status = $cron['timestamp'] < time() ? '⏰ Overdue' : '⏳ Scheduled';
                echo '<tr>';
                echo '<td>' . esc_html($cron['hook']) . '</td>';
                echo '<td>' . esc_html($cron['time']) . '</td>';
                echo '<td>' . $status . '</td>';
                echo '</tr>';
            }
            echo '</table>';
        }
        
        // 3. Check if cron is being triggered
        echo '<h2>3. Cron Triggering Test</h2>';
        $last_cron = get_option('_last_cron_check', 0);
        $time_since = time() - $last_cron;
        echo '<p><strong>Last cron check:</strong> ' . ($last_cron ? date('Y-m-d H:i:s', $last_cron) . ' (' . $time_since . ' seconds ago)' : 'Never') . '</p>';
        
        if ($time_since > 300) { // 5 minutes
            echo '<div style="background: #ffebe9; padding: 10px; border-left: 4px solid #d63638; margin: 10px 0;">';
            echo '<strong>⚠️ Cron hasn\'t run recently</strong><br>';
            echo 'WordPress cron hasn\'t been checked in over 5 minutes. This suggests no page visits or cron is disabled.';
            echo '</div>';
        }
        
        // 4. Test cron URL accessibility
        echo '<h2>4. Cron URL Test</h2>';
        $cron_url = site_url('wp-cron.php?doing_wp_cron');
        echo '<p><strong>Cron URL:</strong> <code>' . esc_html($cron_url) . '</code></p>';
        
        // Try to access the cron URL
        $response = wp_remote_get($cron_url, array(
            'timeout' => 30,
            'blocking' => true,
            'user-agent' => 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url')
        ));
        
        if (is_wp_error($response)) {
            echo '<div style="background: #ffebe9; padding: 10px; border-left: 4px solid #d63638; margin: 10px 0;">';
            echo '<strong>❌ Cron URL Error</strong><br>';
            echo 'Error accessing wp-cron.php: ' . esc_html($response->get_error_message());
            echo '</div>';
        } else {
            $status_code = wp_remote_retrieve_response_code($response);
            if ($status_code == 200) {
                echo '<div style="background: #edfaed; padding: 10px; border-left: 4px solid #00a32a; margin: 10px 0;">';
                echo '<strong>✅ Cron URL Accessible</strong><br>';
                echo 'wp-cron.php is accessible (HTTP 200).';
                echo '</div>';
            } else {
                echo '<div style="background: #ffebe9; padding: 10px; border-left: 4px solid #d63638; margin: 10px 0;">';
                echo '<strong>❌ Cron URL Issue</strong><br>';
                echo 'wp-cron.php returned HTTP ' . $status_code . ' instead of 200.';
                echo '</div>';
            }
        }
        
        // 5. Check WordPress constants
        echo '<h2>5. WordPress Constants</h2>';
        $constants = array(
            'WP_CRON_LOCK_TIMEOUT' => WP_CRON_LOCK_TIMEOUT ?? 'Not set',
            'ALTERNATE_WP_CRON' => defined('ALTERNATE_WP_CRON') ? (ALTERNATE_WP_CRON ? 'true' : 'false') : 'Not set',
            'WP_DEBUG' => defined('WP_DEBUG') ? (WP_DEBUG ? 'true' : 'false') : 'Not set',
            'WP_DEBUG_LOG' => defined('WP_DEBUG_LOG') ? (WP_DEBUG_LOG ? 'true' : 'false') : 'Not set'
        );
        
        echo '<table border="1" cellpadding="5" style="border-collapse: collapse;">';
        foreach ($constants as $constant => $value) {
            echo '<tr><td><strong>' . esc_html($constant) . '</strong></td><td>' . esc_html($value) . '</td></tr>';
        }
        echo '</table>';
        
        // 6. Recommendations
        echo '<h2>6. Recommendations</h2>';
        echo '<div style="background: #e7f3ff; padding: 15px; border-left: 4px solid #0073aa; margin: 10px 0;">';
        echo '<h3>Possible Solutions:</h3>';
        echo '<ol>';
        echo '<li><strong>Docker/Development Issue:</strong> WP-Cron requires page visits to trigger. In Docker environments, you may need to set up a real cron job.</li>';
        echo '<li><strong>Set up real cron:</strong> Add this to your server cron: <code>* * * * * curl -s "' . esc_html($cron_url) . '" > /dev/null 2>&1</code></li>';
        echo '<li><strong>Alternative cron:</strong> Enable ALTERNATE_WP_CRON in wp-config.php</li>';
        echo '<li><strong>Plugin solution:</strong> Use a cron management plugin</li>';
        echo '<li><strong>Manual processing:</strong> Use the "Process Queue Now" button until cron is fixed</li>';
        echo '</ol>';
        echo '</div>';
        
        // 7. Quick fix for testing
        echo '<h2>7. Quick Test</h2>';
        echo '<p><a href="' . admin_url('admin.php?page=sentinel-settings&action=process_queue_now') . '" class="button button-primary">📤 Process Queue Now (Manual)</a></p>';
        echo '<p><em>This will manually process the queue to clear it while you fix the cron issue.</em></p>';
        
        echo '<hr>';
        echo '<p><a href="' . admin_url('admin.php?page=sentinel-settings') . '">← Back to Settings</a></p>';
        echo '</div>';
        
        exit; // Don't redirect, just show the diagnostics
    }

    private function handle_anonymize_logs() {
        if (!class_exists('Sentinel_Cleanup')) {
            wp_redirect(add_query_arg(array(
                'page' => 'sentinel-settings',
                'message' => 'anonymize_error'
            ), admin_url('admin.php')));
            exit;
        }
        $result = Sentinel_Cleanup::anonymize_old_logs(true);
        $total = 0;
        if (is_array($result)) {
            foreach ($result as $table => $stats) {
                $total += isset($stats['anonymized']) ? intval($stats['anonymized']) : 0;
            }
        }
        error_log('[Sentinel Admin] handle_anonymize_logs() called, anonymized ' . $total . ' logs.');
        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'anonymize_success',
            'count' => $total
        ), admin_url('admin.php')));
        exit;
    }
    // --- END MERGE ---

    /**
     * AJAX handler for exporting logs as JSON (filtered by date range)
     */
    public function ajax_export_logs_json() {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Unauthorized'), 403);
        }
        check_ajax_referer('sentinel_export_logs_json', 'nonce');

        $date_range = isset($_POST['date_range']) ? sanitize_text_field($_POST['date_range']) : '30';
        $valid_ranges = array('7', '30', '90', 'all');
        if (!in_array($date_range, $valid_ranges)) {
            $date_range = '30';
        }
        $format = isset($_POST['format']) ? sanitize_text_field($_POST['format']) : 'json';
        $valid_formats = array('json', 'csv', 'xml');
        if (!in_array($format, $valid_formats)) {
            $format = 'json';
        }
        $export_source = isset($_POST['export_source']) ? sanitize_text_field($_POST['export_source']) : 'main';
        $valid_sources = array('main', 'archive', 'both');
        if (!in_array($export_source, $valid_sources)) {
            $export_source = 'main';
        }

        global $wpdb;
        $main_table = $wpdb->prefix . 'sentinel_logs';
        $archive_table = $wpdb->prefix . 'sentinel_logs_archive';
        $where = '';
        $params = array();
        if ($date_range !== 'all') {
            $days = intval($date_range);
            $from = date('Y-m-d 00:00:00', strtotime("-{$days} days"));
            $where = 'WHERE created_at >= %s';
            $params[] = $from;
        }

        $logs = array();
        if ($export_source === 'main' || $export_source === 'both') {
            $query = "SELECT * FROM $main_table $where ORDER BY created_at DESC";
            $main_logs = $params ? $wpdb->get_results($wpdb->prepare($query, $params)) : $wpdb->get_results($query);
            foreach ($main_logs as $log) {
                $logs[] = array(
                    'id' => $log->id,
                    'event_key' => $log->event_key,
                    'category' => $log->category,
                    'priority' => $log->priority,
                    'user_id' => $log->user_id,
                    'ip_address' => $log->ip_address,
                    'user_agent' => $log->user_agent,
                    'url' => $log->url,
                    'data' => $log->data,
                    'created_at' => $log->created_at,
                    'source' => 'main'
                );
            }
        }
        if ($export_source === 'archive' || $export_source === 'both') {
            $query = "SELECT * FROM $archive_table $where ORDER BY created_at DESC";
            $archive_logs = $params ? $wpdb->get_results($wpdb->prepare($query, $params)) : $wpdb->get_results($query);
            foreach ($archive_logs as $log) {
                $logs[] = array(
                    'id' => $log->id,
                    'event_key' => $log->event_key,
                    'category' => $log->category,
                    'priority' => $log->priority,
                    'user_id' => $log->user_id,
                    'ip_address' => $log->ip_address,
                    'user_agent' => $log->user_agent,
                    'url' => $log->url,
                    'data' => $log->data,
                    'created_at' => $log->created_at,
                    'source' => 'archive'
                );
            }
        }

        // Output in requested format
        $filename = 'sentinel-logs-' . $export_source . '-' . ($date_range === 'all' ? 'all' : $date_range . 'days') . '-' . date('Y-m-d') . '.' . $format;
        if ($format === 'json') {
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            echo json_encode($logs, JSON_PRETTY_PRINT);
            exit;
        } else if ($format === 'csv') {
            // CSV export implementation
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            $out = fopen('php://output', 'w');
            // Output header
            fputcsv($out, array('id','event_key','category','priority','user_id','ip_address','user_agent','url','data','created_at','source'));
            foreach ($logs as $log) {
                // Flatten data as JSON string
                $row = $log;
                $row['data'] = is_string($log['data']) ? $log['data'] : json_encode($log['data']);
                fputcsv($out, $row);
            }
            fclose($out);
            exit;
        } else if ($format === 'xml') {
            // XML export implementation
            header('Content-Type: application/xml');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><logs></logs>');
            foreach ($logs as $log) {
                $logElem = $xml->addChild('log');
                foreach ($log as $key => $value) {
                    // Data as string
                    $logElem->addChild($key, htmlspecialchars(is_string($value) ? $value : json_encode($value)));
                }
            }
            echo $xml->asXML();
            exit;
        }
    }
} 