<?php

/**
 * Uninstall Sentinel Plugin
 *
 * Executed when the plugin is deleted from WordPress admin.
 * Removes ALL Sentinel data: tables, options, transients, and cron entries.
 *
 * Security: This file is only run by WordPress during plugin deletion.
 * The plugin is NOT loaded, so we cannot call plugin functions — all
 * hook names and option names are duplicated here as local values.
 */

if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

global $wpdb;

// ── 1. Drop Sentinel database tables ────────────────────────────────────────
$tables = [
    $wpdb->prefix . 'sentinel_logs',
    $wpdb->prefix . 'sentinel_logs_archive',
    $wpdb->prefix . 'sentinel_incidents',
];

foreach ($tables as $table) {
    $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
}

// ── 2. Delete known Sentinel options by name ─────────────────────────────────
$options = [
    'sentinel_settings',
    'sentinel_version',
    'sentinel_db_version',
    'sentinel_log_management',
    'sentinel_premium_license',
    'sentinel_license_info',
    'sentinel_security_settings',
    'sentinel_custom_events',
    'sentinel_disabled_events',
    'sentinel_file_hashes',
    'sentinel_file_baselines',
    'sentinel_memory_analysis_history',
    'sentinel_custom_events_cleaned_v2',
    'sentinel_daily_digest_last_sent',
    'sentinel_weekly_digest_last_sent',
];

foreach ($options as $option) {
    delete_option($option);
}

// ── 3. Wildcard cleanup for any remaining Sentinel options and transients ────
// Uses $wpdb->esc_like() and $wpdb->prepare() to prevent injection.
// Escaped underscores in LIKE so only the literal 'sentinel_' prefix matches.
$like_patterns = [
    $wpdb->esc_like('sentinel_') . '%',
    $wpdb->esc_like('_transient_sentinel') . '%',
    $wpdb->esc_like('_transient_timeout_sentinel') . '%',
    $wpdb->esc_like('_site_transient_sentinel') . '%',
    $wpdb->esc_like('_site_transient_timeout_sentinel') . '%',
];

foreach ($like_patterns as $pattern) {
    $wpdb->query(
        $wpdb->prepare(
            "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
            $pattern
        )
    );
}

// ── 4. Remove Sentinel cron events from the cron option ─────────────────────
// The plugin is not loaded, so sentinel_get_cron_hook_names() is unavailable.
// This list MUST stay in sync with sentinel_get_cron_hook_names() in sentinel.php.
$sentinel_cron_hooks = [
    'sentinel_cleanup_logs',
    'sentinel_optimize_database',
    'sentinel_process_log_queue',
    'sentinel_retry_database',
    'sentinel_autoresolve_incidents',
    'sentinel_anonymize_logs',
    'sentinel_daily_digest',
    'sentinel_weekly_digest',
    'sentinel_check_files',
    'sentinel_optimize_tables', // legacy
];

$cron = get_option('cron');

if (is_array($cron)) {
    $changed = false;

    foreach ($cron as $timestamp => $hooks) {
        if (!is_array($hooks)) {
            continue;
        }

        foreach ($hooks as $hook => $events) {
            if (in_array($hook, $sentinel_cron_hooks, true)) {
                unset($cron[$timestamp][$hook]);
                $changed = true;
            }
        }

        // Remove the timestamp bucket if it's now empty (only 'version' key may remain).
        if (is_array($cron[$timestamp]) && empty(array_filter($cron[$timestamp], 'is_array'))) {
            unset($cron[$timestamp]);
            $changed = true;
        }
    }

    if ($changed) {
        update_option('cron', $cron);
    }
}

// ── 5. Flush object cache ───────────────────────────────────────────────────
wp_cache_flush();
