<?php
/**
 * VMPFence Security Uninstall
 * 
 * Fired when the plugin is uninstalled.
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.1.1 Added comprehensive data cleanup and critical fixes
 * @since 2.1.2 Added removal of mu-plugins file and directory
 * @since 2.2.0 Added cleanup of geoip transients
 * @since 2.2.2 Added cleanup of data retention choice option
 * @since 2.2.4 Added cleanup for onboarding state, SIEM DB version
 */

// If uninstall not called from WordPress, exit
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// Load plugin constants and dependencies
define('VMPFENCE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('VMPFENCE_PLUGIN_URL', plugin_dir_url(__FILE__));

// Define VMPFENCE_VERSION if not already defined (vmpfence.php is not loaded during uninstall)
if (!defined('VMPFENCE_VERSION')) {
    define('VMPFENCE_VERSION', '2.2.6');
}

// Load required classes in correct order
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-constants.php';
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-utils.php';
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-audit-log.php';
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-config.php';
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-database.php';

// ============================================================================
// LOCAL CLEANUP ONLY - Server NEVER deletes data
// ============================================================================
// NEW POLICY: Server NEVER deletes user/license/API key data
// - FREE and PREMIUM licenses both preserved permanently on server
// - WordPress "Delete" button always triggers full local cleanup (WordPress standard)
// - Plugin manages local WordPress cleanup only
// - Users can always reinstall and reuse their license via setup wizard

// ✅ CRITICAL FIX: WordPress Delete button ALWAYS deletes everything (standard behavior)
// The "keep data" option only applies to deactivation (temporary), not deletion (permanent)
// When user clicks Delete, they expect a clean slate for future reinstalls
$preserve_data = false; // Always clean up on deletion

if (!$preserve_data) {
    global $wpdb;
    
    // Remove onboarding state
    VMPFence_Config::delete('onboarding_dismissed');
    
    // Remove all options FIRST (before dropping tables)
    VMPFence_Config::remove_all_options();
    // Remove database tables
    VMPFence_Database::drop_tables();
    // Clean up deactivation-related options (not in remove_all_options to avoid deletion during deactivation)
    delete_option('vmpfence_enable_deactivation_choice');
    // Clean up SIEM DB version option (prevents stale state on reinstall — ISSUE-002 fix)
    delete_option('vmpfence_siem_db_version');
    // Ensure all vmpfence tables are dropped (including any missed ones)
    $all_tables = $wpdb->get_results("SHOW TABLES LIKE '{$wpdb->prefix}vmpfence_%'", ARRAY_N);
    foreach ($all_tables as $table) {
        $table_name = $table[0];
        $wpdb->query("DROP TABLE IF EXISTS `{$table_name}`");
    }
    
    // Clean up all GeoIP transient caches
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} 
             WHERE option_name LIKE %s 
             OR option_name LIKE %s",
            $wpdb->esc_like('_transient_vmpfence_geoip_') . '%',
            $wpdb->esc_like('_transient_timeout_vmpfence_geoip_') . '%'
        )
    );

    // Remove upload directory
    $upload_dir = wp_upload_dir();
    vmpfence_remove_directory_uninstall($upload_dir['basedir'] . '/vmpfence/');
    
    // CRITICAL FIX: Remove ALL scan-related transients and locks
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_vmpfence_%' OR option_name LIKE '_transient_timeout_vmpfence_%'");
    
    // Remove scan progress and checkpoint data
    delete_option('vmpfence_scan_progress');
    delete_option('vmpfence_last_scan_debug_logs');
    
    // Remove cron jobs including async scan worker
    wp_clear_scheduled_hook('vmpfence_daily_scan');
    wp_clear_scheduled_hook('vmpfence_cleanup');
    wp_clear_scheduled_hook('vmpfence_hourly_check');
    wp_clear_scheduled_hook('vmpfence_weekly_report');
    wp_clear_scheduled_hook('vmpfence_hourly_blocked_ip_sync'); // Real-time IP blocklist sync
    wp_clear_scheduled_hook('vmpfence_async_scan_worker'); // Async scan worker
    // SIEM sync crons (v2.3.0+) — ISSUE-004 fix
    wp_clear_scheduled_hook('vmpfence_siem_sync');
    wp_clear_scheduled_hook('vmpfence_retry_identification');
}

// Remove early protection file from mu-plugins (always, even if preserving data)
$mu_plugins_file = WP_CONTENT_DIR . '/mu-plugins/vmpfence-early-protection.php';
if (file_exists($mu_plugins_file)) {
    @unlink($mu_plugins_file);
}

// Remove mu-plugins directory if it's empty
$mu_plugins_dir = WP_CONTENT_DIR . '/mu-plugins';
if (is_dir($mu_plugins_dir)) {
    $files = array_diff(scandir($mu_plugins_dir), array('.', '..'));
    if (empty($files)) {
        @rmdir($mu_plugins_dir);
    }
}

// Clean up the preserve_data option itself (whether we preserved data or not)
delete_option('vmpfence_preserve_data_on_uninstall');

// Remove rewrite rules
flush_rewrite_rules();

/**
 * Remove directory and all contents recursively
 *
 * @param string $dir Directory path
 * @return bool
 */
function vmpfence_remove_directory_uninstall($dir) {
    if (!is_dir($dir)) {
        return false;
    }

    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (is_dir($path)) {
            vmpfence_remove_directory_uninstall($path);
        } else {
            @unlink($path);
        }
    }

    return @rmdir($dir);
}
