<?php
/**
 * Compliance Guard — uninstall handler.
 *
 * Fires when WordPress deletes the plugin via wp-admin → Plugins → Delete
 * (NOT on simple deactivation). Safe by default: leaves every option,
 * audit log, scan history, and stored detection intact so the merchant
 * does not lose months of compliance evidence by accidentally clicking
 * Delete. Merchants who genuinely want a full wipe can set the
 * `RPCA_UNINSTALL_DELETE_DATA` constant to true in wp-config.php before
 * deletion; only then does this handler purge the plugin's option keys,
 * transients, scheduled events, and custom tables.
 *
 * @package RUO_Compliance_AI_Auditor
 */

// Guard: only run inside a WordPress uninstall request.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Default behaviour is preservation. Merchants must explicitly opt in
// to data deletion via wp-config.php — protects against accidental
// "Delete plugin" clicks wiping months of audit evidence + scan
// history that may matter for chargeback or regulator review.
if ( ! defined( 'RPCA_UNINSTALL_DELETE_DATA' ) || true !== RPCA_UNINSTALL_DELETE_DATA ) {
	return;
}

global $wpdb;

// (1) Delete every plugin-owned option key. Listed explicitly so a
// future option key in the same `rpca_` namespace is NOT silently
// deleted unless it was on this list.
$option_keys = array(
	'rpca_options',
	'rpca_last_scan',
	'rpca_scan_history',
	'rpca_audit_log',
	'rpca_user_feedback_log',
	'rpca_processor_doc_analysis',
	'rpca_intent_chain_anchor',
	'rpca_intent_chain_latest_hash',
	'rpca_setup_wizard_state',
);
foreach ( $option_keys as $option_key ) {
	delete_option( $option_key );
	delete_site_option( $option_key );
}

// (2) Delete every plugin-owned transient + namespaced transient.
// Wildcard deletion goes through wpdb because there is no core
// helper for "delete every transient starting with prefix X."
$transient_prefixes = array(
	'rpca_',
);
foreach ( $transient_prefixes as $prefix ) {
	$like = $wpdb->esc_like( '_transient_' . $prefix ) . '%';
	$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) );
	$like = $wpdb->esc_like( '_transient_timeout_' . $prefix ) . '%';
	$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) );
}

// (3) Clear scheduled cron events the plugin registered. These MUST stay in
// sync with the hook constants the main plugin schedules + the
// wp_clear_scheduled_hook() list in RUO_Compliance_AI_Auditor::deactivate().
// uninstall.php is standalone (the plugin class is not loaded here), so the
// hook NAMES are duplicated as literals — tests/uninstall-cron-cleanup-checks.mjs
// pins them against the real constants so they can never drift again.
// v0.7.459: prior list cleared four names that never existed
// (rpca_daily_scan_event / rpca_weekly_digest_event / rpca_fda_ingest_event /
// rpca_synthetic_buyer_event) and missed every real recurring hook, leaving
// orphaned cron entries on a full-wipe uninstall. deactivate() (which always
// runs first) covers the normal path, but uninstall must be correct too.
foreach ( array(
	'rpca_regulator_alert_send',          // single-event regulator alert dispatch
	'rpca_scheduled_monitor_scan',        // MONITOR_HOOK
	'rpca_background_admin_scan',          // BACKGROUND_SCAN_HOOK
	'rpca_daily_fda_intelligence_update', // FDA_INTELLIGENCE_HOOK
	'rpca_addendum2_daily_ops',           // DAILY_OPS_HOOK
	'rpca_addendum2_weekly_ops',          // WEEKLY_OPS_HOOK
	'rpca_anchor_intent_chain',           // ANCHOR_HOOK
) as $hook ) {
	$timestamp = wp_next_scheduled( $hook );
	while ( $timestamp ) {
		wp_unschedule_event( $timestamp, $hook );
		$timestamp = wp_next_scheduled( $hook );
	}
}

// (4) Drop the per-order intent-attestation evidence tables created
// at activation. Listed explicitly so we never accidentally drop
// something with a similar prefix.
$plugin_tables = array(
	$wpdb->prefix . 'ruo_intent_attestations',
	$wpdb->prefix . 'ruo_render_captures',
	$wpdb->prefix . 'ruo_session_features',
	$wpdb->prefix . 'ruo_coa_chain',
);
foreach ( $plugin_tables as $table ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery
	$wpdb->query( 'DROP TABLE IF EXISTS ' . $table );
}

// (5) Clear custom capabilities the plugin added.
foreach ( array( 'manage_ruo_compliance_emergency' ) as $cap ) {
	$role = get_role( 'administrator' );
	if ( $role ) {
		$role->remove_cap( $cap );
	}
}
