<?php
/**
 * Debug Logs Admin Page
 * 
 * Provides an admin interface to view, download, and manage plugin debug logs
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Register the debug logs submenu page
 */
function wpsec_register_debug_logs_menu() {
    // Only show this menu if debug mode is enabled
    if (!defined('WPSEC_DEBUG') || !WPSEC_DEBUG) {
        return;
    }
    
    add_submenu_page(
        'wpsec-scan-debug',     // Parent menu slug
        'WPFort Debug Logs',    // Page title
        'Debug Logs',           // Menu title
        'manage_options',       // Capability
        'wpsec-debug-logs',     // Menu slug
        'wpsec_render_debug_logs_page' // Callback function
    );
}
add_action('admin_menu', 'wpsec_register_debug_logs_menu');

/**
 * Handle debug log actions
 */
function wpsec_handle_debug_log_actions() {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    // Handle actions
    if (isset($_POST['wpsec_log_action']) && isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'wpsec_log_action')) {
        $action = sanitize_text_field($_POST['wpsec_log_action']);
        
        switch ($action) {
            case 'clear_logs':
                if (class_exists('WPSEC_Logger')) {
                    // Clear all log files including rotated ones
                    $log_files = WPSEC_Logger::get_log_files();
                    $cleared_count = 0;
                    foreach ($log_files as $filename => $file_info) {
                        if (file_exists($file_info['path'])) {
                            if (unlink($file_info['path'])) {
                                $cleared_count++;
                            }
                        }
                    }
                    // Also clear the main log
                    WPSEC_Logger::clear_log();
                    add_settings_error('wpsec_logs', 'logs_cleared', 'All debug logs have been cleared successfully (' . $cleared_count . ' files).', 'updated');
                }
                break;
        }
    }
    
    // Handle download action
    if (isset($_GET['action']) && $_GET['action'] === 'download_log' && isset($_GET['file']) && isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'download_log')) {
        $file = sanitize_text_field($_GET['file']);
        
        if (class_exists('WPSEC_Logger')) {
            $log_files = WPSEC_Logger::get_log_files();
            
            if (isset($log_files[$file])) {
                $log_path = $log_files[$file]['path'];
                
                // Set headers for download
                header('Content-Type: text/plain');
                header('Content-Disposition: attachment; filename="' . basename($log_path) . '"');
                header('Content-Length: ' . filesize($log_path));
                header('Connection: close');
                
                // Output file content
                // Use WP_Filesystem instead of direct readfile
                global $wp_filesystem;
                if (empty($wp_filesystem)) {
                    require_once(ABSPATH . '/wp-admin/includes/file.php');
                    WP_Filesystem();
                }
                echo esc_html($wp_filesystem->get_contents($log_path));
                exit;
            }
        }
    }
}
add_action('admin_init', 'wpsec_handle_debug_log_actions');

/**
 * Render the debug logs admin page
 */
function wpsec_render_debug_logs_page() {
    // Check user capability
    if (!current_user_can('manage_options')) {
        return;
    }
    
    // Styles for the log viewer
    echo '<style>
        .wpsec-log-viewer {
            background: #fff;
            border: 1px solid #ccd0d4;
            box-shadow: 0 1px 1px rgba(0,0,0,.04);
            margin-top: 20px;
            padding: 10px;
        }
        .wpsec-log-content {
            background: #f6f7f7;
            border: 1px solid #ddd;
            font-family: monospace;
            height: 500px;
            margin-bottom: 20px;
            overflow: auto;
            padding: 10px;
            white-space: pre-wrap;
        }
        .wpsec-log-content .debug { color: #666; }
        .wpsec-log-content .info { color: #0073aa; }
        .wpsec-log-content .notice { color: #00a32a; }
        .wpsec-log-content .warning { color: #ffb900; }
        .wpsec-log-content .error { color: #d63638; }
        .wpsec-log-content .critical { color: #d63638; font-weight: bold; }
        .wpsec-log-files {
            margin-top: 20px;
        }
        .wpsec-log-files table {
            border-collapse: collapse;
            width: 100%;
        }
        .wpsec-log-files th, .wpsec-log-files td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .wpsec-log-files th {
            background-color: #f6f7f7;
        }
        .wpsec-log-actions {
            margin-top: 20px;
        }
        .wpsec-log-filter {
            margin-bottom: 10px;
        }
    </style>';
    
    // Page header
    echo '<div class="wrap">';
    echo '<h1>' . esc_html__('WPFort Debug Logs', 'wpfortai-security') . '</h1>';
    
    // Only show success messages, suppress error notices to avoid UI clutter
    $settings_errors = get_settings_errors('wpsec_logs');
    foreach ($settings_errors as $error) {
        if ($error['type'] === 'updated') {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($error['message']) . '</p></div>';
        }
    }
    
    // Display log content if logger class exists
    if (class_exists('WPSEC_Logger')) {
        $log_files = WPSEC_Logger::get_log_files();
        $current_log = isset($_GET['log']) && isset($log_files[$_GET['log']]) ? sanitize_text_field($_GET['log']) : basename(WPSEC_Logger::get_log_file());
        $current_log_path = isset($log_files[$current_log]) ? $log_files[$current_log]['path'] : WPSEC_Logger::get_log_file();
        
        // Log viewer tabs
        if (!empty($log_files)) {
            echo '<div class="nav-tab-wrapper">';
            foreach ($log_files as $filename => $file_info) {
                $active = ($current_log === $filename) ? ' nav-tab-active' : '';
                echo '<a href="' . esc_url(admin_url('admin.php?page=wpsec-debug-logs&log=' . urlencode($filename))) . '" class="nav-tab' . esc_attr($active) . '">' . esc_html($filename) . ' (' . esc_html($file_info['size']) . ')</a>';
            }
            echo '</div>';
            
            // Log content
            $log_content = WPSEC_Logger::get_log_content($current_log_path);
            
            // Filter controls
            echo '<div class="wpsec-log-filter">';
            echo '<select id="wpsec-log-level-filter">';
            echo '<option value="">All Levels</option>';
            echo '<option value="DEBUG">Debug Only</option>';
            echo '<option value="INFO">Info & Above</option>';
            echo '<option value="NOTICE">Notice & Above</option>';
            echo '<option value="WARNING">Warning & Above</option>';
            echo '<option value="ERROR">Error & Above</option>';
            echo '<option value="CRITICAL">Critical Only</option>';
            echo '</select>';
            
            echo ' <label><input type="checkbox" id="wpsec-errors-only" /> Show Errors Only</label>';
            
            echo ' <input type="text" id="wpsec-log-search" placeholder="Search logs..." style="width: 200px;">';
            echo ' <button id="wpsec-log-search-btn" class="button">Search</button>';
            echo ' <button id="wpsec-log-search-clear" class="button">Clear</button>';
            echo '</div>';
            
            echo '<div class="wpsec-log-viewer">';
            echo '<div class="wpsec-log-content" id="wpsec-log-content">';
            
            // Process log content with syntax highlighting (limit to last 1000 lines to avoid UI overload)
            if (!empty($log_content)) {
                $lines = explode(PHP_EOL, $log_content);
                $total_lines = count($lines);
                $max_display_lines = 1000;
                
                if ($total_lines > $max_display_lines) {
                    $lines = array_slice($lines, -$max_display_lines);
                    echo '<div class="notice notice-info inline"><p>Showing last ' . $max_display_lines . ' lines of ' . $total_lines . ' total lines. Download the full log for complete history.</p></div>';
                }
                
                foreach ($lines as $line) {
                    if (empty(trim($line))) continue;
                    
                    // Determine the log level and apply appropriate CSS class
                    $class = 'info'; // default
                    if (strpos($line, 'DEBUG') !== false) {
                        $class = 'debug';
                    } elseif (strpos($line, 'INFO') !== false) {
                        $class = 'info';
                    } elseif (strpos($line, 'NOTICE') !== false) {
                        $class = 'notice';
                    } elseif (strpos($line, 'WARNING') !== false) {
                        $class = 'warning';
                    } elseif (strpos($line, 'ERROR') !== false) {
                        $class = 'error';
                    } elseif (strpos($line, 'CRITICAL') !== false) {
                        $class = 'critical';
                    }
                    
                    echo '<div class="log-line ' . esc_attr($class) . '">' . esc_html($line) . '</div>';
                }
            } else {
                echo esc_html__('The log file is empty.', 'wpfortai-security');
            }
            
            echo '</div>'; // .wpsec-log-content
            
            // Log actions
            echo '<div class="wpsec-log-actions">';
            
            // Download button
            if (isset($log_files[$current_log])) {
                $download_url = wp_nonce_url(
                    admin_url('admin.php?page=wpsec-debug-logs&action=download_log&file=' . urlencode($current_log)),
                    'download_log'
                );
                echo '<a href="' . esc_url($download_url) . '" class="button button-secondary">Download Log</a> ';
            }
            
            // Clear log form
            echo '<form method="post" style="display:inline;">';
            wp_nonce_field('wpsec_log_action');
            echo '<input type="hidden" name="wpsec_log_action" value="clear_logs">';
            echo '<button type="submit" class="button button-secondary" onclick="return confirm(\'Are you sure you want to clear all logs?\');">Clear Logs</button>';
            echo '</form>';
            
            echo '</div>'; // .wpsec-log-actions
            echo '</div>'; // .wpsec-log-viewer
            
            // JavaScript for filtering
            echo '<script>
                jQuery(document).ready(function($) {
                    // Filter logs by level
                    $("#wpsec-log-level-filter").change(function() {
                        var level = $(this).val();
                        
                        if (level === "") {
                            $(".log-line").show();
                            return;
                        }
                        
                        $(".log-line").hide();
                        
                        switch(level) {
                            case "DEBUG":
                                $(".debug").show();
                                break;
                            case "INFO":
                                $(".info, .notice, .warning, .error, .critical").show();
                                break;
                            case "NOTICE":
                                $(".notice, .warning, .error, .critical").show();
                                break;
                            case "WARNING":
                                $(".warning, .error, .critical").show();
                                break;
                            case "ERROR":
                                $(".error, .critical").show();
                                break;
                            case "CRITICAL":
                                $(".critical").show();
                                break;
                        }
                    });
                    
                    // Search logs
                    $("#wpsec-log-search-btn").click(function() {
                        var searchText = $("#wpsec-log-search").val().toLowerCase();
                        
                        if (searchText === "") {
                            $(".log-line").show();
                            return;
                        }
                        
                        $(".log-line").each(function() {
                            var lineText = $(this).text().toLowerCase();
                            if (lineText.indexOf(searchText) > -1) {
                                $(this).show();
                            } else {
                                $(this).hide();
                            }
                        });
                    });
                    
                    // Clear search
                    $("#wpsec-log-search-clear").click(function() {
                        $("#wpsec-log-search").val("");
                        $(".log-line").show();
                    });
                    
                    // Errors only checkbox
                    $("#wpsec-errors-only").change(function() {
                        if ($(this).is(":checked")) {
                            $(".log-line").hide();
                            $(".error, .critical").show();
                        } else {
                            $(".log-line").show();
                        }
                    });
                });
            </script>';
            
        } else {
            echo '<p>No log files found.</p>';
        }
        
        // Additional information
        echo '<h3>Debug Information</h3>';
        echo '<p>Debug Mode: ' . (defined('WPSEC_DEBUG') && WPSEC_DEBUG ? '<span style="color:green">Enabled</span>' : '<span style="color:red">Disabled</span>') . '</p>';
        echo '<p>To enable or disable debug mode, add the following line to your wp-config.php file:</p>';
        echo '<pre>define(\'WPSEC_DEBUG\', true); // Set to false to disable debug mode</pre>';
    } else {
        echo '<div class="notice notice-error"><p>The WPSEC_Logger class is not available. Debug logs cannot be displayed.</p></div>';
    }
    
    echo '</div>'; // .wrap
}
