<?php
/**
 * VMPFence Audit Log View
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.1.0 Updated to reflect VMP WordPress Security branding.
 * @since 2.2.1 Updated text-domain to vmpfence-security
 * @since 2.2.2 Updated to reflect VMP Security branding.
 * @since 2.2.5 Added updated Audit Log management, Audit Log style updated
 * @since 2.2.6 Added Custom Pattern block to Firewall, Custom Pattern Block Message Updated
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Detect if we're embedded in Tools page or standalone
$in_tools_page = (isset($_GET['page']) && $_GET['page'] === 'vmpfence-tools');

// Detect which tab is active - use different parameter when in Tools page
$current_tab = $in_tools_page 
    ? (isset($_GET['audit_subtab']) ? sanitize_text_field($_GET['audit_subtab']) : 'compliance')
    : (isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'compliance');

// Get filter parameters
$filter_event_type = isset($_GET['filter_event_type']) ? sanitize_text_field($_GET['filter_event_type']) : '';
$filter_user = isset($_GET['filter_user']) ? sanitize_text_field($_GET['filter_user']) : '';
$filter_date_from = isset($_GET['filter_date_from']) ? sanitize_text_field($_GET['filter_date_from']) : '';
$filter_date_to = isset($_GET['filter_date_to']) ? sanitize_text_field($_GET['filter_date_to']) : '';
$filter_search = isset($_GET['filter_search']) ? sanitize_text_field($_GET['filter_search']) : '';
$current_page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
$per_page = 50;

// Build query args
$query_args = array(
    'limit' => $per_page,
    'offset' => ($current_page - 1) * $per_page,
    'order_by' => 'time',
    'order' => 'DESC'
);

if (!empty($filter_event_type)) {
    $query_args['event_type'] = $filter_event_type;
}

if (!empty($filter_user)) {
    $query_args['user_id'] = absint($filter_user);
}

if (!empty($filter_date_from)) {
    $query_args['date_from'] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $query_args['date_to'] = $filter_date_to;
}

if (!empty($filter_search)) {
    $query_args['search'] = $filter_search;
}

// Check if user has premium license
$is_premium = (VMPFence_License::get_license_type() === 'premium');

// Get entries and count (only if on compliance tab)
if ($current_tab === 'compliance') {
    // Limit free users to 50 entries total
    if (!$is_premium) {
        // Calculate how many entries we can show based on current page
        $max_free_entries = 50;
        $available_entries = max(0, $max_free_entries - (($current_page - 1) * $per_page));
        if ($available_entries > 0) {
            $query_args['limit'] = min($query_args['limit'], $available_entries);
        } else {
            $query_args['limit'] = 0;
        }
    }
    
    $entries = VMPFence_Audit_Log::get_entries($query_args);
    $total_entries = VMPFence_Audit_Log::get_count($query_args);
    
    // For free users, cap total entries at 50
    if (!$is_premium && $total_entries > 50) {
        $total_entries = 50;
    }
    
    $total_pages = ceil($total_entries / $per_page);

    // Get statistics for last 30 days
    $event_stats = VMPFence_Audit_Log::get_event_statistics(30);
    $user_stats = VMPFence_Audit_Log::get_user_statistics(30);
}

// Assets are enqueued in dashboard.php admin_enqueue_scripts hook
?>

<?php if (!$in_tools_page): ?>
<div class="wrap vmpfence-audit-log" style="max-width: 1300px;">
<?php else: ?>
<div class="vmpfence-audit-log-embedded">
<?php endif; ?>
    
    <!-- Header Section -->
    <div class="audit-log-header-section">
        <?php if (!$in_tools_page): ?>
        <h1>
            <?php echo esc_html(get_admin_page_title()); ?>
            <!-- <a href="#" class="audit-log-learn-more" target="_blank" rel="noopener noreferrer">
                <?php echo esc_html__('Learn more about the Audit Log', 'vmpfence-security'); ?>
                <span class="dashicons dashicons-external"></span>
            </a> -->
        </h1>
        <?php else: ?>
        <div style="display: flex; justify-content: flex-end; margin-bottom: 15px;">
            <!-- <a href="#" class="audit-log-learn-more" target="_blank" rel="noopener noreferrer">
                <?php echo esc_html__('Learn more about the Audit Log', 'vmpfence-security'); ?>
                <span class="dashicons dashicons-external"></span>
            </a> -->
        </div>
        <?php endif; ?>
        
        <!-- Top Description -->
        <div class="audit-log-description">
            <p><?php echo esc_html__('The VMP Security Audit Log records a history of events on your site to assist in monitoring for unauthorized actions or signs of compromise, ranging from user creation and editing to plugin/theme installation and updates. You can choose to log all events or significant events only, which excludes all authentication, site configuration, and site functionality events. Events are securely saved to VMP Security Central to prevent any tampering with this data that may interfere with your incident analysis and response.', 'vmpfence-security'); ?></p>
        </div>

        <?php if ($in_tools_page): ?>
        <!-- Audit Log Options Panel (Only in Tools view) -->
        <div class="audit-log-options-panel">
            <div class="audit-log-options-header" id="audit-log-options-toggle">
                <h3><?php echo esc_html__('Audit Log Options', 'vmpfence-security'); ?></h3>
                <span class="audit-log-toggle-icon">▶</span>
            </div>
            <div class="audit-log-options-content" style="display: none;">
                <!-- Options Description -->
                <div class="audit-log-options-description">
                    <p><?php echo esc_html__('These options let you choose which site events to record in the audit log. When enabled and your site is connected to VMP Security Central, these events are automatically sent to Central to prevent any tampering by an attacker. When', 'vmpfence-security'); ?> <strong><?php echo esc_html__('Audit Log logging mode', 'vmpfence-security'); ?></strong> <?php echo esc_html__('is set to "Significant Events", all events except content changes will be recorded. "All Events" will include content-related events and may be used to monitor for unauthorized post or page changes. "Preview" and "Disabled" modes do not send any events to Central.', 'vmpfence-security'); ?></p>
                </div>

                <!-- Action Buttons -->
                <div class="audit-log-options-buttons">
                    <button type="button" class="button button-secondary-outline" id="audit-log-restore-defaults">
                        <?php echo esc_html__('RESTORE DEFAULTS', 'vmpfence-security'); ?>
                    </button>
                    <button type="button" class="button button-secondary-outline" id="audit-log-cancel-changes">
                        <?php echo esc_html__('CANCEL CHANGES', 'vmpfence-security'); ?>
                    </button>
                    <button type="button" class="button button-primary" id="audit-log-save-changes">
                        <?php echo esc_html__('SAVE CHANGES', 'vmpfence-security'); ?>
                    </button>
                </div>

                <form id="vmpfence-audit-log-options-form">

                <!-- Logging Mode Selection -->
                <div class="audit-log-option-row">
                    <label class="audit-log-option-label">
                        <?php echo esc_html__('Audit Log logging mode', 'vmpfence-security'); ?>
                        <span class="dashicons dashicons-editor-help audit-log-help-icon" title="<?php echo esc_attr__('Choose which events to log', 'vmpfence-security'); ?>"></span>
                    </label>
                    <div class="audit-log-toggle-group">
                        <?php
                        $saved_mode = get_option('vmpfence_audit_log_logging_mode', 'preview');
                        ?>
                        <button type="button" class="audit-log-toggle-btn<?php echo ($saved_mode === 'disabled') ? ' active' : ''; ?>" data-mode="disabled">
                            <?php echo esc_html__('DISABLED', 'vmpfence-security'); ?>
                        </button>
                        <button type="button" class="audit-log-toggle-btn<?php echo ($saved_mode === 'preview') ? ' active' : ''; ?>" data-mode="preview">
                            <?php echo esc_html__('PREVIEW', 'vmpfence-security'); ?>
                        </button>
                        <button type="button" class="audit-log-toggle-btn<?php echo ($saved_mode === 'significant') ? ' active' : ''; ?>" data-mode="significant">
                            <?php echo esc_html__('SIGNIFICANT EVENTS', 'vmpfence-security'); ?>
                        </button>
                        <button type="button" class="audit-log-toggle-btn<?php echo ($saved_mode === 'all') ? ' active' : ''; ?>" data-mode="all">
                            <?php echo esc_html__('ALL EVENTS', 'vmpfence-security'); ?>
                        </button>
                    </div>
                    <input type="hidden" name="audit_log_logging_mode" id="audit_log_logging_mode" value="<?php echo esc_attr($saved_mode); ?>">
                </div>

                <!-- Display Menu Option -->
                <div class="audit-log-option-row">
                    <label class="audit-log-checkbox-label">
                        <span class="audit-log-styled-checkbox">
                            <?php
                            $display_menu = VMPFence_Config::get('display_audit_log_menu', 1);
                            ?>
                            <input type="checkbox" name="display_audit_log_menu" id="display_audit_log_menu" value="1" <?php checked($display_menu, '1'); ?> />
                            <span class="checkmark"></span>
                        </span>
                        <span><?php echo esc_html__('Display Audit Log menu option', 'vmpfence-security'); ?></span>
                    </label>
                </div>
                </form>
            </div>
        </div>

        <?php if (!$is_premium): ?>
        <!-- Premium Feature Notice -->
        <div class="audit-log-premium-notice">
            <div class="audit-log-premium-status">
                <strong><?php echo esc_html__('Audit log mode: Not recording.', 'vmpfence-security'); ?></strong>
                <span class="audit-log-premium-badge"><?php echo esc_html__('Premium Feature', 'vmpfence-security'); ?></span>
            </div>
        </div>

        <!-- Off-Site Logging Section -->
        <div class="audit-log-offsite-section">
            <h3><?php echo esc_html__('Log Security Events to an Off-Site Audit Log on VMP Security Central', 'vmpfence-security'); ?></h3>
            <div class="audit-log-offsite-content">
                <div class="audit-log-offsite-text">
                    <p><?php echo esc_html__('The VMP Security Audit Log is designed to monitor all changes and actions in security-sensitive areas of the site. Actions such as user creation, plugin installation and activation, changes to settings, and similar are all logged with relevant contextual information for later review or forensic analysis. Additionally, the log is securely saved outside of the site on VMP Security Central to avoid tampering or deletion by malicious actors.', 'vmpfence-security'); ?></p>
                </div>
                <div class="audit-log-offsite-image">
                    <div class="audit-log-placeholder-image">
                        <span class="dashicons dashicons-desktop"></span>
                        <p><?php echo esc_html__('VMP Security Central Dashboard', 'vmpfence-security'); ?></p>
                    </div>
                </div>
            </div>
            <div class="audit-log-offsite-actions">
                <!-- <button type="button" class="button button-primary button-large" disabled>
                    <?php echo esc_html__('UPGRADE TO PREMIUM', 'vmpfence-security'); ?>
                </button> -->
            </div>
        </div>
        <?php endif; // End free user sections ?>
        <?php endif; // End Tools-only sections ?>
    </div>

    <div class="nav-tab-wrapper audit-log-tabs">
        <?php 
        $base_url = $in_tools_page 
            ? admin_url('admin.php?page=vmpfence-tools&tab=audit-log') 
            : admin_url('admin.php?page=vmpfence-audit-log');
        $tab_param = $in_tools_page ? 'audit_subtab' : 'tab';
        ?>
        <a href="<?php echo esc_url(add_query_arg($tab_param, 'compliance', $base_url)); ?>" 
           class="nav-tab <?php echo ($current_tab === 'compliance') ? 'nav-tab-active' : ''; ?>">
             Compliance Audit
        </a>
        <a href="<?php echo esc_url(add_query_arg($tab_param, 'security', $base_url)); ?>" 
           class="nav-tab <?php echo ($current_tab === 'security') ? 'nav-tab-active' : ''; ?>">
             Security Events
        </a>
    </div>

    <?php if ($current_tab === 'compliance'): ?>
    <!-- COMPLIANCE AUDIT TAB CONTENT -->

    <!-- Recent Event Summary Header -->
    <div class="audit-log-summary-header" id="audit-log-recent-event-summary">
        <h2><?php echo esc_html__('Recent Event Summary', 'vmpfence-security'); ?></h2>
        <p class="audit-log-summary-subtitle"><?php echo esc_url(home_url()); ?></p>
        <p class="audit-log-summary-description"><?php echo esc_html__('The most recently-detected events on this site are listed below. When the audit log is enabled and your site is connected to VMP Security Central, full details of each event can be found on Central. This includes information such as record IDs, version numbers, and which modifications were made. Log entries in preview mode are only stored locally.', 'vmpfence-security'); ?></p>
    </div>

    <!-- Statistics Overview - Premium Feature -->
    <?php /* ?>
    <div class="audit-stats-grid">
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($total_entries)); ?></div>
                <div class="stat-label">Total Events</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">📅</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(count($event_stats)); ?></div>
                <div class="stat-label">Event Types (30d)</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">👥</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(count($user_stats)); ?></div>
                <div class="stat-label">Active Users (30d)</div>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon">🕐</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(current_time('H:i')); ?></div>
                <div class="stat-label">Last Update</div>
            </div>
        </div>
    </div>
    <?php */ ?>

    <!-- Filters - Premium Feature -->
    <?php /* ?>
    <div class="audit-filters">
        <form method="get" class="filter-form">
            <?php if ($in_tools_page): ?>
            <input type="hidden" name="page" value="vmpfence-tools">
            <input type="hidden" name="tab" value="audit-log">
            <input type="hidden" name="audit_subtab" value="compliance">
            <?php else: ?>
            <input type="hidden" name="page" value="vmpfence-audit-log">
            <input type="hidden" name="tab" value="compliance">
            <?php endif; ?>
            
            <div class="filter-row">
                <div class="filter-group">
                    <label for="filter_event_type">Event Type:</label>
                    <select name="filter_event_type" id="filter_event_type">
                        <option value="">All Events</option>
                        <?php foreach ($event_stats as $stat): ?>
                            <option value="<?php echo esc_attr($stat['event_type']); ?>" <?php selected($filter_event_type, $stat['event_type']); ?>>
                                <?php echo esc_html(ucwords(str_replace('_', ' ', $stat['event_type']))); ?> (<?php echo esc_html($stat['count']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label for="filter_date_from">Date From:</label>
                    <input type="date" name="filter_date_from" id="filter_date_from" value="<?php echo esc_attr($filter_date_from); ?>">
                </div>

                <div class="filter-group">
                    <label for="filter_date_to">Date To:</label>
                    <input type="date" name="filter_date_to" id="filter_date_to" value="<?php echo esc_attr($filter_date_to); ?>">
                </div>

                <div class="filter-group">
                    <label for="filter_search">Search:</label>
                    <input type="text" name="filter_search" id="filter_search" value="<?php echo esc_attr($filter_search); ?>" placeholder="Search message, user, object...">
                </div>

                <div class="filter-actions">
                    <button type="submit" class="button button-primary">
                        <span class="dashicons dashicons-filter"></span> Apply Filters
                    </button>
                    <a href="<?php echo esc_url(add_query_arg($tab_param, 'compliance', $base_url)); ?>" class="button">
                        <span class="dashicons dashicons-dismiss"></span> Clear
                    </a>
                </div>
            </div>
        </form>
    </div>
    <?php */ ?>

    <!-- Audit Log Table -->
    <?php if (!$is_premium): ?>
    <div class="audit-log-premium-restriction" style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between;">
        <div>
            <strong><?php echo esc_html__('Limited to 50 Recent Entries', 'vmpfence-security'); ?></strong>
            <p style="margin: 5px 0 0 0;"><?php echo esc_html__('Upgrade to Premium to access your complete audit log history with unlimited entries and advanced filtering.', 'vmpfence-security'); ?></p>
        </div>
        <!-- <button type="button" class="button button-primary" disabled style="white-space: nowrap;">
            <?php echo esc_html__('UPGRADE TO PREMIUM', 'vmpfence-security'); ?>
        </button> -->
    </div>
    <?php endif; ?>
    <div class="audit-log-container">
        <?php if (empty($entries)): ?>
            <div class="no-entries">
                <span class="dashicons dashicons-info"></span>
                <p>No audit log entries found matching your filters.</p>
            </div>
        <?php else: ?>
            <table class="wp-list-table widefat fixed striped audit-log-table">
                <thead>
                    <tr>
                        <th class="column-time">Time</th>
                        <th class="column-event">Event Type</th>
                        <th class="column-user">User</th>
                        <th class="column-ip">IP Address</th>
                        <th class="column-message">Message</th>
                        <th class="column-details">Details</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $grouped = VMPFence_Audit_Log::group_entries($entries);
                    foreach ($grouped as $group):
                        $primary = $group['primary'];
                        $entry_ids = array_map(function($e) { return $e['id']; }, $group['entries']);
                    ?>
                        <tr data-entry-id="<?php echo esc_attr($primary['id']); ?>">
                            <td class="column-time">
                                <span class="timestamp" title="<?php echo esc_attr($primary['time_formatted']); ?>">
                                    <?php echo esc_html(human_time_diff((int)$primary['time'], time()) . ' ago'); ?>
                                </span>
                            </td>
                            <td class="column-event">
                                <?php $total = count($group['entries']); $i = 0; foreach ($group['entries'] as $ge): $i++; ?>
                                    <span class="event-type-indicator">
                                        <?php
                                        $event_type = $ge['event_type'];
                                        $color_class = 'event-color-default';
                                        
                                        if (strpos($event_type, 'login') !== false || strpos($event_type, 'logout') !== false || strpos($event_type, 'auth') !== false || strpos($event_type, 'password') !== false) {
                                            $color_class = 'event-color-authentication';
                                        } elseif (strpos($event_type, 'user') !== false || strpos($event_type, 'role') !== false || strpos($event_type, 'capabilities') !== false || strpos($event_type, 'super_admin') !== false) {
                                            $color_class = 'event-color-user';
                                        } elseif (strpos($event_type, 'plugin') !== false || strpos($event_type, 'theme') !== false || strpos($event_type, 'core_update') !== false || strpos($event_type, 'auto_update') !== false) {
                                            $color_class = 'event-color-plugin';
                                        } elseif (strpos($event_type, 'waf') !== false || strpos($event_type, 'block') !== false || strpos($event_type, 'brute') !== false || strpos($event_type, 'lockout') !== false || strpos($event_type, 'threat') !== false || strpos($event_type, 'banned') !== false || strpos($event_type, 'rate_limit') !== false || strpos($event_type, 'custom_pattern') !== false) {
                                            $color_class = 'event-color-firewall';
                                        } elseif (strpos($event_type, 'config') !== false || strpos($event_type, 'setting') !== false || strpos($event_type, 'option') !== false || strpos($event_type, 'vmpfence') !== false || strpos($event_type, 'license') !== false) {
                                            $color_class = 'event-color-settings';
                                        } elseif (strpos($event_type, 'multisite') !== false || strpos($event_type, 'network') !== false) {
                                            $color_class = 'event-color-multisite';
                                        } elseif (strpos($event_type, 'post') !== false || strpos($event_type, 'page') !== false || strpos($event_type, 'content') !== false || strpos($event_type, 'comment') !== false || strpos($event_type, 'media') !== false || strpos($event_type, 'term') !== false || strpos($event_type, 'menu') !== false || strpos($event_type, 'file_upload') !== false) {
                                            $color_class = 'event-color-content';
                                        } elseif (strpos($event_type, 'scan') !== false || strpos($event_type, 'mail') !== false || strpos($event_type, 'recovery') !== false || strpos($event_type, 'file_editor') !== false || strpos($event_type, 'database') !== false || strpos($event_type, 'backup') !== false || strpos($event_type, 'xmlrpc') !== false || strpos($event_type, 'rest_api') !== false || strpos($event_type, 'wp_die') !== false || strpos($event_type, 'customizer') !== false || strpos($event_type, 'support') !== false || strpos($event_type, 'feedback') !== false) {
                                            $color_class = 'event-color-system';
                                        }
                                        ?>
                                        <span class="event-dot <?php echo esc_attr($color_class); ?>"></span>
                                        <?php echo esc_html(VMPFence_Audit_Log::get_event_type_name($ge['event_type'])); ?>
                                    </span><?php if ($i < $total): ?><br><?php endif; ?>
                                <?php endforeach; ?>
                            </td>
                            <td class="column-user">
                                <?php if ($primary['username']): ?>
                                    <strong><?php echo esc_html($primary['username']); ?></strong>
                                    <?php if ($primary['user_role']): ?>
                                        <br><small class="user-role"><?php echo esc_html($primary['user_role']); ?></small>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <em>System</em>
                                <?php endif; ?>
                            </td>
                            <td class="column-ip">
                                <?php echo esc_html(!empty($primary['ip_formatted']) ? $primary['ip_formatted'] : 'N/A'); ?>
                            </td>
                            <td class="column-message">
                                <?php $total_m = count($group['entries']); $m = 0; foreach ($group['entries'] as $me): $m++; ?>
                                    <?php echo esc_html(wp_trim_words($me['message'], 20)); ?><?php if ($m < $total_m): ?><br><?php endif; ?>
                                <?php endforeach; ?>
                            </td>
                            <td class="column-details">
                                <button class="button button-small view-details" style="color: #191970; border-color: #191970;" data-entry-id="<?php echo esc_attr($primary['id']); ?>">
                                    <span class="dashicons dashicons-visibility"></span> View
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <div class="tablenav">
                    <div class="tablenav-pages">
                        <span class="displaying-num">
                            <?php printf(esc_html__('%s items', 'vmpfence-security'), number_format_i18n($total_entries)); ?>
                        </span>
                        <?php
                        $pagination_args = array('paged' => '%#%');
                        $pagination_args[$tab_param] = 'compliance';
                        if ($in_tools_page) {
                            $pagination_args['tab'] = 'audit-log';
                        }
                        
                        $page_links = paginate_links(array(
                            'base' => add_query_arg($pagination_args),
                            'format' => '',
                            'prev_text' => '&laquo;',
                            'next_text' => '&raquo;',
                            'total' => $total_pages,
                            'current' => $current_page
                        ));
                        if ($page_links) {
                            echo '<span class="pagination-links">' . wp_kses_post($page_links) . '</span>';
                        }
                        ?>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Event Type Legend -->
    <div class="audit-log-legend">
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-authentication"></span>
            <span><?php echo esc_html__('Authentication', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-user"></span>
            <span><?php echo esc_html__('User/Permissions', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-plugin"></span>
            <span><?php echo esc_html__('Plugin/Themes/Updates', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-firewall"></span>
            <span><?php echo esc_html__('Firewall', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-settings"></span>
            <span><?php echo esc_html__('Site Settings', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-multisite"></span>
            <span><?php echo esc_html__('Multisite', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-content"></span>
            <span><?php echo esc_html__('Content', 'vmpfence-security'); ?></span>
        </div>
        <div class="audit-log-legend-item">
            <span class="event-dot event-color-system"></span>
            <span><?php echo esc_html__('System', 'vmpfence-security'); ?></span>
        </div>
    </div>

    <!-- Top Event Types -->
    <?php if (!empty($event_stats)): ?>
        <div class="audit-section" style="position: relative;">
            <?php if (!$is_premium): ?>
            <!-- Premium Overlay for Free Users -->
            <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(255, 255, 255, 0.85); z-index: 10; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(3px);">
                <div style="text-align: center; background: rgba(255, 193, 7, 0.95); padding: 30px 40px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
                    <span class="dashicons dashicons-lock" style="font-size: 48px; color: #fff; margin-bottom: 10px; width: 48px; height: 48px;"></span>
                    <h3 style="color: #fff; margin: 10px 0; font-size: 20px;"><?php echo esc_html__('Premium Feature', 'vmpfence-security'); ?></h3>
                    <p style="color: #fff; margin: 10px 0 0 0;"><?php echo esc_html__('Upgrade to Premium for full access to event statistics', 'vmpfence-security'); ?></p>
                </div>
            </div>
            <?php endif; ?>
            <h2>Top Event Types (Last 30 Days) <?php if (!$is_premium): ?><span style="background: #ffc107; color: #000; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 600; margin-left: 10px;">PREMIUM</span><?php endif; ?></h2>
            <div class="event-stats">
                <?php 
                $max_count = !empty($event_stats) ? $event_stats[0]['count'] : 1;
                foreach (array_slice($event_stats, 0, 10) as $stat): 
                    $percentage = ($stat['count'] / $max_count) * 100;
                ?>
                    <div class="stat-row">
                        <span class="stat-label"><?php echo esc_html(ucwords(str_replace('_', ' ', $stat['event_type']))); ?></span>
                        <div class="stat-bar-container">
                            <div class="stat-bar" style="width: <?php echo esc_attr($percentage); ?>%"></div>
                        </div>
                        <span class="stat-count"><?php echo esc_html(number_format($stat['count'])); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Top Users -->
    <?php if (!empty($user_stats)): ?>
        <div class="audit-section">
            <h2>Most Active Users (Last 30 Days)</h2>
            <div class="user-stats">
                <?php 
                $max_count = !empty($user_stats) ? $user_stats[0]['count'] : 1;
                foreach (array_slice($user_stats, 0, 10) as $stat): 
                    $percentage = ($stat['count'] / $max_count) * 100;
                ?>
                    <div class="stat-row">
                        <span class="stat-label">
                            <strong><?php echo esc_html($stat['username'] ?: 'System'); ?></strong>
                            <?php if (!empty($stat['user_role'])): ?>
                                <small>(<?php echo esc_html($stat['user_role']); ?>)</small>
                            <?php endif; ?>
                        </span>
                        <div class="stat-bar-container">
                            <div class="stat-bar stat-bar-user" style="width: <?php echo esc_attr($percentage); ?>%"></div>
                        </div>
                        <span class="stat-count"><?php echo esc_html(number_format($stat['count'])); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <?php endif; // End compliance tab ?>

<?php if ($current_tab === 'security'): ?>
<!-- SECURITY EVENTS TAB CONTENT -->
<?php 
// Include the security events partial view
include VMPFENCE_PLUGIN_DIR . 'admin/views/partials/security-events-view.php';
?>
<?php endif; // End security tab ?>

</div>
<!-- End .wrap -->

<!-- Details Modal -->
<div id="audit-details-modal" class="audit-modal" style="display: none;">
    <div class="audit-modal-content">
        <div class="audit-modal-header">
            <h2>Audit Log Details</h2>
            <button class="audit-modal-close">&times;</button>
        </div>
        <div class="audit-modal-body" id="audit-details-content">
            <div class="loading">Loading...</div>
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Note: ALL handlers are now in audit-log.js to prevent duplicates
    // EXCEPT: Toggle button needs to update hidden input (form serialization requirement)
    
    // Audit log logging mode buttons - update hidden input for form serialization
    $('.audit-log-toggle-btn').on('click', function() {
        $('.audit-log-toggle-btn').removeClass('active');
        $(this).addClass('active');
        $('#audit_log_logging_mode').val($(this).data('mode'));
    });
    
    // View details button click handler
    $(document).on('click', '.view-details', function(e) {
        e.preventDefault();
        var entryId = $(this).data('entry-id');
        
        // Show modal
        $('#audit-details-modal').fadeIn(200);
        $('#audit-details-content').html('<div class="loading">Loading...</div>');
        
        // Fetch details via AJAX
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'vmpfence_get_audit_entry',
                nonce: (typeof vmpfenceAuditLog !== 'undefined') ? vmpfenceAuditLog.nonce : '',
                entry_id: entryId
            },
            success: function(response) {
                if (response.success && response.data && response.data.entry) {
                    var entry = response.data.entry;
                    var html = '<div class="audit-entry-details">';
                    html += '<table class="audit-details-table">';
                    html += '<tr><th>Time:</th><td>' + entry.time_formatted + '</td></tr>';
                    html += '<tr><th>Event Type:</th><td>' + entry.event_type + '</td></tr>';
                    html += '<tr><th>User:</th><td>' + entry.username + ' (' + entry.user_role + ')</td></tr>';
                    html += '<tr><th>Action:</th><td>' + entry.action + '</td></tr>';
                    html += '<tr><th>Object:</th><td>' + (entry.object_type || '—') + '</td></tr>';
                    html += '<tr><th>IP Address:</th><td>' + entry.ip_formatted + '</td></tr>';
                    html += '<tr><th>Message:</th><td>' + entry.message + '</td></tr>';
                    if (entry.old_value) {
                        html += '<tr><th>Old Value:</th><td><pre>' + JSON.stringify(entry.old_value, null, 2) + '</pre></td></tr>';
                    }
                    if (entry.new_value) {
                        html += '<tr><th>New Value:</th><td><pre>' + JSON.stringify(entry.new_value, null, 2) + '</pre></td></tr>';
                    }
                    if (entry.additional_info) {
                        html += '<tr><th>Additional Info:</th><td><pre>' + JSON.stringify(entry.additional_info, null, 2) + '</pre></td></tr>';
                    }
                    html += '</table>';
                    html += '</div>';
                    $('#audit-details-content').html(html);
                } else {
                    $('#audit-details-content').html('<p>Error loading details.</p>');
                }
            },
            error: function() {
                $('#audit-details-content').html('<p>Failed to load details. Please try again.</p>');
            }
        });
    });
    
    // Modal close functionality
    $('.audit-modal-close, .audit-modal').on('click', function(e) {
        if (e.target === this) {
            $('#audit-details-modal').fadeOut(200);
        }
    });
});
</script>
