<?php
/**
 * Sentinel Event Registry Page
 * 
 * Management interface for all registered events.
 */

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

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

// Handle enable/disable event actions
if (isset($_POST['toggle_event']) && wp_verify_nonce($_POST['_wpnonce'], 'sentinel_toggle_event')) {
    $event_key = sanitize_text_field($_POST['event_key']);
    $enabled = isset($_POST['enabled']) ? 1 : 0;
    
    // Update event status in options
    $disabled_events = get_option('sentinel_disabled_events', array());
    if ($enabled) {
        $disabled_events = array_diff($disabled_events, array($event_key));
    } else {
        $disabled_events[] = $event_key;
    }
    update_option('sentinel_disabled_events', array_unique($disabled_events));
    
    echo '<div class="notice notice-success is-dismissible"><p>Event status updated successfully.</p></div>';
}

// Get all registered events dynamically from the Sentinel_Events class
$event_definitions = array();

if (class_exists('Sentinel_Events')) {
    $all_registered_events = Sentinel_Events::get_all_events();
    
    // If no events are registered via the class, fall back to core WordPress events
    if (empty($all_registered_events)) {
        $event_definitions = array(
            // Authentication Events
            'user_login' => array(
                'category' => 'authentication',
                'priority' => 'info',
                'description' => 'User successfully logged in'
            ),
            'user_logout' => array(
                'category' => 'authentication', 
                'priority' => 'info',
                'description' => 'User logged out'
            ),
            'user_registered' => array(
                'category' => 'authentication',
                'priority' => 'info', 
                'description' => 'New user registered'
            ),
            'login_failed' => array(
                'category' => 'authentication',
                'priority' => 'warning',
                'description' => 'Failed login attempt'
            ),
            'auth_cookie_bad' => array(
                'category' => 'authentication',
                'priority' => 'warning',
                'description' => 'Invalid authentication cookie'
            ),

            // Content Events
            'profile_updated' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'User profile updated'
            ),
            'post_published' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Post published'
            ),
            'post_updated' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Post updated'
            ),
            'post_deleted' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Post deleted'
            ),
            'comment_posted' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Comment posted'
            ),
            'comment_approved' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Comment approved'
            ),
            'comment_deleted' => array(
                'category' => 'content',
                'priority' => 'info',
                'description' => 'Comment deleted'
            ),

            // System Events
            'plugin_activated' => array(
                'category' => 'system',
                'priority' => 'info',
                'description' => 'Plugin activated'
            ),
            'plugin_deactivated' => array(
                'category' => 'system',
                'priority' => 'info',
                'description' => 'Plugin deactivated'
            ),
            'logs_cleaned' => array(
                'category' => 'system',
                'priority' => 'info',
                'description' => 'System cleaned up old logs'
            ),
            'tables_optimized' => array(
                'category' => 'system',
                'priority' => 'info',
                'description' => 'Database tables optimized'
            ),

            // Error Events
            'php_fatal_error' => array(
                'category' => 'errors',
                'priority' => 'critical',
                'description' => 'PHP fatal error occurred'
            ),
            'php_warning' => array(
                'category' => 'errors',
                'priority' => 'warning',
                'description' => 'PHP warning occurred'
            ),
            'php_notice' => array(
                'category' => 'errors',
                'priority' => 'info',
                'description' => 'PHP notice occurred'
            ),
            'php_deprecated' => array(
                'category' => 'errors',
                'priority' => 'warning',
                'description' => 'PHP deprecated function used'
            ),
            'wp_database_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'WordPress database error'
            ),
            'wp_memory_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'WordPress memory limit exceeded'
            ),
            'wp_permission_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'WordPress permission error'
            ),
            'wp_config_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'WordPress configuration error'
            ),
            'nonce_verification_failed' => array(
                'category' => 'security',
                'priority' => 'warning',
                'description' => 'Nonce verification failed'
            ),
            'permission_denied' => array(
                'category' => 'security',
                'priority' => 'warning',
                'description' => 'Permission denied'
            ),
            'http_404_error' => array(
                'category' => 'errors',
                'priority' => 'info',
                'description' => 'HTTP 404 error (page not found)'
            ),
            'http_500_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'HTTP 500 error (server error)'
            ),
            'wp_remote_error' => array(
                'category' => 'errors',
                'priority' => 'warning',
                'description' => 'WordPress remote request error'
            ),
            'wp_cron_error' => array(
                'category' => 'errors',
                'priority' => 'warning',
                'description' => 'WordPress cron error'
            ),
            'plugin_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'Plugin error occurred'
            ),
            'theme_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'Theme error occurred'
            ),
            'plugin_activation_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'Plugin activation error'
            ),
            'file_upload_error' => array(
                'category' => 'errors',
                'priority' => 'warning',
                'description' => 'File upload error'
            ),
            'file_permission_error' => array(
                'category' => 'errors',
                'priority' => 'error',
                'description' => 'File permission error'
            )
        );
    } else {
        // Use dynamically registered events
        $event_definitions = $all_registered_events;
    }
} else {
    // Fallback message if class doesn't exist
    echo '<div class="notice notice-error"><p>Sentinel_Events class not found. Please check your plugin installation.</p></div>';
}

// Get all registered events (from the registration function)
$all_events = array();
$disabled_events = get_option('sentinel_disabled_events', array());

// Get usage statistics for each event (with role-based filtering)
$stats_query = "SELECT event_key, COUNT(*) as count, MAX(created_at) as last_triggered 
     FROM $table 
     GROUP BY event_key";

$stats_results = $wpdb->get_results($stats_query);

foreach ($stats_results as $stat) {
    $event_stats[$stat->event_key] = array(
        'count' => $stat->count,
        'last_triggered' => $stat->last_triggered
    );
}

// Filter handling
$category_filter = isset($_GET['category_filter']) ? sanitize_text_field($_GET['category_filter']) : '';
$priority_filter = isset($_GET['priority_filter']) ? sanitize_text_field($_GET['priority_filter']) : '';
$status_filter = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
$search_filter = isset($_GET['search_filter']) ? sanitize_text_field($_GET['search_filter']) : '';

// Apply filters
$filtered_events = $event_definitions;

if ($category_filter) {
    $filtered_events = array_filter($filtered_events, function($event) use ($category_filter) {
        return $event['category'] === $category_filter;
    });
}

if ($priority_filter) {
    $filtered_events = array_filter($filtered_events, function($event) use ($priority_filter) {
        return $event['priority'] === $priority_filter;
    });
}

if ($status_filter) {
    $filtered_events = array_filter($filtered_events, function($event, $key) use ($status_filter, $disabled_events) {
        $is_disabled = in_array($key, $disabled_events);
        if ($status_filter === 'enabled') {
            return !$is_disabled;
        } elseif ($status_filter === 'disabled') {
            return $is_disabled;
        }
        return true;
    }, ARRAY_FILTER_USE_BOTH);
}

if ($search_filter) {
    $filtered_events = array_filter($filtered_events, function($event, $key) use ($search_filter) {
        return stripos($key, $search_filter) !== false || 
               stripos($event['description'], $search_filter) !== false;
    }, ARRAY_FILTER_USE_BOTH);
}

// Get unique categories and priorities for filters
$categories = array_unique(array_column($event_definitions, 'category'));
$priorities = array_unique(array_column($event_definitions, 'priority'));
sort($categories);
sort($priorities);
?>

<div class="wrap sentinel-dashboard">
    <div class="sentinel-logo">
        <div class="sentinel-logo-card">
            <img src="<?php echo plugins_url('assets/img/Logo.png', dirname(__FILE__, 2)); ?>" alt="Sentinel Logo"
                height="80" />
        </div>
    </div>
    <h1 class="sentinel-dashboard-title">Event Registry</h1>
    <p>Manage all registered events in the Sentinel logging system. Enable or disable events, view usage statistics, and
        configure event settings.</p>



    <div class="notice notice-info">
        <p><strong>ℹ️ Event Logging Control:</strong> Events that are disabled (toggle switch off) will <strong>not be
                logged</strong> to the database.
            This allows you to control which activities are tracked without affecting your site's functionality.
            Changes take effect immediately.</p>
    </div>

    <!-- Filters -->
    <div class="sentinel-filters">
        <form method="get" action="">
            <input type="hidden" name="page" value="sentinel-events">

            <div class="sentinel-filter-row">
                <div class="sentinel-filter-group">
                    <label for="category_filter">Category:</label>
                    <select name="category_filter" id="category_filter">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $category): ?>
                        <option value="<?php echo esc_attr($category); ?>"
                            <?php selected($category_filter, $category); ?>>
                            <?php echo esc_html(ucfirst($category)); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="sentinel-filter-group">
                    <label for="priority_filter">Priority:</label>
                    <select name="priority_filter" id="priority_filter">
                        <option value="">All Priorities</option>
                        <?php foreach ($priorities as $priority): ?>
                        <option value="<?php echo esc_attr($priority); ?>"
                            <?php selected($priority_filter, $priority); ?>>
                            <?php echo esc_html(ucfirst($priority)); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="sentinel-filter-group">
                    <label for="status_filter">Status:</label>
                    <select name="status_filter" id="status_filter">
                        <option value="">All Statuses</option>
                        <option value="enabled" <?php selected($status_filter, 'enabled'); ?>>Enabled</option>
                        <option value="disabled" <?php selected($status_filter, 'disabled'); ?>>Disabled</option>
                    </select>
                </div>

                <div class="sentinel-filter-group">
                    <label for="search_filter">Search:</label>
                    <input type="text" name="search_filter" id="search_filter"
                        value="<?php echo esc_attr($search_filter); ?>" placeholder="Search events...">
                </div>
            </div>

            <div class="sentinel-filter-row">
                <div class="sentinel-filter-actions">
                    <button type="submit" class="button button-primary">Filter</button>
                    <a href="<?php echo admin_url('admin.php?page=sentinel-events'); ?>" class="button">Clear
                        Filters</a>
                </div>
            </div>
        </form>
    </div>

    <!-- Summary Stats -->
    <div class="sentinel-event-summary">
        <div class="sentinel-summary-stats">
            <div class="sentinel-summary-stat">
                <span class="count"><?php echo count($event_definitions); ?></span>
                <span class="label">Total Events</span>
            </div>
            <div class="sentinel-summary-stat">
                <span class="count"><?php echo count($event_definitions) - count($disabled_events); ?></span>
                <span class="label">Enabled</span>
            </div>
            <div class="sentinel-summary-stat">
                <span class="count"><?php echo count($disabled_events); ?></span>
                <span class="label">Disabled</span>
            </div>
            <div class="sentinel-summary-stat">
                <span class="count"><?php echo count($filtered_events); ?></span>
                <span class="label">Filtered Results</span>
            </div>
        </div>
    </div>

    <!-- Events Table -->
    <div class="sentinel-events-table">
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th style="width: 50px;">Status</th>
                    <th>Event Key</th>
                    <th>Category</th>
                    <th>Priority</th>
                    <th>Description</th>
                    <th>Usage Count</th>
                    <th>Last Triggered</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($filtered_events): ?>
                <?php foreach ($filtered_events as $event_key => $event): ?>
                <?php 
                $is_disabled = in_array($event_key, $disabled_events);
                $usage_count = isset($event_stats[$event_key]) ? $event_stats[$event_key]['count'] : 0;
                $last_triggered = isset($event_stats[$event_key]) ? $event_stats[$event_key]['last_triggered'] : null;
                ?>
                <tr class="<?php echo $is_disabled ? 'sentinel-event-disabled' : ''; ?>">
                    <td>
                        <form method="post" style="display: inline;">
                            <?php wp_nonce_field('sentinel_toggle_event'); ?>
                            <input type="hidden" name="event_key" value="<?php echo esc_attr($event_key); ?>">
                            <input type="hidden" name="toggle_event" value="1">
                            <label class="sentinel-toggle-switch">
                                <input type="checkbox" name="enabled" value="1" <?php checked(!$is_disabled); ?>>
                                <span class="sentinel-toggle-slider"></span>
                            </label>
                        </form>
                    </td>
                    <td>
                        <code class="sentinel-event-key"><?php echo esc_html($event_key); ?></code>
                    </td>
                    <td>
                        <span class="sentinel-category sentinel-category-<?php echo esc_attr($event['category']); ?>">
                            <?php echo esc_html(ucfirst($event['category'])); ?>
                        </span>
                    </td>
                    <td>
                        <span class="sentinel-priority sentinel-priority-<?php echo esc_attr($event['priority']); ?>">
                            <?php echo esc_html(ucfirst($event['priority'])); ?>
                        </span>
                    </td>
                    <td><?php echo esc_html($event['description']); ?></td>
                    <td>
                        <?php if ($usage_count > 0): ?>
                        <span class="sentinel-usage-count"><?php echo number_format($usage_count); ?></span>
                        <?php else: ?>
                        <span class="sentinel-no-usage">Never triggered</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($last_triggered): ?>
                        <span class="sentinel-last-triggered">
                            <?php echo human_time_diff(strtotime($last_triggered), current_time('timestamp')); ?> ago
                        </span>
                        <?php else: ?>
                        <span class="sentinel-never-triggered">Never</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <button class="button button-small"
                            onclick="showEventDetails('<?php echo esc_js($event_key); ?>')">
                            View Details
                        </button>
                    </td>
                </tr>
                <tr id="event-details-<?php echo esc_attr($event_key); ?>" style="display: none;">
                    <td colspan="8">
                        <div class="sentinel-event-details">
                            <h4>Event Details: <?php echo esc_html($event_key); ?></h4>

                            <div class="sentinel-detail-grid">
                                <div class="sentinel-detail-column">
                                    <div class="sentinel-detail-row">
                                        <strong>Event Key:</strong>
                                        <code><?php echo esc_html($event_key); ?></code>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>Category:</strong>
                                        <span
                                            class="sentinel-category sentinel-category-<?php echo esc_attr($event['category']); ?>">
                                            <?php echo esc_html(ucfirst($event['category'])); ?>
                                        </span>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>Priority:</strong>
                                        <span
                                            class="sentinel-priority sentinel-priority-<?php echo esc_attr($event['priority']); ?>">
                                            <?php echo esc_html(ucfirst($event['priority'])); ?>
                                        </span>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>Status:</strong>
                                        <span
                                            class="sentinel-status-<?php echo $is_disabled ? 'disabled' : 'enabled'; ?>">
                                            <?php echo $is_disabled ? 'Disabled' : 'Enabled'; ?>
                                        </span>
                                    </div>
                                </div>

                                <div class="sentinel-detail-column">
                                    <div class="sentinel-detail-row">
                                        <strong>Total Triggers:</strong>
                                        <?php echo number_format($usage_count); ?>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>First Triggered:</strong>
                                        <?php if ($usage_count > 0): ?>
                                        <?php 
                                            $first_log = $wpdb->get_var($wpdb->prepare(
                                                "SELECT created_at FROM $table WHERE event_key = %s ORDER BY created_at ASC LIMIT 1",
                                                $event_key
                                            ));
                                            echo $first_log ? date('Y-m-d H:i:s', strtotime($first_log)) : 'Unknown';
                                            ?>
                                        <?php else: ?>
                                        Never
                                        <?php endif; ?>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>Last Triggered:</strong>
                                        <?php echo $last_triggered ? date('Y-m-d H:i:s', strtotime($last_triggered)) : 'Never'; ?>
                                    </div>
                                    <div class="sentinel-detail-row">
                                        <strong>Avg. Per Day:</strong>
                                        <?php 
                                        if ($usage_count > 0 && $last_triggered) {
                                            $days_since_first = max(1, (strtotime($last_triggered) - strtotime($first_log ?? $last_triggered)) / (24 * 60 * 60));
                                            echo number_format($usage_count / $days_since_first, 2);
                                        } else {
                                            echo '0';
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>

                            <div class="sentinel-detail-row">
                                <strong>Description:</strong>
                                <?php echo esc_html($event['description']); ?>
                            </div>

                            <?php if ($usage_count > 0): ?>
                            <div class="sentinel-detail-row">
                                <strong>Actions:</strong>
                                <a href="<?php echo admin_url('admin.php?page=sentinel-logs&event_filter=' . urlencode($event_key)); ?>"
                                    class="button button-small">
                                    View Logs for This Event
                                </a>
                            </div>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="8">No events found matching your criteria.</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function showEventDetails(eventKey) {
    const detailsRow = document.getElementById('event-details-' + eventKey);
    if (detailsRow.style.display === 'none') {
        detailsRow.style.display = 'table-row';
    } else {
        detailsRow.style.display = 'none';
    }
}

// Auto-submit toggle forms
document.addEventListener('DOMContentLoaded', function() {
    const toggles = document.querySelectorAll('.sentinel-toggle-switch input[type="checkbox"]');
    toggles.forEach(toggle => {
        toggle.addEventListener('change', function() {
            // Add a small delay to show the visual change
            setTimeout(() => {
                this.form.submit();
            }, 100);
        });
    });
});
</script>