<?php
/**
 * WPFort Security Scan Cleanup Utility
 * 
 * This standalone script will purge all scan-related data from the WordPress database.
 * Place this file in your WordPress root directory and access it via the browser,
 * or run it using WP-CLI with: wp eval-file wpfort-cleanup.php
 */

// Bootstrap WordPress
if (!defined('ABSPATH')) {
    // Define standard WordPress load path
    define('WP_USE_THEMES', false);
    require_once('wp-load.php');
}

// Security check - only allow admins to run this
if (!function_exists('current_user_can') || !current_user_can('manage_options')) {
    die("Access denied. You need admin privileges to run this script.");
}

// Function to purge all scan data
function wpfort_purge_all_scan_data() {
    global $wpdb;
    
    echo "<h1>WPFort Security Scan Data Cleanup</h1>";
    
    // Log the purge action
    wpsec_debug_log('🧹 WPFort Admin: Purging all scan data from database', 'info');
    echo "<p>Starting cleanup process...</p>";
    
    // Get all scan-related options
    $scan_options = $wpdb->get_results(
        "SELECT option_name FROM $wpdb->options 
         WHERE option_name LIKE 'wpsec_scan_%' 
         OR option_name = 'wpsec_active_scans'
         OR option_name = 'wpsec_current_scan_id'
         OR option_name = 'wpsec_scan_problematic_files'
         OR option_name = 'wpsec_scan_excluded_stall_files'",
        ARRAY_A
    );
    
    // Count how many options we're deleting
    $deleted_count = 0;
    $total_count = count($scan_options);
    
    echo "<p>Found " . esc_html($total_count) . " scan-related database entries to clean up.</p>";
    
    // Delete all scan options
    if (!empty($scan_options)) {
        echo "<ul>";
        foreach ($scan_options as $option) {
            $option_name = $option['option_name'];
            if (delete_option($option_name)) {
                echo "<li>Deleted: " . esc_html($option_name) . "</li>";
                $deleted_count++;
            } else {
                echo "<li style='color:red;'>Failed to delete: " . esc_html($option_name) . "</li>";
            }
            
            // Flush output buffer to show progress
            if (ob_get_level() > 0) {
                ob_flush();
                flush();
            }
        }
        echo "</ul>";
    }
    
    // Clear active scans list
    update_option('wpsec_active_scans', []);
    
    // Success message
    echo "<h2>Cleanup Complete!</h2>";
    echo "<p>Successfully removed " . esc_html($deleted_count) . " scan data entries from the database.</p>";
    
    // Log completion
    wpsec_debug_log("✅ WPFort Admin: Purged $deleted_count scan data entries from database", 'info');
    
    // Add a link back to admin
    echo "<p><a href='" . esc_url(admin_url('admin.php?page=wpsec-dashboard')) . "'>Return to WPFort Dashboard</a></p>";
}

// Run the purge function
wpfort_purge_all_scan_data();
