<?php

/**
 * Sentinel Incidents Page
 *
 * Management interface for security incidents.
 */

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

// Check if user has permission
if (!current_user_can('manage_options')) {
    wp_die(__('You do not have sufficient permissions to access this page.'));
}

// Check if premium is active
if (!sentinel_is_premium()) {
    wp_die(__('This feature requires Sentinel+ Premium.'));
}

// Handle actions
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
$incident_id = isset($_GET['incident_id']) ? intval($_GET['incident_id']) : 0;

if ($action && $incident_id) {
    if (wp_verify_nonce($_GET['_wpnonce'] ?? '', $action . '_' . $incident_id)) {
        switch ($action) {
            case 'resolve':
                if (Sentinel_Incidents::resolve_incident($incident_id)) {
                    echo '<div class="notice notice-success is-dismissible"><p>✅ Incident resolved successfully.</p></div>';
                } else {
                    echo '<div class="notice notice-error is-dismissible"><p>❌ Failed to resolve incident.</p></div>';
                }
                break;
            case 'trust_ip':
                $incident = Sentinel_Incidents::get_incident_by_id($incident_id);
                if ($incident) {
                    $ip = inet_ntop($incident['ip']);
                    sentinel_mark_ip_trusted($ip, 86400); // 24 hours
                    echo '<div class="notice notice-success is-dismissible"><p>✅ IP ' . esc_html($ip) . ' trusted for 24 hours. This IP will not trigger new incidents.</p></div>';
                } else {
                    echo '<div class="notice notice-error is-dismissible"><p>❌ Incident not found.</p></div>';
                }
                break;
        }
    } else {
        echo '<div class="notice notice-error is-dismissible"><p>❌ Security verification failed. Please try again.</p></div>';
    }
}

// Get filter parameters
$status_filter = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';
$type_filter = isset($_GET['type_filter']) ? sanitize_text_field($_GET['type_filter']) : '';
$confidence_filter = isset($_GET['confidence_filter']) ? sanitize_text_field($_GET['confidence_filter']) : '';
$search_filter = isset($_GET['search_filter']) ? sanitize_text_field($_GET['search_filter']) : '';

// Build filter args
$filter_args = array();
if ($status_filter) $filter_args['status'] = $status_filter;
if ($type_filter) $filter_args['type'] = $type_filter;
if ($confidence_filter) $filter_args['confidence'] = $confidence_filter;
if ($search_filter) $filter_args['search'] = $search_filter;

// Get incidents data
$incidents = Sentinel_Incidents::get_incidents_list($filter_args, 50);
$stats = Sentinel_Incidents::get_incident_stats(30); // Last 30 days

// Calculate additional stats that aren't in the main stats method
$all_incidents = Sentinel_Incidents::get_incidents_list(array(), 1000);
$stats['total_incidents_30d'] = $stats['recent_incidents']; // Use the correct key
$stats['unique_ips'] = count(array_unique(array_column($all_incidents, 'ip')));
$stats['high_confidence_incidents'] = count(array_filter($all_incidents, function ($i) {
    return $i['confidence'] === 'high';
}));

// Get unique values for filters
$types = array_unique(array_column($all_incidents, 'type'));
$confidences = array('low', 'medium', 'high');

// Add AJAX nonce for incident details
$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">Incidents</h1>
    <p>Monitor and manage security incidents detected by Sentinel+. Track authentication attacks, brute force attempts, and suspicious activity patterns.</p>

    <div class="notice notice-info">
        <p><strong>🛡️ Security Monitoring:</strong> Incidents are automatically detected based on authentication patterns and suspicious behavior. Open incidents require attention, while resolved incidents are for historical reference.</p>
    </div>

    <!-- Incident Statistics Overview -->
    <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-chart-bar"></i>
                Incident Statistics (Last 30 Days)
            </h2>
        </div>
        <div class="sentinel-settings-card-content">
            <div class="sentinel-summary-stats">
                <div class="sentinel-summary-stat">
                    <span class="count"><?php echo esc_html($stats['open_incidents']); ?></span>
                    <span class="label">Open Incidents</span>
                    <?php if ($stats['open_incidents'] > 0): ?>
                        <span class="stat-alert">⚠️</span>
                    <?php else: ?>
                        <span class="stat-good">✅</span>
                    <?php endif; ?>
                </div>

                <div class="sentinel-summary-stat">
                    <span class="count"><?php echo esc_html($stats['total_incidents_30d']); ?></span>
                    <span class="label">Total Incidents</span>
                </div>

                <div class="sentinel-summary-stat">
                    <span class="count"><?php echo esc_html($stats['high_confidence_incidents']); ?></span>
                    <span class="label">High Confidence</span>
                </div>

                <div class="sentinel-summary-stat">
                    <span class="count"><?php echo esc_html($stats['unique_ips']); ?></span>
                    <span class="label">Unique IPs</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Incidents Management -->
    <div class="sentinel-settings-card">
        <div class="sentinel-settings-card-header">
            <h2 class="sentinel-settings-card-title">
                <i class="dashicons dashicons-shield"></i>
                Incident Management
            </h2>
        </div>
        <div class="sentinel-settings-card-content">
            <!-- Filters -->
            <div class="sentinel-filters">
                <form method="get" action="">
                    <input type="hidden" name="page" value="sentinel-incidents">

                    <div class="sentinel-filter-row">
                        <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="open" <?php selected($status_filter, 'open'); ?>>Open</option>
                                <option value="resolved" <?php selected($status_filter, 'resolved'); ?>>Resolved</option>
                            </select>
                        </div>

                        <div class="sentinel-filter-group">
                            <label for="type_filter">Type:</label>
                            <select name="type_filter" id="type_filter">
                                <option value="">All Types</option>
                                <?php foreach ($types as $type): ?>
                                    <option value="<?php echo esc_attr($type); ?>" <?php selected($type_filter, $type); ?>>
                                        <?php echo esc_html(ucfirst(str_replace('security.', '', $type))); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="sentinel-filter-group">
                            <label for="confidence_filter">Confidence:</label>
                            <select name="confidence_filter" id="confidence_filter">
                                <option value="">All Confidence Levels</option>
                                <?php foreach ($confidences as $confidence): ?>
                                    <option value="<?php echo esc_attr($confidence); ?>" <?php selected($confidence_filter, $confidence); ?>>
                                        <?php echo esc_html(ucfirst($confidence)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </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 IP addresses...">
                        </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-incidents'); ?>" 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($all_incidents); ?></span>
                        <span class="label">Total Incidents</span>
                    </div>
                    <div class="sentinel-summary-stat">
                        <span class="count"><?php echo count(array_filter($all_incidents, function ($i) {
                                                return $i['status'] === 'open';
                                            })); ?></span>
                        <span class="label">Open</span>
                    </div>
                    <div class="sentinel-summary-stat">
                        <span class="count"><?php echo count(array_filter($all_incidents, function ($i) {
                                                return $i['status'] === 'resolved';
                                            })); ?></span>
                        <span class="label">Resolved</span>
                    </div>
                    <div class="sentinel-summary-stat">
                        <span class="count"><?php echo count($incidents); ?></span>
                        <span class="label">Filtered Results</span>
                    </div>
                </div>
            </div>

            <!-- Incidents Table -->
            <div class="sentinel-events-table">
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Confidence</th>
                            <th>IP Address</th>
                            <th>Username</th>
                            <th>Source</th>
                            <th>Count</th>
                            <th>First Seen</th>
                            <th>Last Seen</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($incidents): ?>
                            <?php foreach ($incidents as $incident): ?>
                                <tr class="<?php echo $incident['status'] === 'resolved' ? 'sentinel-event-disabled' : ''; ?>">
                                    <td><?php echo esc_html($incident['id']); ?></td>
                                    <td>
                                        <span class="sentinel-category sentinel-category-security incident-type type-<?php echo esc_attr(str_replace('security.', '', $incident['type'])); ?>">
                                            <?php echo esc_html(ucfirst(str_replace('security.', '', $incident['type']))); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="sentinel-priority incident-status status-<?php echo esc_attr($incident['status']); ?>">
                                            <?php echo esc_html(ucfirst($incident['status'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="incident-confidence confidence-<?php echo esc_attr($incident['confidence']); ?>">
                                            <?php echo esc_html(ucfirst($incident['confidence'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <code class="sentinel-event-key incident-ip"><?php echo esc_html(inet_ntop($incident['ip'])); ?></code>
                                    </td>
                                    <td><?php echo esc_html($incident['username'] ?: '—'); ?></td>
                                    <td><?php echo esc_html($incident['source'] ?: '—'); ?></td>
                                    <td>
                                        <span class="sentinel-usage-count"><?php echo number_format($incident['count']); ?></span>
                                    </td>
                                    <td>
                                        <span class="sentinel-last-triggered">
                                            <?php echo esc_html(human_time_diff(strtotime($incident['first_seen'])) . ' ago'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="sentinel-last-triggered">
                                            <?php echo esc_html(human_time_diff(strtotime($incident['last_seen'])) . ' ago'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($incident['status'] === 'open'): ?>
                                            <div class="incident-actions">
                                                <button type="button" class="actions-dropdown-toggle" data-incident-id="<?php echo esc_attr($incident['id']); ?>">
                                                    Actions <span class="dashicons dashicons-arrow-down-alt2"></span>
                                                </button>
                                                <div class="actions-dropdown-menu">
                                                    <a href="<?php echo esc_url(wp_nonce_url(
                                                                    admin_url('admin.php?page=sentinel-incidents&action=resolve&incident_id=' . $incident['id']),
                                                                    'resolve_' . $incident['id']
                                                                )); ?>" class="dropdown-item danger">
                                                        Resolve Incident
                                                    </a>
                                                    <a href="<?php echo esc_url(wp_nonce_url(
                                                                    admin_url('admin.php?page=sentinel-incidents&action=trust_ip&incident_id=' . $incident['id']),
                                                                    'trust_ip_' . $incident['id']
                                                                )); ?>" class="dropdown-item">
                                                        Trust IP (24h)
                                                    </a>
                                                    <button type="button" class="dropdown-item view-details" data-incident-id="<?php echo esc_attr($incident['id']); ?>">
                                                        View Details
                                                    </button>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <button type="button" class="view-details" data-incident-id="<?php echo esc_attr($incident['id']); ?>" style="background: #0073aa; color: white; border: none; padding: 4px 8px; font-size: 12px; border-radius: 3px; cursor: pointer;">
                                                View Details
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <tr id="incident-details-<?php echo esc_attr($incident['id']); ?>" style="display: none;">
                                    <td colspan="11">
                                        <div class="sentinel-event-details">
                                            <h4>Incident Details: #<?php echo esc_html($incident['id']); ?></h4>

                                            <div class="sentinel-detail-grid">
                                                <div class="sentinel-detail-column">
                                                    <div class="sentinel-detail-row">
                                                        <strong>Incident ID:</strong>
                                                        <code><?php echo esc_html($incident['id']); ?></code>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Type:</strong>
                                                        <span class="sentinel-category sentinel-category-security">
                                                            <?php echo esc_html(ucfirst(str_replace('security.', '', $incident['type']))); ?>
                                                        </span>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Status:</strong>
                                                        <span class="incident-status status-<?php echo esc_attr($incident['status']); ?>">
                                                            <?php echo esc_html(ucfirst($incident['status'])); ?>
                                                        </span>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Confidence:</strong>
                                                        <span class="incident-confidence confidence-<?php echo esc_attr($incident['confidence']); ?>">
                                                            <?php echo esc_html(ucfirst($incident['confidence'])); ?>
                                                        </span>
                                                    </div>
                                                </div>

                                                <div class="sentinel-detail-column">
                                                    <div class="sentinel-detail-row">
                                                        <strong>IP Address:</strong>
                                                        <code><?php echo esc_html(inet_ntop($incident['ip'])); ?></code>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Username:</strong>
                                                        <?php echo esc_html($incident['username'] ?: 'N/A'); ?>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Source:</strong>
                                                        <?php echo esc_html($incident['source'] ?: 'N/A'); ?>
                                                    </div>
                                                    <div class="sentinel-detail-row">
                                                        <strong>Attempt Count:</strong>
                                                        <?php echo number_format($incident['count']); ?>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="sentinel-detail-row">
                                                <strong>Time Range:</strong>
                                                First seen: <?php echo esc_html(date('Y-m-d H:i:s', strtotime($incident['first_seen']))); ?> |
                                                Last seen: <?php echo esc_html(date('Y-m-d H:i:s', strtotime($incident['last_seen']))); ?>
                                            </div>

                                            <?php if ($incident['meta']): ?>
                                                <div class="sentinel-detail-row">
                                                    <strong>Additional Data:</strong>
                                                    <pre style="background: #f8f9fa; padding: 10px; border-radius: 4px; font-size: 12px; overflow-x: auto;"><?php echo esc_html(json_encode(json_decode($incident['meta']), JSON_PRETTY_PRINT)); ?></pre>
                                                </div>
                                            <?php endif; ?>

                                            <div class="sentinel-detail-row">
                                                <strong>Actions:</strong>
                                                <a href="<?php echo admin_url('admin.php?page=sentinel-logs&ip_filter=' . urlencode(inet_ntop($incident['ip']))); ?>" class="button button-small">
                                                    View Related Logs
                                                </a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="11">
                                    <div style="text-align: center; padding: 40px; color: #666;">
                                        <?php if ($filter_args): ?>
                                            <p>No incidents found matching your criteria.</p>
                                            <a href="<?php echo admin_url('admin.php?page=sentinel-incidents'); ?>" class="button">Clear Filters</a>
                                        <?php else: ?>
                                            <p>🎉 No incidents detected yet. Your site is secure!</p>
                                            <p><small>Incidents will appear here when Sentinel+ detects suspicious authentication patterns.</small></p>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    jQuery(document).ready(function($) {
        // Simple dropdown toggle
        $(document).on('click', '.actions-dropdown-toggle', function(e) {
            e.stopPropagation();
            var $dropdown = $(this).siblings('.actions-dropdown-menu');

            // Close all other dropdowns
            $('.actions-dropdown-menu').not($dropdown).removeClass('show');

            // Toggle current dropdown
            $dropdown.toggleClass('show');
        });

        // Close dropdowns when clicking outside
        $(document).on('click', function() {
            $('.actions-dropdown-menu').removeClass('show');
        });

        // Handle view details toggle (same as events page)
        $('.view-details').on('click', function(e) {
            e.preventDefault();
            var incidentId = $(this).data('incident-id');
            var detailsRow = $('#incident-details-' + incidentId);

            if (detailsRow.is(':visible')) {
                detailsRow.hide();
            } else {
                // Hide other open details
                $('[id^="incident-details-"]').hide();
                detailsRow.show();
            }

            // Close all dropdowns when details are toggled
            $('.actions-dropdown-menu').removeClass('show');
        });

        // Prevent dropdown menu clicks from closing the dropdown
        $('.actions-dropdown-menu').on('click', function(e) {
            e.stopPropagation();
        });
    });
</script>
