<?php
defined('ABSPATH') || exit;

/**
 * Get firewall debug logs
 * This endpoint returns detailed information about blocked requests
 */
function wpsec_firewall_debug_logs_endpoint($request) {
    // Verify user has admin privileges
    if (!current_user_can('manage_options')) {
        return new WP_Error(
            'permission_error',
            'You do not have permission to access debug logs',
            array('status' => 403)
        );
    }
    
    // Get all debug log keys
    $log_keys = get_option('wpsec_firewall_debug_logs', array());
    $logs = array();
    
    // Retrieve each log from transients
    foreach ($log_keys as $key) {
        $log_data = get_transient($key);
        if ($log_data) {
            $logs[] = array(
                'key' => $key,
                'data' => $log_data
            );
        }
    }
    
    // Sort logs by timestamp (newest first)
    usort($logs, function($a, $b) {
        return strtotime($b['data']['timestamp']) - strtotime($a['data']['timestamp']);
    });
    
    return rest_ensure_response([
        'success' => true,
        'count' => count($logs),
        'logs' => $logs
    ]);
}

/**
 * Clear all firewall debug logs
 */
function wpsec_firewall_debug_clear_endpoint($request) {
    // Verify user has admin privileges
    if (!current_user_can('manage_options')) {
        return new WP_Error(
            'permission_error',
            'You do not have permission to clear debug logs',
            array('status' => 403)
        );
    }
    
    // Get all debug log keys
    $log_keys = get_option('wpsec_firewall_debug_logs', array());
    
    // Delete each log transient
    foreach ($log_keys as $key) {
        delete_transient($key);
    }
    
    // Clear the log keys
    update_option('wpsec_firewall_debug_logs', array());
    
    return rest_ensure_response([
        'success' => true,
        'message' => 'All debug logs cleared successfully'
    ]);
}

// Register endpoints
add_action('rest_api_init', function () {
    register_rest_route('wpsec/v1', '/firewall/debug-logs', [
        'methods' => 'GET',
        'callback' => 'wpsec_firewall_debug_logs_endpoint',
        'permission_callback' => '__return_true'
    ]);
    
    register_rest_route('wpsec/v1', '/firewall/debug-logs/clear', [
        'methods' => 'POST',
        'callback' => 'wpsec_firewall_debug_clear_endpoint',
        'permission_callback' => '__return_true'
    ]);
});

// Add admin page for viewing debug logs
add_action('admin_menu', function() {
    add_submenu_page(
        'tools.php',                 // Parent slug
        'WPFort Firewall Debug',     // Page title
        'WPFort Debug Logs',         // Menu title
        'manage_options',            // Capability
        'wpsec-firewall-debug',      // Menu slug
        'wpsec_render_firewall_debug_page' // Callback function
    );
});

/**
 * Render the firewall debug page
 */
function wpsec_render_firewall_debug_page() {
    ?>
    <div class="wrap">
        <h1>WPFort Firewall Debug Logs</h1>
        <p>This page shows detailed information about requests that were blocked by the WPFort firewall.</p>
        
        <div id="wpsec-debug-logs-container">
            <div class="wpsec-loading">Loading logs...</div>
        </div>
        
        <button id="wpsec-clear-logs" class="button button-secondary">Clear All Logs</button>
        
        <script>
            jQuery(document).ready(function($) {
                // Function to load logs
                function loadDebugLogs() {
                    $('#wpsec-debug-logs-container').html('<div class="wpsec-loading">Loading logs...</div>');
                    
                    $.ajax({
                        url: '<?php echo esc_url(rest_url('wpsec/v1/firewall/debug-logs')); ?>',
                        method: 'GET',
                        beforeSend: function(xhr) {
                            xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>');
                        },
                        success: function(response) {
                            if (response.success && response.logs.length > 0) {
                                var html = '<div class="wpsec-logs-count">Found ' + response.count + ' log entries</div>';
                                html += '<div class="wpsec-logs-table-container">';
                                html += '<table class="wp-list-table widefat fixed striped">';
                                html += '<thead><tr>';
                                html += '<th>Time</th>';
                                html += '<th>User</th>';
                                html += '<th>IP</th>';
                                html += '<th>URL</th>';
                                html += '<th>Rule Triggered</th>';
                                html += '<th>Actions</th>';
                                html += '</tr></thead>';
                                html += '<tbody>';
                                
                                response.logs.forEach(function(log) {
                                    var data = log.data;
                                    var rule = data.matched_rules && data.matched_rules.length > 0 ? 
                                        data.matched_rules[0].rule + ': ' + data.matched_rules[0].description : 'Unknown';
                                    
                                    html += '<tr>';
                                    html += '<td>' + data.timestamp + '</td>';
                                    html += '<td>' + (data.user_id > 0 ? 'ID: ' + data.user_id : 'Not logged in') + '</td>';
                                    html += '<td>' + data.ip_address + '</td>';
                                    html += '<td>' + data.request_uri + '</td>';
                                    html += '<td>' + rule + '</td>';
                                    html += '<td><button class="button button-small wpsec-view-details" data-log-key="' + log.key + '">View Details</button></td>';
                                    html += '</tr>';
                                });
                                
                                html += '</tbody></table></div>';
                                
                                // Add modal for detailed view
                                html += '<div id="wpsec-log-details-modal" style="display:none;"></div>';
                                
                                $('#wpsec-debug-logs-container').html(html);
                                
                                // Initialize details buttons
                                $('.wpsec-view-details').click(function() {
                                    var logKey = $(this).data('log-key');
                                    var logData = null;
                                    
                                    // Find the log data
                                    response.logs.forEach(function(log) {
                                        if (log.key === logKey) {
                                            logData = log.data;
                                        }
                                    });
                                    
                                    if (logData) {
                                        showLogDetails(logData);
                                    }
                                });
                            } else {
                                $('#wpsec-debug-logs-container').html('<div class="notice notice-info"><p>No debug logs found.</p></div>');
                            }
                        },
                        error: function() {
                            $('#wpsec-debug-logs-container').html('<div class="notice notice-error"><p>Error loading debug logs.</p></div>');
                        }
                    });
                }
                
                // Function to show detailed log information
                function showLogDetails(logData) {
                    var html = '<div class="wpsec-modal-content">';
                    html += '<span class="wpsec-modal-close">&times;</span>';
                    html += '<h2>Detailed Block Information</h2>';
                    
                    // Basic information
                    html += '<h3>Request Information</h3>';
                    html += '<table class="wp-list-table widefat fixed">';
                    html += '<tr><th>Time</th><td>' + logData.timestamp + '</td></tr>';
                    html += '<tr><th>IP Address</th><td>' + logData.ip_address + '</td></tr>';
                    html += '<tr><th>User ID</th><td>' + logData.user_id + '</td></tr>';
                    html += '<tr><th>User Roles</th><td>' + (logData.user_roles ? logData.user_roles.join(', ') : 'None') + '</td></tr>';
                    html += '<tr><th>Request URI</th><td>' + logData.request_uri + '</td></tr>';
                    html += '<tr><th>Request Method</th><td>' + logData.request_method + '</td></tr>';
                    html += '<tr><th>User Agent</th><td>' + logData.user_agent + '</td></tr>';
                    html += '<tr><th>Referer</th><td>' + (logData.referer || 'None') + '</td></tr>';
                    html += '<tr><th>Is Admin Area</th><td>' + (logData.is_admin ? 'Yes' : 'No') + '</td></tr>';
                    html += '<tr><th>Is User Logged In</th><td>' + (logData.is_user_logged_in ? 'Yes' : 'No') + '</td></tr>';
                    html += '<tr><th>Is AJAX Request</th><td>' + (logData.is_ajax ? 'Yes' : 'No') + '</td></tr>';
                    html += '<tr><th>Is REST API Request</th><td>' + (logData.is_rest ? 'Yes' : 'No') + '</td></tr>';
                    html += '<tr><th>Is Whitelisted IP</th><td>' + (logData.is_whitelisted_ip ? 'Yes' : 'No') + '</td></tr>';
                    html += '</table>';
                    
                    // Matched rules
                    html += '<h3>Matched Rules</h3>';
                    html += '<table class="wp-list-table widefat fixed">';
                    html += '<thead><tr><th>Rule</th><th>Description</th><th>Score</th><th>Matched String</th><th>Request Parameter</th></tr></thead>';
                    html += '<tbody>';
                    
                    if (logData.matched_rules && logData.matched_rules.length > 0) {
                        logData.matched_rules.forEach(function(rule) {
                            html += '<tr>';
                            html += '<td>' + rule.rule + '</td>';
                            html += '<td>' + rule.description + '</td>';
                            html += '<td>' + rule.score + '</td>';
                            html += '<td><code>' + (rule.matched_string || 'N/A') + '</code></td>';
                            html += '<td>' + rule.key + '</td>';
                            html += '</tr>';
                        });
                    } else {
                        html += '<tr><td colspan="5">No rules matched</td></tr>';
                    }
                    
                    html += '</tbody></table>';
                    
                    // Request data (sanitized)
                    html += '<h3>Request Data</h3>';
                    html += '<div class="wpsec-request-data">';
                    html += '<pre>' + JSON.stringify(logData.request_data, null, 2) + '</pre>';
                    html += '</div>';
                    
                    html += '</div>';
                    
                    // Display the modal
                    $('#wpsec-log-details-modal').html(html).show();
                    
                    // Close button functionality
                    $('.wpsec-modal-close').click(function() {
                        $('#wpsec-log-details-modal').hide();
                    });
                    
                    // Close on click outside
                    $(window).click(function(e) {
                        if ($(e.target).is('#wpsec-log-details-modal')) {
                            $('#wpsec-log-details-modal').hide();
                        }
                    });
                }
                
                // Load logs on page load
                loadDebugLogs();
                
                // Clear logs button
                $('#wpsec-clear-logs').click(function() {
                    if (confirm('Are you sure you want to clear all debug logs?')) {
                        $.ajax({
                            url: '<?php echo esc_url(rest_url('wpsec/v1/firewall/debug-logs/clear')); ?>',
                            method: 'POST',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>');
                            },
                            success: function(response) {
                                if (response.success) {
                                    alert('Logs cleared successfully.');
                                    loadDebugLogs();
                                } else {
                                    alert('Error clearing logs: ' + response.message);
                                }
                            },
                            error: function() {
                                alert('Error clearing logs. Please try again.');
                            }
                        });
                    }
                });
            });
        </script>
        
        <style>
            .wpsec-loading {
                padding: 20px;
                text-align: center;
                font-style: italic;
            }
            
            .wpsec-logs-count {
                margin: 15px 0;
                font-weight: bold;
            }
            
            .wpsec-logs-table-container {
                margin-bottom: 20px;
                overflow-x: auto;
            }
            
            #wpsec-log-details-modal {
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                overflow: auto;
                background-color: rgba(0,0,0,0.4);
            }
            
            .wpsec-modal-content {
                background-color: #fefefe;
                margin: 5% auto;
                padding: 20px;
                border: 1px solid #888;
                width: 80%;
                max-width: 1200px;
                max-height: 80vh;
                overflow-y: auto;
                position: relative;
            }
            
            .wpsec-modal-close {
                color: #aaa;
                float: right;
                font-size: 28px;
                font-weight: bold;
                cursor: pointer;
            }
            
            .wpsec-modal-close:hover,
            .wpsec-modal-close:focus {
                color: black;
                text-decoration: none;
                cursor: pointer;
            }
            
            .wpsec-request-data {
                max-height: 300px;
                overflow-y: auto;
                background-color: #f5f5f5;
                padding: 10px;
                border: 1px solid #ddd;
            }
            
            .wpsec-request-data pre {
                white-space: pre-wrap;
                word-wrap: break-word;
            }
        </style>
    </div>
    <?php
}
