<?php
/**
 * Security Events View (Partial for Audit Log Tab)
 * 
 * This is the logging analytics view extracted as a partial
 * to be included within the audit log page as a tab.
 *
 * @package VMPFence
 * @since 2.0.0
 * @since 2.1.0 - Network Participation moved to correct position
 */

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

// Detect if we're embedded in Tools page (must match audit-log.php detection)
$in_tools_page = (isset($_GET['page']) && $_GET['page'] === 'vmpfence-tools');

// Get network participation status
$participate_network = VMPFence_Config::get('participate_security_network', 1);

// Ensure tables exist before displaying page
if (class_exists('VMPFence_Logging_Database') && !VMPFence_Logging_Database::tables_exist()) {
    echo '<div class="notice notice-warning"><p><strong>VMPFence Logging:</strong> Database tables are being created. Please refresh the page in a moment.</p></div>';
    VMPFence_Logging_Database::ensure_tables_exist();
    return;
}

// Get logging service instance
$logging_service = VMPFence_Logging_Service::get_instance();

// Handle filter submissions with defaults to show today's events
$today = current_time('Y-m-d');
$filters = array(
    'severity' => isset($_GET['filter_severity']) ? sanitize_text_field($_GET['filter_severity']) : '',
    'category' => isset($_GET['filter_category']) ? sanitize_text_field($_GET['filter_category']) : '',
    'date_from' => isset($_GET['filter_date_from']) ? sanitize_text_field($_GET['filter_date_from']) : $today,
    'date_to' => isset($_GET['filter_date_to']) ? sanitize_text_field($_GET['filter_date_to']) : $today,
    'limit' => isset($_GET['filter_limit']) ? absint($_GET['filter_limit']) : 50,
);



// Get API key
$api_key = VMPFence_Config::get('central_api_key', '');

// Check if API key is configured
$api_configured = !empty($api_key);

// Check API availability by pinging it (with caching to avoid repeated checks)
$api_available = false;
if ($api_configured) {
    $cached_status = get_transient('vmpfence_api_status');
    
    if ($cached_status !== false) {
        $api_available = ($cached_status === 'online');
    } else {
        $api_client = new VMPFence_API_Client();
        $ping_result = $api_client->ping_api_key($api_key);
        
        if (!is_wp_error($ping_result) && isset($ping_result['is_valid']) && $ping_result['is_valid']) {
            $api_available = true;
            set_transient('vmpfence_api_status', 'online', 60);
        } else {
            $api_available = false;
            set_transient('vmpfence_api_status', 'offline', 60);
        }
    }
}

// Generate timeline data from local events (last 7 days)
$timeline_data = array('timeline' => array());
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-{$i} days"));
    $label = date('M j', strtotime($date));
    
    global $wpdb;
    $events_table = $wpdb->prefix . 'vmpfence_api_logs';
    $count = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$events_table} WHERE DATE(created_at) = %s",
        $date
    ));
    
    $timeline_data['timeline'][] = array(
        'date' => $label,
        'count' => $count
    );
}

// Get local analytics from WordPress database (works offline)
$analytics_today = $logging_service->get_dashboard_analytics('today');
$analytics_week = $logging_service->get_dashboard_analytics('week');
$analytics_month = $logging_service->get_dashboard_analytics('month');

// Get database statistics
require_once VMPFENCE_PLUGIN_DIR . 'includes/class-database.php';
$database = new VMPFence_Logging_Database();
$db_stats = $database->get_stats();

$local_analytics = array(
    'total_events' => $analytics_month['total_events'],
    'critical_events' => $analytics_month['critical_events'],
    'events_today' => $analytics_today['total_events'],
    'events_this_week' => $analytics_week['total_events'],
    'unsynced_events' => $db_stats['unsynced_events'],
    'total_events_db' => $db_stats['total_events'],
);

// Set analytics for display
$analytics = $analytics_month;
$display_stats = $local_analytics;

// Get distinct event types from database for filter dropdown (last 30 days)
$events_table = $wpdb->prefix . 'vmpfence_api_logs';
$db_event_stats = $wpdb->get_results(
    "SELECT 
        event_type,
        COUNT(*) as count
    FROM {$events_table}
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY event_type
    ORDER BY count DESC"
);

// Combine with expected event types (always show common categories)
$expected_event_types = array(
    'firewall_block' => 'Firewall Block',
    'firewall_allow' => 'Firewall Allow',
    'xss_detected' => 'XSS Detected',
    'sqli_detected' => 'SQLi Detected',
    'malware_detected' => 'Malware Detected',
    'scan_completed' => 'Scan Completed',
    'ip_blocked' => 'IP Blocked',
    'user_login_success' => 'Login Success',
    'login_failed' => 'Login Failed',
    'plugin_activated' => 'Plugin Activated',
    'plugin_deactivated' => 'Plugin Deactivated',
    'user_registered' => 'User Registered',
    'admin_user_created' => 'Admin User Created',
    'theme_switched' => 'Theme Switched',
    'file_uploaded' => 'File Uploaded',
);

// Build event stats array with counts from database
$event_stats = array();
foreach ($db_event_stats as $stat) {
    $event_stats[$stat->event_type] = (object) array(
        'event_type' => $stat->event_type,
        'count' => $stat->count,
        'display_name' => isset($expected_event_types[$stat->event_type]) 
            ? $expected_event_types[$stat->event_type]
            : ucwords(str_replace('_', ' ', $stat->event_type))
    );
}

// Add expected types with 0 count if not in database
foreach ($expected_event_types as $type => $name) {
    if (!isset($event_stats[$type])) {
        $event_stats[$type] = (object) array(
            'event_type' => $type,
            'count' => 0,
            'display_name' => $name
        );
    }
}

// Fetch filtered events from local database (now always shows today's events by default)
$filtered_events = null;
if (true) {
    $events_table = $wpdb->prefix . 'vmpfence_api_logs';
    
    $where_conditions = array('1=1');
    $query_params = array();
    
    if (!empty($filters['severity'])) {
        $where_conditions[] = 'severity = %s';
        $query_params[] = $filters['severity'];
    }
    
    if (!empty($filters['category'])) {
        $where_conditions[] = 'event_type = %s';
        $query_params[] = $filters['category'];
    }
    
    if (!empty($filters['date_from'])) {
        $where_conditions[] = 'DATE(created_at) >= %s';
        $query_params[] = $filters['date_from'];
    }
    
    if (!empty($filters['date_to'])) {
        $where_conditions[] = 'DATE(created_at) <= %s';
        $query_params[] = $filters['date_to'];
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    $limit = absint($filters['limit']);
    
    if (!empty($query_params)) {
        $query = "SELECT * FROM {$events_table} WHERE {$where_clause} ORDER BY created_at DESC LIMIT {$limit}";
        $prepared_query = $wpdb->prepare($query, $query_params);
    } else {
        $query = "SELECT * FROM {$events_table} WHERE {$where_clause} ORDER BY created_at DESC LIMIT {$limit}";
        $prepared_query = $query;
    }
    
    $events = $wpdb->get_results($prepared_query, ARRAY_A);
    
    $formatted_events = array();
    if ($events) {
        foreach ($events as $event) {
            $formatted_events[] = array(
                'id' => $event['id'],
                'event_type' => $event['event_type'],
                'severity' => $event['severity'],
                'message' => $event['message'],
                'created_at' => $event['created_at'],
                'timestamp' => $event['created_at'],
                'ip_address' => $event['ip_address'],
                'event_data' => !empty($event['metadata']) ? json_decode($event['metadata'], true) : array()
            );
        }
    }
    
    $filtered_events = array(
        'events' => $formatted_events,
        'total' => count($formatted_events),
        'source' => 'local'
    );
}

?>

<div class="vmpfence-security-events-tab">
    
    <?php if (!$api_configured): ?>
        <div class="notice notice-warning">
            <p><strong>API Not Configured:</strong> Please configure your API key in the <a href="<?php echo esc_url(admin_url('admin.php?page=vmpfence-dashboard')); ?>">setup wizard</a> to enable full logging and analytics features.</p>
        </div>
    <?php elseif ($api_configured && !$api_available): ?>
        <div class="notice notice-info">
            <p><strong>Working Offline:</strong> The remote API is currently unavailable. Showing local data only. Remote features (historical analytics, exports) will be available when the API is accessible.</p>
        </div>
    <?php endif; ?>
    
    <!-- Network Participation Notice -->
    <div class="vmpfence-network-notice" style="margin: 20px 0 15px 0; padding: 15px; border-left: 4px solid #2271b1; background: #fff; border-radius: 4px;">
        <h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">
            <span class="dashicons dashicons-shield" style="color: #2271b1;"></span>
            Security Events & Network Participation
        </h3>
        <p style="margin: 10px 0;">
            <?php if ($participate_network): ?>
                <strong style="color: #00a32a;">✅ Network Participation: ENABLED</strong><br>
                Your security events are being shared with the VMP Security Network to help protect all users. 
                This includes login attempts, IP blocks, firewall events, and aggregated analytics (synced every 24 hours).
            <?php else: ?>
                <strong style="color: #d63638;">❌ Network Participation: DISABLED</strong><br>
                Your security events are stored locally only. You are not contributing to or benefiting from the network threat intelligence.
            <?php endif; ?>
        </p>
        <p style="margin: 10px 0; font-size: 13px; color: #666;">
            <strong>Data Shared When Enabled:</strong> Event types, severity levels, timestamps, IP addresses, user agents, and anonymized statistics.<br>
            <strong>Not Shared:</strong> Personal content, passwords, file contents (except during premium YARA scans), or sensitive site configuration.
        </p>
        <a href="<?php echo admin_url('admin.php?page=vmpfence-firewall&view=options#participate_security_network'); ?>" 
           class="button button-primary" style="margin-top: 5px;">
            <span class="dashicons dashicons-admin-settings" style="margin-top: 3px;"></span>
            Manage Network Participation Settings
        </a>
    </div>
    
    <!-- Stats Overview -->
    <div class="vmpfence-stats-grid">
        <div class="stat-box">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['total_events'] ?? 0)); ?></div>
                <div class="stat-label">Total Events <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box critical">
            <div class="stat-icon">🚨</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['critical_events'] ?? 0)); ?></div>
                <div class="stat-label">Critical Events <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box warning">
            <div class="stat-icon">⚠️</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['events_today'] ?? 0)); ?></div>
                <div class="stat-label">Events Today <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box success">
            <div class="stat-icon">✅</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['events_this_week'] ?? 0)); ?></div>
                <div class="stat-label">Events This Week <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
    </div>

    <!-- Event Timeline Chart -->
    <?php if (!empty($timeline_data['timeline'])): ?>
    <div class="vmpfence-section">
        <h2>Event Timeline (Last 7 Days)</h2>
        <div class="timeline-chart">
            <canvas id="security-timeline-chart"></canvas>
        </div>
    </div>
    <?php endif; ?>

    <!-- Severity Breakdown -->
    <?php if (isset($analytics['events_by_severity'])): ?>
    <div class="vmpfence-section">
        <h2>Severity Breakdown</h2>
        <div class="severity-bars">
            <?php 
            $analytics_total = isset($analytics['total_events']) && $analytics['total_events'] > 0 
                ? $analytics['total_events'] 
                : array_sum($analytics['events_by_severity']);
            ?>
            <?php foreach ($analytics['events_by_severity'] as $severity => $count): ?>
                <?php 
                $percentage = $analytics_total > 0 ? ($count / $analytics_total) * 100 : 0;
                $severity_class = strtolower($severity);
                ?>
                <div class="severity-row">
                    <span class="severity-label <?php echo esc_attr($severity_class); ?>">
                        <?php echo esc_html(ucfirst($severity)); ?>
                    </span>
                    <div class="severity-bar-container">
                        <div class="severity-bar <?php echo esc_attr($severity_class); ?>" 
                             style="width: <?php echo esc_attr($percentage); ?>%"></div>
                    </div>
                    <span class="severity-count"><?php echo esc_html(number_format($count)); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Event Filters -->
    <div class="vmpfence-section">
        <h2>Event Filters</h2>
        <form method="get" class="event-filters">
            <?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="security">
            <?php else: ?>
                <input type="hidden" name="page" value="vmpfence-audit-log">
                <input type="hidden" name="tab" value="security">
            <?php endif; ?>
            
            <div class="filter-row">
                <label>
                    Severity:
                    <select name="filter_severity">
                        <option value="">All</option>
                        <option value="critical" <?php selected($filters['severity'], 'critical'); ?>>Critical</option>
                        <option value="error" <?php selected($filters['severity'], 'error'); ?>>Error</option>
                        <option value="warning" <?php selected($filters['severity'], 'warning'); ?>>Warning</option>
                        <option value="info" <?php selected($filters['severity'], 'info'); ?>>Info</option>
                    </select>
                </label>
                
                <label>
                    Category:
                    <select name="filter_category">
                        <option value=""><?php _e('All Categories', 'vmpfence-security'); ?></option>
                        <?php if (!empty($event_stats)): ?>
                            <?php foreach ($event_stats as $stat): ?>
                                <option value="<?php echo esc_attr($stat->event_type); ?>" <?php selected($filters['category'], $stat->event_type); ?>>
                                    <?php echo esc_html($stat->display_name); ?> (<?php echo esc_html($stat->count); ?>)
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </label>
                
                <label>
                    Date From:
                    <input type="date" name="filter_date_from" value="<?php echo esc_attr($filters['date_from']); ?>">
                </label>
                
                <label>
                    Date To:
                    <input type="date" name="filter_date_to" value="<?php echo esc_attr($filters['date_to']); ?>">
                </label>
                
                <label>
                    Limit:
                    <select name="filter_limit">
                        <option value="25" <?php selected($filters['limit'], 25); ?>>25</option>
                        <option value="50" <?php selected($filters['limit'], 50); ?>>50</option>
                        <option value="100" <?php selected($filters['limit'], 100); ?>>100</option>
                        <option value="250" <?php selected($filters['limit'], 250); ?>>250</option>
                    </select>
                </label>
                
                <button type="submit" class="button button-primary">Apply Filters</button>
                <?php 
                $reset_url = $in_tools_page 
                    ? admin_url('admin.php?page=vmpfence-tools&tab=audit-log&audit_subtab=security') 
                    : admin_url('admin.php?page=vmpfence-audit-log&tab=security');
                ?>
                <a href="<?php echo esc_url($reset_url); ?>" class="button">Reset</a>
            </div>
        </form>
        
        <?php if (isset($filtered_events) && !empty($filtered_events['events'])): ?>
            <div style="margin-top: 20px;">
                <h3>Filtered Results (<?php echo count($filtered_events['events']); ?> events)</h3>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th>Timestamp</th>
                            <th>Severity</th>
                            <th>Category</th>
                            <th>Message</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($filtered_events['events'] as $event): 
                            $category = $event['event_type'] ?? 'N/A';
                            
                            $message = '';
                            if (!empty($event['event_data'])) {
                                if (isset($event['event_data']['message'])) {
                                    $message = $event['event_data']['message'];
                                } elseif (isset($event['event_data']['rule_description'])) {
                                    $message = $event['event_data']['rule_description'];
                                } elseif (isset($event['event_data']['url'])) {
                                    $message = 'Request: ' . $event['event_data']['url'];
                                } elseif (isset($event['event_data']['ip'])) {
                                    $message = 'IP: ' . $event['event_data']['ip'];
                                } else {
                                    $first_key = array_key_first($event['event_data']);
                                    if ($first_key) {
                                        $first_value = $event['event_data'][$first_key];
                                        if (is_string($first_value) && strlen($first_value) < 100) {
                                            $message = ucfirst($first_key) . ': ' . $first_value;
                                        } else {
                                            $message = count($event['event_data']) . ' data fields';
                                        }
                                    }
                                }
                            }
                            
                            $metadata = $event['event_data'] ?? array();
                        ?>
                            <tr>
                                <td><?php echo esc_html(date('Y-m-d H:i:s', strtotime($event['timestamp'] ?? $event['created_at'] ?? ''))); ?></td>
                                <td>
                                    <span class="severity-badge <?php echo esc_attr(strtolower($event['severity'] ?? 'info')); ?>">
                                        <?php echo esc_html(ucfirst($event['severity'] ?? 'info')); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html(ucfirst(str_replace('_', ' ', $category))); ?></td>
                                <td><?php echo esc_html($message); ?></td>
                                <td>
                                    <?php if (!empty($metadata)): ?>
                                        <button type="button" class="button button-small view-event-details" 
                                                data-details="<?php echo esc_attr(wp_json_encode($metadata)); ?>">
                                            View Details
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php elseif (!empty($filters['severity']) || !empty($filters['category']) || !empty($filters['date_from']) || !empty($filters['date_to'])): ?>
            <div style="margin-top: 20px;">
                <p class="description">No events found matching your filters. Try adjusting the filter criteria.</p>
            </div>
        <?php endif; ?>
    </div>

</div>

<!-- Event Details Modal -->
<div id="event-details-modal" class="vmpfence-modal" style="display: none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Security Event Details</h2>
        <pre id="event-details-content"></pre>
    </div>
</div>

<style>
.vmpfence-modal {
    position: fixed;
    z-index: 100000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.vmpfence-modal .modal-content {
    background-color: #fff;
    margin: 5% auto;
    padding: 20px;
    border: 1px solid #888;
    border-radius: 8px;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    overflow-y: auto;
}

.vmpfence-modal .close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.vmpfence-modal .close:hover,
.vmpfence-modal .close:focus {
    color: #000;
}

#event-details-content {
    background: #f5f5f5;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    font-family: monospace;
    font-size: 12px;
    white-space: pre-wrap;
}
</style>

<!-- Chart.js Library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

<script>
jQuery(document).ready(function($) {
    // View details modal for security events
    $('.view-event-details').on('click', function(e) {
        e.stopPropagation();
        var details = $(this).data('details');
        $('#event-details-content').text(JSON.stringify(details, null, 2));
        $('#event-details-modal').show();
    });

    $('.close').on('click', function() {
        $('#event-details-modal').hide();
    });

    $(window).on('click', function(event) {
        if (event.target.id === 'event-details-modal') {
            $('#event-details-modal').hide();
        }
    });
    
    <?php if (!empty($timeline_data['timeline'])): ?>
    setTimeout(function() {
        var canvas = document.getElementById('security-timeline-chart');
        if (canvas && typeof Chart !== 'undefined') {
            var timelineData = <?php echo wp_json_encode($timeline_data['timeline']); ?>;
            
            var chartData = {
                labels: timelineData.map(function(d) { return d.date; }),
                datasets: [{
                    label: 'Security Events',
                    data: timelineData.map(function(d) { return d.count || 0; }),
                    backgroundColor: '#191970',
                    borderColor: '#191970',
                    borderWidth: 2,
                    borderRadius: 8,
                    hoverBackgroundColor: '#2A2669',
                    hoverBorderColor: '#2A2669'
                }]
            };
            
            var chartConfig = {
                type: 'bar',
                data: chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    aspectRatio: 2.5,
                    layout: {
                        padding: 0
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            enabled: true,
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(25, 25, 112, 0.95)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            titleFont: {
                                family: 'Inter, sans-serif',
                                size: 14,
                                weight: 600
                            },
                            bodyFont: {
                                family: 'Inter, sans-serif',
                                size: 13
                            },
                            padding: 12,
                            cornerRadius: 8,
                            displayColors: false,
                            callbacks: {
                                label: function(context) {
                                    return context.parsed.y + ' event' + (context.parsed.y !== 1 ? 's' : '');
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0,
                                font: {
                                    family: 'Inter, sans-serif',
                                    size: 12
                                },
                                color: '#646970'
                            },
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)',
                                drawBorder: false
                            }
                        },
                        x: {
                            ticks: {
                                font: {
                                    family: 'Inter, sans-serif',
                                    size: 12,
                                    weight: 500
                                },
                                color: '#1d2327'
                            },
                            grid: {
                                display: false,
                                drawBorder: false
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            };
            
            try {
                new Chart(canvas, chartConfig);
            } catch(e) {
                console.error('Chart.js error:', e);
            }
        } else {
            console.error('Canvas element or Chart.js not found');
        }
    }, 500);
    <?php endif; ?>
});
</script>
