<?php
/**
 * WPFort Security - Admin Tools
 * 
 * Provides administrative tools and utilities for managing the security plugin
 */

defined('ABSPATH') || exit;

/**
 * Register admin menu items
 */
function wpsec_register_admin_menu() {
    add_submenu_page(
        'wpsec-dashboard',
        'WPFort Tools',
        'Tools',
        'manage_options',
        'wpsec-tools',
        'wpsec_tools_page'
    );
}
add_action('admin_menu', 'wpsec_register_admin_menu', 20);

/**
 * Display the tools admin page
 */
function wpsec_tools_page() {
    // Handle form submissions
    if (isset($_POST['wpsec_action']) && check_admin_referer('wpsec_tools')) {
        switch ($_POST['wpsec_action']) {
            case 'create_cache_table':
                wpsec_admin_create_cache_table();
                break;
            case 'clear_cache':
                wpsec_admin_clear_file_cache();
                break;
            case 'reset_scan':
                wpsec_admin_reset_current_scan();
                break;
            case 'purge_all_scans':
                wpsec_admin_purge_all_scan_data();
                break;
        }
    }
    
    // Display the admin page
    ?>
    <div class="wrap">
        <h1>WPFort Security Tools</h1>
        
        <div class="card">
            <h2>Database Tools</h2>
            <form method="post" action="">
                <?php wp_nonce_field('wpsec_tools'); ?>
                <p>
                    <button type="submit" name="wpsec_action" value="create_cache_table" class="button button-primary">
                        Create/Repair File Hash Cache Table
                    </button>
                    <span class="description">Use this if you're seeing database errors about missing tables</span>
                </p>
                <p>
                    <button type="submit" name="wpsec_action" value="clear_cache" class="button">
                        Clear File Hash Cache
                    </button>
                    <span class="description">Empties the file hash cache to force full rescans</span>
                </p>
            </form>
        </div>
        
        <div class="card">
            <h2>Scan Tools</h2>
            <form method="post" action="">
                <?php wp_nonce_field('wpsec_tools'); ?>
                <p>
                    <button type="submit" name="wpsec_action" value="reset_scan" class="button button-primary">
                        Reset Current Scan
                    </button>
                    <span class="description">Use this if a scan is stuck and won't respond to cancel</span>
                </p>
                <p>
                    <button type="submit" name="wpsec_action" value="purge_all_scans" class="button button-secondary" 
                           onclick="return confirm('Are you sure you want to purge ALL scan data? This will remove ALL scan history and cannot be undone.')">
                        Purge All Scan Data
                    </button>
                    <span class="description">⚠️ <strong>Warning:</strong> This will completely remove all scan data from the database</span>
                </p>
            </form>
        </div>
    </div>
    <?php
}

/**
 * Admin action to create or repair the file hash cache table
 */
function wpsec_admin_create_cache_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpsec_file_hash_cache';
    
    // Drop the table if it exists to ensure clean creation
    $wpdb->query("DROP TABLE IF EXISTS $table_name");
    
    // Create the table
    require_once(WPSEC_PLUGIN_DIR . 'includes/scan-file-cache.php');
    $result = wpsec_initialize_file_hash_cache();
    
    if ($result) {
        add_settings_error(
            'wpsec_tools',
            'table_created',
            'File hash cache table created successfully!',
            'success'
        );
    } else {
        add_settings_error(
            'wpsec_tools',
            'table_error',
            'Failed to create file hash cache table. Check server error logs for details.',
            'error'
        );
    }
}

/**
 * Admin action to clear the file hash cache
 */
function wpsec_admin_clear_file_cache() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpsec_file_hash_cache';
    
    // Truncate the table
    $wpdb->query("TRUNCATE TABLE $table_name");
    
    add_settings_error(
        'wpsec_tools',
        'cache_cleared',
        'File hash cache cleared successfully!',
        'success'
    );
}

/**
 * Admin action to reset a stuck scan
 */
function wpsec_admin_reset_current_scan() {
    // Get all active scans
    $active_scans = get_option('wpsec_active_scans', []);
    
    if (!empty($active_scans)) {
        foreach ($active_scans as $scan_id) {
            // Delete all scan data
            delete_option('wpsec_scan_' . $scan_id . '_queue');
            delete_option('wpsec_scan_' . $scan_id . '_results');
            delete_option('wpsec_scan_' . $scan_id . '_status');
            delete_option('wpsec_scan_' . $scan_id . '_progress');
            delete_option('wpsec_scan_' . $scan_id . '_total_files');
            delete_option('wpsec_scan_' . $scan_id . '_files_scanned');
            delete_option('wpsec_scan_' . $scan_id . '_checkpoint');
            delete_option('wpsec_scan_' . $scan_id . '_last_scanned_file');
            delete_option('wpsec_scan_' . $scan_id . '_last_progress_update');
            delete_option('wpsec_scan_' . $scan_id . '_stall_file');
            delete_option('wpsec_scan_' . $scan_id . '_stall_patterns');
        }
        
        // Clear the active scans list
        update_option('wpsec_active_scans', []);
        
        add_settings_error(
            'wpsec_tools',
            'scan_reset',
            count($active_scans) . ' active scan(s) have been reset successfully!',
            'success'
        );
    } else {
        add_settings_error(
            'wpsec_tools',
            'no_scans',
            'No active scans found to reset.',
            'info'
        );
    }
}
