<?php
/**
 * Fires when the plugin is uninstalled.
 *
 * Honours the user's "Remove all data on uninstall" preference (default OFF).
 *
 * @package WPLens
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable WordPress.DB.DirectDatabaseQuery.SchemaChange
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter
//
// Justification: uninstall.php is executed once at plugin uninstall time. It runs in
// global scope by design — there is no class to wrap variables inside. Table-drop
// SQL uses statically-built table names from $wpdb->prefix . a constant suffix.


$settings = get_option( 'wplens_settings', array() );
$remove   = is_array( $settings )
	&& ! empty( $settings['privacy']['remove_data_on_uninstall'] );

if ( ! $remove ) {
	return;
}

global $wpdb;
$prefix = $wpdb->prefix;

// Drop custom tables.
$tables = array(
	$prefix . 'wplens_crawler_log',
	$prefix . 'wplens_scans',
	$prefix . 'wplens_citation_queries',
	$prefix . 'wplens_citation_checks',
);

foreach ( $tables as $table ) {
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DROP TABLE IF EXISTS {$table}" );
}

// Delete options.
$options = array(
	'wplens_settings',
	'wplens_db_version',
	'wplens_ip_salt',
	'wplens_provider_keys',
	'wplens_setup_complete',
	'wplens_credits_this_month',
);
foreach ( $options as $opt ) {
	delete_option( $opt );
}

// Clear transients.
delete_transient( 'wplens_bot_regex_v1' );
delete_transient( 'wplens_llms_txt_present' );

// Unschedule crons.
$hooks = array(
	'wplens_cron_log_pruner',
	'wplens_cron_citations_run',
	'wplens_cron_weekly_report',
	'wplens_cron_self_health',
);
foreach ( $hooks as $hook ) {
	$ts = wp_next_scheduled( $hook );
	while ( false !== $ts ) {
		wp_unschedule_event( $ts, $hook );
		$ts = wp_next_scheduled( $hook );
	}
}
