<?php

/**
 * 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'));
        add_action('wp_dashboard_setup', array($this, 'register_dashboard_widgets'));
    }

    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook)
    {
        // Load only on Sentinel pages OR WP Dashboard for our widget
        $is_sentinel_page = strpos($hook, 'sentinel') !== false;
        $is_wp_dashboard = ($hook === 'index.php');

        if (!$is_sentinel_page && !$is_wp_dashboard) {
            return;
        }

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

        if ($is_sentinel_page) {
            // Charting only for Sentinel pages
            wp_enqueue_script(
                'chart-js',
                'https://cdn.jsdelivr.net/npm/chart.js',
                array(),
                '3.9.1',
                true
            );

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

            // Localize admin variables for AJAX
            wp_localize_script('sentinel-admin', 'sentinel_admin_vars', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('sentinel_admin_nonce')
            ));

            // Sentinel dashboard charts/UX
            wp_enqueue_script(
                'sentinel-dashboard',
                plugin_dir_url(__FILE__) . 'js/sentinel-dashboard.js',
                array('jquery', 'chart-js'),
                SENTINEL_VERSION,
                true
            );

            // Localize dashboard variables for AJAX (API key management)
            wp_localize_script('sentinel-dashboard', 'sentinel_dashboard_vars', array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('sentinel_dashboard_nonce')
            ));

            // Settings JS (self-initializes)
            wp_enqueue_script(
                'sentinel-settings',
                plugin_dir_url(__FILE__) . 'js/sentinel-settings.js',
                array('jquery'),
                SENTINEL_VERSION,
                true
            );
        }

        if ($is_wp_dashboard) {
            // Lightweight widget logic for WP Dashboard only
            wp_enqueue_script(
                'sentinel-wp-dashboard',
                plugin_dir_url(__FILE__) . 'js/sentinel-wp-dashboard.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')
        );

        // Premium: Incidents - only for admins
        if (current_user_can('manage_options') && sentinel_is_premium()) {
            add_submenu_page(
                'sentinel-dashboard',
                'Incidents',
                'Incidents',
                'manage_options',
                'sentinel-incidents',
                array($this, 'render_incidents_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')
            );
        }

        // Auth Test Page - only in debug mode for admins
    }

    /**
     * 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';
    }


    /**
     * Render the Incidents page
     */
    public function render_incidents_page()
    {
        include plugin_dir_path(__FILE__) . 'views/incidents-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',

            // Premium: Auth attempt tracking
            'auth_success' => 'yes',
            'auth_fail' => 'no',

            // Premium: Security incidents
            'security_incident_opened' => 'warning',
            'security_incident_updated' => 'update',
            'security_incident_resolved' => 'yes-alt',
            '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 ' . wp_rand(1, 100),
                        'bounty_value' => wp_rand(100, 1000),
                        'auto_approved' => wp_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 ' . wp_rand(1, 50)
                    );
                    break;
                case 'difficulty_rated':
                    $data = array(
                        'rating' => wp_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_' . wp_rand(1, 5),
                'ip_address' => '192.168.1.' . wp_rand(1, 255),
                'user_agent' => 'Mozilla/5.0 (Test Browser)'
            ),
            'http_404_error' => array(
                'requested_url' => '/non-existent-page-' . wp_rand(1, 10),
                'referer' => '/sample-page',
                'user_agent' => 'Mozilla/5.0 (Test Browser)'
            ),
            'file_upload_error' => array(
                'filename' => 'test_file_' . wp_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 (wp_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;
    }


    /**
     * Handle admin actions from GET/POST requests
     */
    public function handle_admin_actions()
    {
        // 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');
        }

        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 'anonymize_logs':
                $this->handle_anonymize_logs();
                break;
        }
    }

    /**
     * Handle test logging action
     */
    private function handle_test_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()
        ));

        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'test_logging',
            'result' => $test_result ? 'success' : 'failed'
        ), admin_url('admin.php')));
        exit;
    }

    /**
     * Handle manual cleanup action
     */
    private function handle_manual_cleanup()
    {
        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);

        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'cleanup_success',
            'count' => $archived_count
        ), admin_url('admin.php')));
        exit;
    }

    /**
     * Handle manual optimization action
     */
    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;
    }

    /**
     * Handle process queue now action
     */
    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;
    }

    /**
     * Handle anonymize logs action
     */
    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;
            }
        }

        wp_redirect(add_query_arg(array(
            'page' => 'sentinel-settings',
            'message' => 'anonymize_success',
            'count' => $total
        ), admin_url('admin.php')));
        exit;
    }

    /**
     * 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;
}
}

/**
* Register dashboard widgets in WordPress Dashboard
*/
public function register_dashboard_widgets()
{
// Keep this for admins only (matches AJAX capability)
if (!current_user_can('manage_options')) {
return;
}

wp_add_dashboard_widget(
'sentinel_memory_insights',
'Sentinel Memory Insights',
array($this, 'render_memory_dashboard_widget')
);

// Premium: Incidents widget
if (sentinel_is_premium()) {
wp_add_dashboard_widget(
'sentinel_incidents',
'Sentinel+ Incidents',
array($this, 'render_incidents_dashboard_widget')
);
}
}

/**
* Render the Memory Insights widget on the main WP Dashboard
*/
public function render_memory_dashboard_widget()
{
$stats = null;
if (class_exists('Sentinel_Memory_Monitor')) {
$stats = Sentinel_Memory_Monitor::get_memory_stats();
}
?>
<div id="sentinel-memory-widget" class="sentinel-memory-widget">
    <div class="inside">
        <div class="sentinel-memory-quick">
            <p><strong>Current:</strong>
                <?php echo $stats ? esc_html($stats['current_usage_formatted']) : '—'; ?><?php echo $stats ? ' (' . esc_html($stats['usage_percent']) . '%)' : ''; ?>
            </p>
            <p><strong>Peak:</strong>
                <?php echo $stats ? esc_html($stats['peak_usage_formatted']) : '—'; ?><?php echo $stats ? ' (' . esc_html($stats['peak_percent']) . '%)' : ''; ?>
            </p>
            <p><strong>Limit:</strong> <?php echo $stats ? esc_html($stats['limit_formatted']) : '—'; ?></p>
        </div>

        <div id="sentinel-memory-insights" aria-live="polite">
            <p>Loading insights…</p>
        </div>

        <p>
            <button type="button" class="button" id="sentinel-memory-refresh">Refresh</button>
        </p>
    </div>
</div>
<?php
    }

    /**
     * Render the Incidents widget on the main WP Dashboard
     */
    public function render_incidents_dashboard_widget()
    {
        // Get incident statistics
        $stats = Sentinel_Incidents::get_incident_stats(1); // Last 24 hours
        $open_incidents = Sentinel_Incidents::get_incidents_list(array('status' => 'open'), 5);

        // Get failed login count for last 24 hours
        $failed_logins_24h = 0;
        global $wpdb;
        $table_name = $wpdb->prefix . 'sentinel_logs';
        $failed_logins_24h = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE event_key = %s AND created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)",
            'auth_fail'
        ));
    ?>
<div id="sentinel-incidents-widget" class="sentinel-incidents-widget">
    <div class="inside">
        <div class="sentinel-incidents-overview">
            <div class="sentinel-stat-card">
                <div class="stat-number"><?php echo esc_html($stats['open_incidents']); ?></div>
                <div class="stat-label">Open Incidents</div>
                <?php if ($stats['open_incidents'] > 0): ?>
                <div class="stat-alert">⚠️</div>
                <?php else: ?>
                <div class="stat-good">✅</div>
                <?php endif; ?>
            </div>

            <div class="sentinel-stat-card">
                <div class="stat-number"><?php echo esc_html($stats['total_incidents_24h']); ?></div>
                <div class="stat-label">Incidents (24h)</div>
            </div>

            <div class="sentinel-stat-card">
                <div class="stat-number"><?php echo esc_html($failed_logins_24h); ?></div>
                <div class="stat-label">Failed Logins (24h)</div>
            </div>
        </div>

        <?php if (!empty($open_incidents)): ?>
        <div class="sentinel-recent-incidents">
            <h4>Recent Open Incidents</h4>
            <div class="incident-list">
                <?php foreach ($open_incidents as $incident): ?>
                <div class="incident-item">
                    <div class="incident-type">
                        <?php echo esc_html(ucfirst(str_replace('security.', '', $incident['type']))); ?>
                    </div>
                    <div class="incident-details">
                        <span class="incident-ip"><?php echo esc_html(inet_ntop($incident['ip'])); ?></span>
                        <span class="incident-confidence confidence-<?php echo esc_attr($incident['confidence']); ?>">
                            <?php echo esc_html(ucfirst($incident['confidence'])); ?>
                        </span>
                    </div>
                    <div class="incident-time">
                        <?php echo esc_html(human_time_diff(strtotime($incident['last_seen'])) . ' ago'); ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="sentinel-no-incidents">
            <p>✅ No open incidents</p>
        </div>
        <?php endif; ?>

        <div class="sentinel-incidents-actions">
            <a href="<?php echo esc_url(admin_url('admin.php?page=sentinel-incidents')); ?>"
                class="button button-primary">
                View All Incidents
            </a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=sentinel-security-settings')); ?>" class="button">
                Security Settings
            </a>
        </div>
    </div>
</div>

<!-- Styles are now handled by the main sentinel-admin.scss file -->
<?php
    }
}