<?php

/**
 * Sentinel Logs Page
 */

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

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

// Role-based filtering for editors (only if enabled in settings)
$is_editor = current_user_can('edit_published_posts') && !current_user_can('manage_options');
$settings = get_option('sentinel_log_management', array());
$role_based_access_enabled = !empty($settings['role_based_access']);

// Remove IP whitelist enforcement logic

// Audit log access if enabled
if (!empty($settings['audit_log_access']) && function_exists('sentinel_log_event')) {
    sentinel_log_event(
        'log_accessed',
        array(
            'page' => 'logs',
            'ip' => $_SERVER['REMOTE_ADDR'],
            'query' => $_GET
        ),
        get_current_user_id()
    );
}

// Handle filters
$event_filter = isset($_GET['event_filter']) ? sanitize_text_field($_GET['event_filter']) : '';
$user_filter = isset($_GET['user_filter']) && $_GET['user_filter'] !== '' ? intval($_GET['user_filter']) : '';
$priority_filter = isset($_GET['priority_filter']) ? sanitize_text_field($_GET['priority_filter']) : '';
$ip_filter = isset($_GET['ip_filter']) ? sanitize_text_field($_GET['ip_filter']) : '';
$date_from = isset($_GET['date_from']) ? sanitize_text_field($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? sanitize_text_field($_GET['date_to']) : '';

// Build query
$where_conditions = array();
$query_params = array();

if ($event_filter) {
    $where_conditions[] = 'event_key = %s';
    $query_params[] = $event_filter;
}

if ($user_filter !== '' && $user_filter !== 0) {
    $where_conditions[] = 'user_id = %d';
    $query_params[] = intval($user_filter);
}

if ($priority_filter) {
    $where_conditions[] = 'priority = %s';
    $query_params[] = $priority_filter;
}

if ($ip_filter) {
    $where_conditions[] = 'ip_address LIKE %s';
    $query_params[] = '%' . $wpdb->esc_like($ip_filter) . '%';
}

if ($date_from) {
    $where_conditions[] = 'created_at >= %s';
    $query_params[] = $date_from . ' 00:00:00';
}

if ($date_to) {
    $where_conditions[] = 'created_at <= %s';
    $query_params[] = $date_to . ' 23:59:59';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Add role-based filtering for editors if enabled
if ($is_editor && $role_based_access_enabled) {
    if (!empty($where_conditions)) {
        $where_clause .= ' AND category IN (\'user\', \'content\', \'authentication\')';
    } else {
        $where_clause = 'WHERE category IN (\'user\', \'content\', \'authentication\')';
    }
}

// Pagination
$per_page = 50;
$current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get total count (use separate params array to avoid parameter mismatch)
$count_query = "SELECT COUNT(*) FROM $table $where_clause";
$count_params = $query_params; // Copy the filter parameters



if (!empty($count_params)) {
    $count_query = $wpdb->prepare($count_query, $count_params);
}
$total_logs = $wpdb->get_var($count_query);

$total_pages = ceil($total_logs / $per_page);

// Get logs (add pagination params to the original filter params)
$query = "SELECT * FROM $table $where_clause ORDER BY created_at DESC LIMIT %d OFFSET %d";
$main_query_params = $query_params; // Copy filter parameters
$main_query_params[] = $per_page;   // Add pagination parameters
$main_query_params[] = $offset;

$logs = $wpdb->get_results($wpdb->prepare($query, $main_query_params));

// Get unique event keys for filter
$event_keys = $wpdb->get_col("SELECT DISTINCT event_key FROM $table ORDER BY event_key");

// Get users for filter
$users = $wpdb->get_results("SELECT DISTINCT user_id FROM $table WHERE user_id > 0 ORDER BY user_id");
$usernames = array();
if ($users) {
    $user_ids = wp_list_pluck($users, 'user_id');
    $user_data = $wpdb->get_results("SELECT ID, user_login, display_name FROM {$wpdb->users} WHERE ID IN (" . implode(',', $user_ids) . ")");
    foreach ($user_data as $user) {
        $usernames[$user->ID] = $user->display_name ?: $user->user_login;
    }
}
$usernames[0] = 'Guest/Anonymous';


?>

<div class="wrap sentinel-dashboard">
    <div class="sentinel-logo">
        <div class="sentinel-logo-card">
            <img src="<?php echo plugins_url('assets/img/Logo.png', dirname(__FILE__, 2)); ?>" alt="Sentinel Logo"
                height="80" />
        </div>
    </div>
    <h1 class="sentinel-dashboard-title">Activity Logs</h1>



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

            <div class="sentinel-filter-row">
                <div class="sentinel-filter-group">
                    <label for="event_filter">Event Type:</label>
                    <select name="event_filter" id="event_filter">
                        <option value="">All Events</option>
                        <?php foreach ($event_keys as $event_key): ?>
                        <option value="<?php echo esc_attr($event_key); ?>"
                            <?php selected($event_filter, $event_key); ?>>
                            <?php echo esc_html($event_key); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="sentinel-filter-group">
                    <label for="user_filter">User:</label>
                    <select name="user_filter" id="user_filter">
                        <option value="">All Users</option>
                        <?php foreach ($usernames as $user_id => $username): ?>
                        <option value="<?php echo esc_attr($user_id); ?>" <?php selected($user_filter, $user_id); ?>>
                            <?php echo esc_html($username); ?>
                        </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>
                        <option value="low" <?php selected($priority_filter, 'low'); ?>>Low</option>
                        <option value="medium" <?php selected($priority_filter, 'medium'); ?>>Medium</option>
                        <option value="high" <?php selected($priority_filter, 'high'); ?>>High</option>
                        <option value="critical" <?php selected($priority_filter, 'critical'); ?>>Critical</option>
                    </select>
                </div>

                <?php
                // Only show IP filter if IP logging is enabled AND user is not an editor with role-based access
                $ip_logging_enabled = !empty($settings['log_ip_addresses']);
                if ($ip_logging_enabled && (!$is_editor || !$role_based_access_enabled)): ?>
                <div class="sentinel-filter-group">
                    <label for="ip_filter">IP Address:</label>
                    <input type="text" name="ip_filter" id="ip_filter" value="<?php echo esc_attr($ip_filter); ?>"
                        placeholder="Filter by IP..." class="small-text">
                </div>
                <?php endif; ?>

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

                <div class="sentinel-filter-group">
                    <label for="date_to">Date To:</label>
                    <input type="date" name="date_to" id="date_to" value="<?php echo esc_attr($date_to); ?>">
                </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-logs'); ?>" class="button">Clear Filters</a>
                </div>
            </div>
        </form>
    </div>



    <!-- Results Summary -->
    <div class="sentinel-results-summary">
        <div class="sentinel-summary-card">
            <span class="sentinel-summary-count"><?php echo number_format_i18n($total_logs); ?></span>
            <span class="sentinel-summary-label"><?php echo _n('Activity Log', 'Activity Logs', $total_logs); ?></span>
        </div>
    </div>

    <!-- Logs Grid -->
    <div class="sentinel-logs-grid">
        <?php if ($logs): ?>
        <?php foreach ($logs as $log): ?>
        <div class="sentinel-log-card" data-log-id="<?php echo $log->id; ?>">
            <div class="sentinel-log-header">
                <div class="sentinel-log-icon">
                    <i class="dashicons dashicons-<?php echo sentinel_get_activity_icon($log->event_key); ?>"></i>
                </div>
                <div class="sentinel-log-meta">
                    <div class="sentinel-log-title">
                        <?php echo esc_html(sentinel_format_activity_message($log, $usernames)); ?>
                    </div>
                    <div class="sentinel-log-subtitle">
                        <span class="sentinel-event-key"><?php echo esc_html($log->event_key); ?></span>
                        <span class="sentinel-priority sentinel-priority-<?php echo esc_attr($log->priority); ?>">
                            <?php echo esc_html(ucfirst($log->priority)); ?>
                        </span>
                    </div>
                </div>
                <div class="sentinel-log-actions">
                    <?php if ($log->event_key === 'user_deletion_request'): ?>
                    <?php
                        // Parse the request data to get status
                        $request_data = json_decode($log->data, true);
                        $request_status = isset($request_data['status']) ? $request_data['status'] : 'pending';
                        ?>
                    <?php if ($request_status === 'pending'): ?>
                    <button class="sentinel-btn sentinel-btn-small sentinel-btn-approve"
                        onclick="handleDeletionRequest(<?php echo $log->id; ?>, 'approve')" title="Approve Request">
                        <i class="dashicons dashicons-yes-alt"></i>
                    </button>
                    <button class="sentinel-btn sentinel-btn-small sentinel-btn-deny"
                        onclick="handleDeletionRequest(<?php echo $log->id; ?>, 'deny')" title="Deny Request">
                        <i class="dashicons dashicons-no-alt"></i>
                    </button>
                    <?php else: ?>
                    <span class="sentinel-status-badge sentinel-status-<?php echo esc_attr($request_status); ?>">
                        <?php echo esc_html(ucfirst($request_status)); ?>
                    </span>
                    <?php endif; ?>
                    <?php endif; ?>
                    <button class="sentinel-btn sentinel-btn-small" onclick="toggleLogDetails(<?php echo $log->id; ?>)">
                        <i class="dashicons dashicons-visibility"></i>
                    </button>
                            <?php
                            // PREMIUM: Add "View Changes" button for file monitoring events
                            if (sentinel_is_premium() && $log->event_key === 'file_modified') {
                                $log_data = json_decode($log->data, true);
                                if (is_array($log_data) && isset($log_data['has_diff']) && $log_data['has_diff']) {
                                    $baseline_id = isset($log_data['baseline_id']) ? $log_data['baseline_id'] : '';
                                    $filename = isset($log_data['file_name']) ? $log_data['file_name'] : '';

                                    if (!empty($baseline_id)) {
                            ?>
                                        <button class="sentinel-diff-btn sentinel-btn sentinel-btn-small"
                                            data-baseline-id="<?php echo esc_attr($baseline_id); ?>"
                                            data-filename="<?php echo esc_attr($filename); ?>"
                                            type="button"
                                            title="View file changes">
                                            <i class="dashicons dashicons-editor-code"></i>
                                        </button>
                            <?php
                                    }
                                }
                            }
                            ?>
                </div>
            </div>
            <div class="sentinel-log-info">
                <div class="sentinel-log-info-item">
                    <i class="dashicons dashicons-admin-users"></i>
                    <span><?php echo esc_html(isset($usernames[$log->user_id]) ? $usernames[$log->user_id] : 'Unknown'); ?></span>
                </div>
                <div class="sentinel-log-info-item">
                    <i class="dashicons dashicons-clock"></i>
                    <span><?php echo esc_html(human_time_diff(strtotime($log->created_at), current_time('timestamp')) . ' ago'); ?></span>
                </div>
                <div class="sentinel-log-info-item">
                    <i class="dashicons dashicons-location"></i>
                    <span><?php
                        // Check if IP logging is enabled and if editor should see IPs
                        $ip_logging_enabled = !empty($settings['log_ip_addresses']);

                        if (!$ip_logging_enabled) {
                            echo '<em style="color: #666;">IP logging disabled</em>';
                        } elseif ($is_editor && $role_based_access_enabled) {
                            echo '<em style="color: #666;">IP hidden for editors</em>';
                        } elseif (empty($log->ip_address)) {
                            echo '<em style="color: #999;">No IP recorded</em>';
                        } else {
                            echo esc_html($log->ip_address);
                        }
                    ?></span>
                </div>
            </div>
            <div id="log-details-<?php echo $log->id; ?>" class="sentinel-log-details" style="display: none;">
                <div class="sentinel-log-details-content">
                    <h4>📋 Event Details</h4>
                    <div class="sentinel-detail-grid">
                        <div class="sentinel-detail-column">
                            <div class="sentinel-detail-row">
                                <strong>Event Key:</strong> <?php echo esc_html($log->event_key); ?>
                            </div>
                            <div class="sentinel-detail-row">
                                <strong>Category:</strong> <?php echo esc_html($log->category); ?>
                            </div>
                            <div class="sentinel-detail-row">
                                <strong>URL:</strong> <?php echo esc_html($log->url); ?>
                            </div>
                        </div>
                        <div class="sentinel-detail-column">
                            <div class="sentinel-detail-row">
                                <strong>User Agent:</strong>
                                <?php echo esc_html(substr($log->user_agent, 0, 60)) . (strlen($log->user_agent) > 60 ? '...' : ''); ?>
                            </div>
                            <div class="sentinel-detail-row">
                                <strong>Timestamp:</strong>
                                <?php echo esc_html(date('Y-m-d H:i:s', strtotime($log->created_at))); ?>
                            </div>
                        </div>
                    </div>

                    <?php
                    // Parse and display specific data based on event type
                    $data = (!empty($log->data) && $log->data !== 'null') ? json_decode($log->data, true) : array();
                    if ($data && is_array($data)):

                        // Display specific fields for different event types
                        if ($log->event_key === 'http_404_error' && isset($data['requested_url'])): ?>
                    <div class="sentinel-detail-section">
                        <strong>🔍 404 Error Details:</strong>
                        <div class="sentinel-detail-row">
                            <strong>Requested URL:</strong> <?php echo esc_html($data['requested_url']); ?>
                        </div>
                        <?php if (isset($data['referer'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Referer:</strong> <?php echo esc_html($data['referer']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php elseif ($log->event_key === 'login_failed'): ?>
                    <?php if (isset($data['username'])): ?>
                    <div class="sentinel-detail-section">
                        <strong>🔐 Login Failure Details:</strong>
                        <div class="sentinel-detail-row">
                            <strong>Username:</strong> <?php echo esc_html($data['username']); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php elseif (strpos($log->event_key, 'php_') === 0): ?>
                    <div class="sentinel-detail-section">
                        <strong>⚠️ PHP Error Details:</strong>
                        <?php if (isset($data['error_message'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Error Message:</strong> <?php echo esc_html($data['error_message']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['error_file'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>File:</strong> <?php echo esc_html($data['error_file']); ?>
                            <?php if (isset($data['error_line'])): ?>
                            (Line: <?php echo esc_html($data['error_line']); ?>)
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php elseif ($log->event_key === 'file_upload_error'): ?>
                    <div class="sentinel-detail-section">
                        <strong>📁 File Upload Error Details:</strong>
                        <?php if (isset($data['filename'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Filename:</strong> <?php echo esc_html($data['filename']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['error_message'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Error:</strong> <?php echo esc_html($data['error_message']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php elseif ($log->event_key === 'user_deletion_request'): ?>
                    <div class="sentinel-detail-section">
                        <strong>🔒 Data Deletion Request Details:</strong>
                        <?php if (isset($data['reason'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Reason:</strong> <?php echo esc_html($data['reason']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['details']) && !empty($data['details'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Additional Details:</strong> <?php echo esc_html($data['details']); ?>
                        </div>
                        <?php endif; ?>
                        <div class="sentinel-detail-row">
                            <strong>Status:</strong>
                            <span
                                class="sentinel-status-badge sentinel-status-<?php echo esc_attr($data['status'] ?? 'pending'); ?>">
                                <?php echo esc_html(ucfirst($data['status'] ?? 'pending')); ?>
                            </span>
                        </div>
                        <?php if (isset($data['request_date'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Request Date:</strong> <?php echo esc_html($data['request_date']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['processed_date'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Processed Date:</strong> <?php echo esc_html($data['processed_date']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['processed_by'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Processed By:</strong> <?php echo esc_html($data['processed_by']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if (isset($data['admin_notes'])): ?>
                        <div class="sentinel-detail-row">
                            <strong>Admin Notes:</strong> <?php echo esc_html($data['admin_notes']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <!-- Full Data (Raw) -->
                    <div class="sentinel-detail-section">
                        <strong>📊 Raw Data:</strong>
                        <pre
                            class="sentinel-raw-data"><?php echo esc_html(json_encode($data, JSON_PRETTY_PRINT)); ?></pre>
                    </div>
                    <?php else: ?>
                    <div class="sentinel-detail-section">
                        <strong>📊 Data:</strong>
                        <pre class="sentinel-raw-data"><?php echo esc_html($log->data); ?></pre>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
        <?php else: ?>
        <div class="sentinel-empty-state">
            <div class="sentinel-empty-icon">
                <i class="dashicons dashicons-search"></i>
            </div>
            <h3>No Activity Logs Found</h3>
            <p>No logs match your current filter criteria. Try adjusting your filters or check back later.</p>
        </div>
        <?php endif; ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="sentinel-pagination">
        <?php
        $pagination_links = paginate_links(array(
            'base' => add_query_arg('paged', '%#%'),
            'format' => '',
            'prev_text' => __('← Previous'),
            'next_text' => __('Next →'),
            'total' => $total_pages,
            'current' => $current_page,
            'type' => 'array'
        ));

        if ($pagination_links) {
            echo '<nav class="sentinel-pagination-nav">';
            echo implode('', $pagination_links);
            echo '</nav>';
        }
        ?>
    </div>
    <?php endif; ?>
</div>

<!-- Modal Overlay -->
<div id="sentinel-modal-overlay" class="sentinel-modal-overlay">
    <div class="sentinel-modal">
        <div class="sentinel-modal-header">
            <h3 class="sentinel-modal-title">
                <span class="sentinel-modal-icon" id="modal-icon">⚠️</span>
                <span id="modal-title">Confirm Action</span>
            </h3>
        </div>
        <div class="sentinel-modal-content">
            <div id="modal-message">Are you sure you want to perform this action?</div>
        </div>
        <div class="sentinel-modal-actions">
            <button type="button" class="sentinel-modal-btn sentinel-modal-btn-secondary"
                id="modal-cancel">Cancel</button>
            <button type="button" class="sentinel-modal-btn" id="modal-confirm">Confirm</button>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Modal functionality
    const modal = {
        overlay: $('#sentinel-modal-overlay'),
        title: $('#modal-title'),
        message: $('#modal-message'),
        icon: $('#modal-icon'),
        confirmBtn: $('#modal-confirm'),
        cancelBtn: $('#modal-cancel'),

        show: function(options) {
            this.title.text(options.title || 'Confirm Action');
            this.message.html(options.message || 'Are you sure you want to perform this action?');
            this.icon.html(options.icon || '⚠️');

            // Set button text and classes
            this.confirmBtn.text(options.confirmText || 'Confirm');
            this.cancelBtn.text(options.cancelText || 'Cancel');

            // Reset button states
            this.confirmBtn.prop('disabled', false);
            this.cancelBtn.prop('disabled', false);

            // Set button styles
            this.confirmBtn.removeClass('sentinel-modal-btn-danger sentinel-modal-btn-success');
            if (options.confirmClass) {
                this.confirmBtn.addClass(options.confirmClass);
            }

            // Show/hide cancel button
            this.cancelBtn.show();

            // Store callback
            this.confirmCallback = options.onConfirm;

            // Show modal
            this.overlay.show();
        },

        hide: function() {
            this.overlay.hide();
            this.confirmCallback = null;
            // Reset button states when hiding
            this.confirmBtn.prop('disabled', false);
            this.cancelBtn.prop('disabled', false);
        },

        showLoading: function(message) {
            this.title.text('Processing...');
            this.message.html(`
                <div class="sentinel-modal-loading">
                    <div class="spinner"></div>
                    ${message || 'Please wait while we process your request...'}
                </div>
            `);
            this.confirmBtn.prop('disabled', true);
            this.cancelBtn.prop('disabled', true);
        },

        showSuccess: function(message) {
            this.icon.html('✅');
            this.title.text('Success');
            this.message.html(message);
            this.confirmBtn.text('OK').removeClass(
                'sentinel-modal-btn-danger sentinel-modal-btn-success').addClass(
                'sentinel-modal-btn-success');
            this.confirmBtn.prop('disabled', false);
            this.cancelBtn.hide();
        },

        showError: function(message) {
            this.icon.html('❌');
            this.title.text('Error');
            this.message.html(message);
            this.confirmBtn.text('OK').removeClass(
                'sentinel-modal-btn-danger sentinel-modal-btn-success').addClass(
                'sentinel-modal-btn-danger');
            this.confirmBtn.prop('disabled', false);
            this.cancelBtn.hide();
        }
    };

    // Close modal on overlay click or escape key
    modal.overlay.on('click', function(e) {
        if (e.target === this) {
            modal.hide();
        }
    });

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && modal.overlay.is(':visible')) {
            modal.hide();
        }
    });

    // Cancel button
    modal.cancelBtn.on('click', function() {
        modal.hide();
    });

    // Confirm button
    modal.confirmBtn.on('click', function() {
        if (modal.confirmCallback) {
            modal.confirmCallback();
        } else {
            modal.hide();
        }
    });

    // Toggle log details function
    window.toggleLogDetails = function(logId) {
        const detailsDiv = document.getElementById('log-details-' + logId);
        const card = document.querySelector('[data-log-id="' + logId + '"]');

        if (detailsDiv.style.display === 'none') {
            detailsDiv.style.display = 'block';
            card.classList.add('expanded');
        } else {
            detailsDiv.style.display = 'none';
            card.classList.remove('expanded');
        }
    };

    // Handle deletion requests with modal
    window.handleDeletionRequest = function(logId, action) {
        const actionText = action === 'approve' ? 'approve' : 'deny';
        const actionColor = action === 'approve' ? 'success' : 'danger';

        // Show confirmation modal
        modal.show({
            title: `Confirm ${actionText.charAt(0).toUpperCase() + actionText.slice(1)} Request`,
            message: `
                <div class="sentinel-modal-warning">
                    <div style="display: flex; align-items: flex-start; gap: 8px;">
                        <span class="sentinel-modal-icon">⚠️</span>
                        <div>
                            <strong>Are you sure you want to ${actionText} this data deletion request?</strong><br>
                            ${action === 'approve' ?
                                'This will permanently anonymize the user\'s data in all logs. This action cannot be undone.' :
                                'This will deny the user\'s request for data deletion. The user will be notified.'
                            }
                        </div>
                    </div>
                </div>
            `,
            icon: action === 'approve' ? '✅' : '❌',
            confirmText: action === 'approve' ? 'Approve & Anonymize' : 'Deny Request',
            confirmClass: `sentinel-modal-btn-${actionColor}`,
            onConfirm: function() {
                // Show loading state
                modal.showLoading('Processing your request...');

                // Get admin notes if approving
                let adminNotes = '';
                if (action === 'approve') {
                    // Show notes input modal
                    modal.hide();
                    modal.show({
                        title: 'Add Approval Notes (Optional)',
                        message: `
                            <div class="sentinel-modal-info">
                                <div style="display: flex; align-items: flex-start; gap: 8px;">
                                    <span class="sentinel-modal-icon">📝</span>
                                    <div>
                                        <strong>Add notes about this approval:</strong><br>
                                        This will be logged for audit purposes.
                                    </div>
                                </div>
                            </div>
                            <div style="margin-top: 16px;">
                                <label for="admin-notes" style="display: block; margin-bottom: 8px; font-weight: 500;">Notes:</label>
                                <textarea id="admin-notes" rows="3" style="width: 100%; padding: 8px; border: 1px solid #d1d5db; border-radius: 4px; resize: vertical;" placeholder="Enter any notes about this approval..."></textarea>
                            </div>
                        `,
                        icon: '📝',
                        confirmText: 'Continue with Approval',
                        confirmClass: 'sentinel-modal-btn-success',
                        onConfirm: function() {
                            adminNotes = $('#admin-notes').val();
                            processDeletionRequest(logId, action, adminNotes);
                        }
                    });
                } else {
                    processDeletionRequest(logId, action, adminNotes);
                }
            }
        });
    };

    function processDeletionRequest(logId, action, adminNotes) {
        // Show loading state
        modal.showLoading('Processing your request...');

        // Make AJAX request
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'sentinel_process_deletion_request',
                log_id: logId,
                request_action: action,
                admin_notes: adminNotes,
                nonce: '<?php echo wp_create_nonce('sentinel_process_deletion_request'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    // Show success message
                    modal.showSuccess(`
                        <div class="sentinel-modal-info">
                            <div style="display: flex; align-items: flex-start; gap: 8px;">
                                <span class="sentinel-modal-icon">✅</span>
                                <div>
                                    <strong>Request ${action}d successfully!</strong><br>
                                    ${response.data.message}
                                </div>
                            </div>
                        </div>
                    `);

                    // Set callback to reload page after OK
                    modal.confirmCallback = function() {
                        location.reload();
                    };
                } else {
                    // Show error message
                    modal.showError(`
                        <div class="sentinel-modal-warning">
                            <div style="display: flex; align-items: flex-start; gap: 8px;">
                                <span class="sentinel-modal-icon">❌</span>
                                <div>
                                    <strong>Error occurred:</strong><br>
                                    ${response.data ? response.data.message : 'Unknown error occurred'}
                                </div>
                            </div>
                        </div>
                    `);
                }
            },
            error: function() {
                // Show error message
                modal.showError(`
                    <div class="sentinel-modal-warning">
                        <div style="display: flex; align-items: flex-start; gap: 8px;">
                            <span class="sentinel-modal-icon">❌</span>
                            <div>
                                <strong>Network error occurred.</strong><br>
                                Please check your connection and try again.
                            </div>
                        </div>
                    </div>
                `);
            }
        });
    }
});
</script>
