<?php
/**
 * Uninstall script for BW Lead Attribution Intelligence.
 *
 * Runs when the plugin is deleted via the WP Admin plugins screen.
 * Cleans up options, the handoff table, and the prune cron.
 */

defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

// Delete plugin options.
// Capabilities are on ROLES, not in an option, so deleting options alone would
// leave two orphan names on every role forever.
require_once __DIR__ . '/includes/class-bw-lead-ai-caps.php';
BW_Lead_AI_Caps::remove_all();
delete_option( 'bw_lead_ai_caps_granted' );

delete_option( 'bw_lead_ai_settings' );
delete_option( 'bw_lead_ai_utm_tracking' );
delete_option( 'bw_lead_ai_version' );
delete_option( 'bw_lead_ai_handoff_schema' );
delete_option( 'bw_lead_ai_last_reprocess' );
// Which data-quality findings the owner had said they knew about. Site state, not
// settings, which is why it is its own option — and why it has to be named here too.
delete_option( 'bw_lead_ai_quality_dismissed' );
// The pepper is the key that makes stored email HMACs computable. It must go
// when the data goes — an orphaned pepper is a standing invitation to correlate.
delete_option( 'bw_lead_ai_email_pepper' );

// Delete site meta on multisite.
if ( is_multisite() ) {
	delete_site_option( 'bw_lead_ai_settings' );
}

// Stop the handoff prune cron.
$bw_lead_ai_prune = wp_next_scheduled( 'bw_lead_ai_handoff_prune' );
if ( $bw_lead_ai_prune ) {
	wp_unschedule_event( $bw_lead_ai_prune, 'bw_lead_ai_handoff_prune' );
}

// Drop both tables. Created lazily, so either may not exist. The leads table is
// the one that must never be forgotten here: it holds names, emails and email
// HMACs — uninstalling a plugin and leaving its personal-data table behind is
// precisely what a site owner would not expect.
global $wpdb;
foreach ( array( 'bw_lead_ai_handoffs', 'bw_lead_ai_leads' ) as $bw_lead_ai_suffix ) {
	$bw_lead_ai_table = $wpdb->prefix . $bw_lead_ai_suffix;
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name built from $wpdb->prefix.
	$wpdb->query( "DROP TABLE IF EXISTS {$bw_lead_ai_table}" );
}
