<?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>';
}

// Load event definitions from centralized file
require_once plugin_dir_path(__FILE__) . '../../includes/event-definitions.php';

// Verify the function exists - if not, something is seriously wrong
if (!function_exists('sentinel_get_default_event_definitions')) {
    wp_die('Critical Error: Event definitions not loaded. Please check Sentinel plugin installation.');
}

// Always use the centralized event definitions as the source of truth
$event_definitions = sentinel_get_default_event_definitions();

// Verify we got valid data
if (empty($event_definitions) || !is_array($event_definitions)) {
    wp_die('Critical Error: No event definitions found. Please check Sentinel plugin installation.');
}

// 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);

// Add AJAX nonce for custom events functionality
$ajax_nonce = wp_create_nonce('sentinel_ajax_nonce');
?>

<div class="wrap sentinel-dashboard">
    <!-- Hidden input for AJAX nonce -->
    <input type="hidden" id="sentinel_ajax_nonce" value="<?php echo esc_attr($ajax_nonce); ?>" />
    <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>

    <!-- 3rd Party Plugin Integrations Section (Available to all users) -->
    <div class="sentinel-settings-card" style="margin-bottom: 30px;">
        <div class="sentinel-settings-card-header">
            <h2 class="sentinel-settings-card-title">
                <i class="dashicons dashicons-admin-plugins"></i>
                3rd Party Plugin Integrations
            </h2>
        </div>
        <div class="sentinel-settings-card-content sentinel-plugin-integrations">
            <?php
            // Detect active plugins
            $woocommerce_active = is_plugin_active('woocommerce/woocommerce.php');
            $cf7_active = is_plugin_active('contact-form-7/wp-contact-form-7.php');
            $wpforms_active = is_plugin_active('wpforms-lite/wpforms.php') || class_exists('WPForms');
            $gravity_forms_active = class_exists('GFForms');
            $yoast_seo_active = is_plugin_active('wordpress-seo/wp-seo.php') && class_exists('WPSEO_Options');

            // Check which templates are already configured
            $existing_custom_events = get_option('sentinel_custom_events', array());
            $templates_config = sentinel_get_plugin_templates();

            // Check if template events are already created
            function sentinel_template_status($template_key, $templates_config, $existing_custom_events)
            {
                if (!isset($templates_config[$template_key])) return array('configured' => false, 'events_created' => 0);

                $template_events = array_keys($templates_config[$template_key]['events']);
                $created_events = 0;

                foreach ($template_events as $event_key) {
                    if (isset($existing_custom_events[$event_key])) {
                        $created_events++;
                    }
                }

                return array(
                    'configured' => $created_events > 0,
                    'events_created' => $created_events,
                    'total_events' => count($template_events),
                    'fully_configured' => $created_events === count($template_events)
                );
            }

            $woo_status = sentinel_template_status('woocommerce', $templates_config, $existing_custom_events);
            $cf7_status = sentinel_template_status('contact-form-7', $templates_config, $existing_custom_events);
            $wpforms_status = sentinel_template_status('wpforms', $templates_config, $existing_custom_events);
            $gf_status = sentinel_template_status('gravity-forms', $templates_config, $existing_custom_events);
            $yoast_status = sentinel_template_status('yoast-seo', $templates_config, $existing_custom_events);
            // Elementor removed

            // Check if any templates are available to show (not fully configured)
            $woo_available = $woocommerce_active && !$woo_status['fully_configured'];
            $cf7_available = $cf7_active && !$cf7_status['fully_configured'];
            $wpforms_available = $wpforms_active && !$wpforms_status['fully_configured'];
            $gf_available = $gravity_forms_active && !$gf_status['fully_configured'];
            $yoast_available = $yoast_seo_active && !$yoast_status['fully_configured'];
            $any_templates_available = $woo_available || $cf7_available || $wpforms_available || $gf_available || $yoast_available;

            // Check if any plugins are active (for showing the entire plugin integrations section)
            $any_plugins_active = $woocommerce_active || $cf7_active || $wpforms_active || $gravity_forms_active || $yoast_seo_active;

            // Only show Quick Setup Templates section if there are templates to configure
            if ($any_templates_available): ?>
                <!-- Quick Setup Templates -->
                <div class="sentinel-templates-section">
                    <h4>Quick Setup Templates</h4>
                    <p>One-click setup for popular WordPress plugins. Templates will automatically configure optimal
                        settings for common events.</p>

                    <div class="sentinel-templates-grid">

                        <?php if ($woocommerce_active && !$woo_status['fully_configured']): ?>
                            <!-- WooCommerce Templates -->
                            <div class="sentinel-template-card">
                                <div class="sentinel-template-header">
                                    <h5>🛒 WooCommerce Events</h5>
                                    <span class="sentinel-plugin-badge">Plugin Detected</span>
                                </div>
                                <div class="sentinel-template-body">
                                    <p>Track orders, payments, and customer actions</p>
                                    <ul class="sentinel-template-events">
                                        <li>New Order Placed</li>
                                        <li>Payment Completed</li>
                                        <li>Order Status Changed</li>
                                        <li>Payment Failed</li>
                                    </ul>
                                    <div class="sentinel-template-actions">
                                        <?php if ($woo_status['configured']): ?>
                                            <div class="sentinel-template-partial">
                                                <span class="sentinel-partial-badge">⚠️ Partially Configured</span>
                                                <div class="sentinel-partial-details">
                                                    <?php echo $woo_status['events_created']; ?> of
                                                    <?php echo $woo_status['total_events']; ?> events configured.
                                                    <button type="button" class="button button-secondary sentinel-setup-template"
                                                        data-template="woocommerce">
                                                        Complete Setup
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="button button-primary sentinel-setup-template"
                                                data-template="woocommerce">
                                                Setup WooCommerce Events
                                            </button>
                                        <?php endif; ?>
                                        <div class="sentinel-template-status" id="template-status-woocommerce"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($cf7_active && !$cf7_status['fully_configured']): ?>
                            <!-- Contact Form 7 Templates -->
                            <div class="sentinel-template-card">
                                <div class="sentinel-template-header">
                                    <h5>📝 Contact Form 7 Events</h5>
                                    <span class="sentinel-plugin-badge">Plugin Detected</span>
                                </div>
                                <div class="sentinel-template-body">
                                    <p>Track form submissions and failures</p>
                                    <ul class="sentinel-template-events">
                                        <li>Form Submitted</li>
                                        <li>Form Submission Failed</li>
                                    </ul>
                                    <div class="sentinel-template-actions">
                                        <?php if ($cf7_status['configured']): ?>
                                            <div class="sentinel-template-partial">
                                                <span class="sentinel-partial-badge">⚠️ Partially Configured</span>
                                                <div class="sentinel-partial-details">
                                                    <?php echo $cf7_status['events_created']; ?> of
                                                    <?php echo $cf7_status['total_events']; ?> events configured.
                                                    <button type="button" class="button button-secondary sentinel-setup-template"
                                                        data-template="contact-form-7">
                                                        Complete Setup
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="button button-primary sentinel-setup-template"
                                                data-template="contact-form-7">
                                                Setup Contact Form 7 Events
                                            </button>
                                        <?php endif; ?>
                                        <div class="sentinel-template-status" id="template-status-contact-form-7"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($wpforms_active && !$wpforms_status['fully_configured']): ?>
                            <!-- WPForms Templates -->
                            <div class="sentinel-template-card">
                                <div class="sentinel-template-header">
                                    <h5>📝 WPForms Events</h5>
                                    <span class="sentinel-plugin-badge">Plugin Detected</span>
                                </div>
                                <div class="sentinel-template-body">
                                    <p>Track form submissions and payments</p>
                                    <ul class="sentinel-template-events">
                                        <li>Form Submitted</li>
                                        <li>Payment Completed</li>
                                    </ul>
                                    <div class="sentinel-template-actions">
                                        <?php if ($wpforms_status['configured']): ?>
                                            <div class="sentinel-template-partial">
                                                <span class="sentinel-partial-badge">⚠️ Partially Configured</span>
                                                <div class="sentinel-partial-details">
                                                    <?php echo $wpforms_status['events_created']; ?> of
                                                    <?php echo $wpforms_status['total_events']; ?> events configured.
                                                    <button type="button" class="button button-secondary sentinel-setup-template"
                                                        data-template="wpforms">
                                                        Complete Setup
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="button button-primary sentinel-setup-template"
                                                data-template="wpforms">
                                                Setup WPForms Events
                                            </button>
                                        <?php endif; ?>
                                        <div class="sentinel-template-status" id="template-status-wpforms"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>



                        <?php if ($gravity_forms_active && !$gf_status['fully_configured']): ?>
                            <!-- Gravity Forms Templates -->
                            <div class="sentinel-template-card">
                                <div class="sentinel-template-header">
                                    <h5>📋 Gravity Forms Events</h5>
                                    <span class="sentinel-plugin-badge">Plugin Detected</span>
                                </div>
                                <div class="sentinel-template-body">
                                    <p>Track form submissions and payments</p>
                                    <ul class="sentinel-template-events">
                                        <li>Form Submitted</li>
                                        <li>Payment Completed</li>
                                    </ul>
                                    <div class="sentinel-template-actions">
                                        <?php if ($gf_status['configured']): ?>
                                            <div class="sentinel-template-partial">
                                                <span class="sentinel-partial-badge">⚠️ Partially Configured</span>
                                                <div class="sentinel-partial-details">
                                                    <?php echo $gf_status['events_created']; ?> of
                                                    <?php echo $gf_status['total_events']; ?> events configured.
                                                    <button type="button" class="button button-secondary sentinel-setup-template"
                                                        data-template="gravity-forms">
                                                        Complete Setup
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="button button-primary sentinel-setup-template"
                                                data-template="gravity-forms">
                                                Setup Gravity Forms Events
                                            </button>
                                        <?php endif; ?>
                                        <div class="sentinel-template-status" id="template-status-gravity-forms"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($yoast_seo_active && !$yoast_status['fully_configured']): ?>
                            <!-- Yoast SEO Templates -->
                            <div class="sentinel-template-card">
                                <div class="sentinel-template-header">
                                    <h5>🔍 Yoast SEO Events</h5>
                                    <span class="sentinel-plugin-badge">Plugin Detected</span>
                                </div>
                                <div class="sentinel-template-body">
                                    <p>Track SEO meta updates, score changes, and optimization actions</p>
                                    <ul class="sentinel-template-events">
                                        <li>SEO Meta Updated</li>
                                        <li>SEO Score Changed</li>
                                        <li>Schema Markup Updated</li>
                                        <li>Bulk SEO Action</li>
                                    </ul>
                                    <div class="sentinel-template-actions">
                                        <?php if ($yoast_status['configured']): ?>
                                            <div class="sentinel-template-partial">
                                                <span class="sentinel-partial-badge">⚠️ Partially Configured</span>
                                                <div class="sentinel-partial-details">
                                                    <?php echo $yoast_status['events_created']; ?> of
                                                    <?php echo $yoast_status['total_events']; ?> events configured.
                                                    <button type="button" class="button button-secondary sentinel-setup-template"
                                                        data-template="yoast-seo">
                                                        Complete Setup
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="button button-primary sentinel-setup-template"
                                                data-template="yoast-seo">
                                                Setup Yoast SEO Events
                                            </button>
                                        <?php endif; ?>
                                        <div class="sentinel-template-status" id="template-status-yoast-seo"></div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!$any_plugins_active): ?>
                <div class="sentinel-no-plugins">
                    <div class="sentinel-no-plugins-icon">🔌</div>
                    <h4>No Plugin Integrations Available</h4>
                    <p>Install and activate supported plugins like WooCommerce, Contact Form 7, WPForms, or Gravity Forms to
                        see
                        integration options here.</p>
                </div>
            <?php else: ?>
                <!-- Plugin-Specific Event Controls -->
                <div class="sentinel-plugin-events">
                    <?php
                    $templates = sentinel_get_plugin_templates();
                    $custom_events = get_option('sentinel_custom_events', array());
                    $disabled_events = get_option('sentinel_disabled_events', array());

                    foreach ($templates as $plugin_key => $plugin_config):
                        if (!$plugin_config['plugin_active']) continue;

                        // Check if any events from this plugin exist
                        $plugin_events = array();
                        foreach ($plugin_config['events'] as $event_key => $event_config) {
                            if (isset($custom_events[$event_key])) {
                                $plugin_events[$event_key] = array_merge($event_config, $custom_events[$event_key]);
                            }
                        }

                        if (empty($plugin_events)) continue;
                    ?>
                        <div class="sentinel-plugin-category">
                            <div class="sentinel-plugin-category-header">
                                <h4>
                                    <?php
                                    $icons = array('woocommerce' => '🛒', 'contact-form-7' => '📧', 'gravity-forms' => '📋', 'yoast-seo' => '🔍');
                                    echo isset($icons[$plugin_key]) ? $icons[$plugin_key] : '🔌';
                                    ?>
                                    <?php echo esc_html($plugin_config['name']); ?> Events
                                </h4>
                                <span class="sentinel-event-count"><?php echo count($plugin_events); ?> Events</span>
                            </div>

                            <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>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($plugin_events as $event_key => $event_config):
                                            $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_config['category']); ?>">
                                                        <?php echo esc_html(ucfirst($event_config['category'])); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <span
                                                        class="sentinel-priority sentinel-priority-<?php echo esc_attr($event_config['priority']); ?>">
                                                        <?php echo esc_html(ucfirst($event_config['priority'])); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo esc_html($event_config['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">No activity</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>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if (sentinel_is_premium()): ?>
        <!-- Custom Events Management Section (Premium Only) -->
        <div class="sentinel-settings-card" style="margin-bottom: 30px;">
            <div class="sentinel-settings-card-header">
                <h2 class="sentinel-settings-card-title">
                    <i class="dashicons dashicons-plus-alt"></i>
                    Custom Events Management
                    <?php echo sentinel_get_plan_badge(); ?>
                </h2>
            </div>
            <div class="sentinel-settings-card-content sentinel-custom-events">
                <p style="margin-bottom: 20px;">Create and manage custom events for your specific site monitoring needs.
                    Perfect for tracking unique business logic, custom plugin activities, or specialized user interactions.
                </p>

                <!-- Add New Custom Event Form -->
                <div class="sentinel-custom-events-form">
                    <h4>Add New Custom Event</h4>

                    <div class="sentinel-form-grid">
                        <div class="sentinel-form-group">
                            <label for="custom_event_key">Event Key</label>
                            <input type="text" id="custom_event_key" placeholder="e.g., order_completed" />
                            <small>Unique identifier (letters, numbers, underscores only)</small>
                        </div>

                        <div class="sentinel-form-group">
                            <label for="custom_event_label">Display Name</label>
                            <input type="text" id="custom_event_label" placeholder="e.g., Order Completed" />
                            <small>Human-readable name</small>
                        </div>

                        <div class="sentinel-form-group">
                            <label for="custom_event_category">Category</label>
                            <select id="custom_event_category">
                                <option value="custom">Custom</option>
                                <option value="user">User</option>
                                <option value="system">System</option>
                                <option value="security">Security</option>
                                <option value="content">Content</option>
                                <option value="ecommerce">E-commerce</option>
                            </select>
                        </div>

                        <div class="sentinel-form-group">
                            <label for="custom_event_priority">Priority</label>
                            <select id="custom_event_priority">
                                <option value="low">Low</option>
                                <option value="medium" selected>Medium</option>
                                <option value="high">High</option>
                                <option value="critical">Critical</option>
                            </select>
                        </div>
                    </div>

                    <div class="sentinel-form-group">
                        <label for="custom_event_description">Description</label>
                        <textarea id="custom_event_description" placeholder="Describe what this event tracks..."></textarea>
                        <small>Optional description of this custom event</small>
                    </div>

                    <div class="sentinel-form-actions">
                        <button type="button" id="sentinel-add-custom-event" class="sentinel-add-event-btn">
                            <i class="dashicons dashicons-plus-alt"></i> Add Custom Event
                        </button>
                        <span id="sentinel-add-event-status" class="sentinel-status-message"></span>
                    </div>
                </div>

                <!-- Existing Custom Events -->
                <div class="sentinel-custom-events-list">
                    <h3>Your Custom Events</h3>
                    <div id="sentinel-events-container" class="sentinel-events-container">
                        <!-- Loading message - will be replaced by table -->
                        <p id="sentinel-loading-events" class="sentinel-loading-events">Loading custom events...</p>
                    </div>
                </div>


            </div>
        </div>
    <?php else: ?>
        <!-- Premium Feature Notice for Custom Events -->
        <div class="sentinel-settings-card" style="margin-bottom: 30px;">
            <div class="sentinel-settings-card-header">
                <h2 class="sentinel-settings-card-title">
                    <i class="dashicons dashicons-lock"></i>
                    Custom Events - Sentinel+ Feature
                </h2>
            </div>
            <div class="sentinel-settings-card-content">
                <div class="sentinel-feature-preview">
                    <div class="sentinel-feature-preview-icon">🔒</div>
                    <h3>Sentinel+ Feature</h3>
                    <p>Create and manage custom events for your specific site monitoring needs. Perfect for tracking unique
                        business logic, custom plugin activities, or specialized user interactions.</p>

                    <div class="sentinel-feature-list">
                        <h4>What you'll get:</h4>
                        <ul>
                            <li>
                                <i class="dashicons dashicons-yes-alt"></i>
                                Custom event registration API
                            </li>
                            <li>
                                <i class="dashicons dashicons-yes-alt"></i>
                                Event validation and management
                            </li>
                            <li>
                                <i class="dashicons dashicons-yes-alt"></i>
                                Integration with logging system
                            </li>
                            <li>
                                <i class="dashicons dashicons-yes-alt"></i>
                                Testing and debugging tools
                            </li>
                        </ul>
                    </div>

                    <div style="margin-top: 30px;">
                        <a href="https://buy.stripe.com/3cIdR98A1g3qdKb43C0gw00" class="button button-primary" target="_blank" rel="noopener"
                            style="padding: 12px 30px; font-size: 16px; font-weight: 600;">
                            Upgrade to Sentinel+
                        </a>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <!-- System Events Registry -->
    <div class="sentinel-settings-card">
        <div class="sentinel-settings-card-header">
            <h2 class="sentinel-settings-card-title">
                <i class="dashicons dashicons-admin-generic"></i>
                System Events Registry
            </h2>
        </div>
        <div class="sentinel-settings-card-content">
            <!-- 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 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">
                        <?php
                        // Count disabled system events only (not custom events)
                        $disabled_system_events = array_filter($disabled_events, function ($event_key) {
                            return sentinel_is_default_event($event_key);
                        });
                        $system_enabled_count = count($event_definitions) - count($disabled_system_events);
                        ?>
                        <span class="count"><?php echo $system_enabled_count; ?></span>
                        <span class="label">Enabled</span>
                    </div>
                    <div class="sentinel-summary-stat">
                        <span class="count"><?php echo count($disabled_system_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';
                }
            }

            // AJAX toggle for system events
            document.addEventListener('DOMContentLoaded', function() {
                const toggles = document.querySelectorAll(
                    '.sentinel-toggle-switch input[type="checkbox"]:not(.sentinel-custom-event-toggle)');
                toggles.forEach(toggle => {
                    toggle.addEventListener('change', function() {
                        const checkbox = this;
                        const form = checkbox.form;
                        const eventKey = form.querySelector('input[name="event_key"]').value;
                        const isEnabled = checkbox.checked;
                        const row = checkbox.closest('tr');

                        // Disable checkbox during request
                        checkbox.disabled = true;

                        // Add loading state to row
                        row.classList.add('sentinel-updating');

                        // Make AJAX request
                        fetch(ajaxurl, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded',
                                },
                                body: new URLSearchParams({
                                    action: 'sentinel_toggle_system_event',
                                    event_key: eventKey,
                                    enabled: isEnabled ? 1 : 0,
                                    nonce: document.getElementById(
                                        'sentinel_ajax_nonce').value
                                })
                            })
                            .then(response => response.json())
                            .then(result => {
                                if (!result.success) {
                                    // Revert checkbox on error
                                    checkbox.checked = !isEnabled;
                                    console.error('Error toggling system event:', result.error);
                                } else {
                                    // Update row styling based on enabled state
                                    if (isEnabled) {
                                        row.classList.remove('sentinel-event-disabled');
                                    } else {
                                        row.classList.add('sentinel-event-disabled');
                                    }
                                }

                                // Remove loading state and re-enable
                                row.classList.remove('sentinel-updating');
                                checkbox.disabled = false;
                            })
                            .catch(error => {
                                // Revert checkbox on error
                                checkbox.checked = !isEnabled;

                                // Revert visual state on error
                                if (!isEnabled) {
                                    row.classList.remove('sentinel-event-disabled');
                                } else {
                                    row.classList.add('sentinel-event-disabled');
                                }

                                row.classList.remove('sentinel-updating');
                                checkbox.disabled = false;
                                console.error('Network error toggling system event:', error);
                            });
                    });
                });
            });
        </script>
