<?php
/**
 * Uninstall: remove all plugin data from the database.
 *
 * Fired when the user clicks "Delete" on the plugin list screen.
 * All custom tables, options, and transients created by this plugin are
 * removed here.
 *
 * @package ProductRecommendations
 */

// Bail if not called from WordPress uninstall context.
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;


// Only wipe data when the user has explicitly opted in via the plugin settings.
if ( 'yes' === get_option( 'preco_delete_all_data_on_deactive' ) ) {

	global $wpdb;

	// Clear scheduled cron events.
	wp_clear_scheduled_hook( 'preco_cleanup_user_events' );

	// Drop custom tables.
	$preco_tables = array(
		'preco_user_events',
		'preco_analytics_events',
	);

	foreach ( $preco_tables as $preco_table ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( 'DROP TABLE IF EXISTS `' . esc_sql( $wpdb->prefix . $preco_table ) . '`' );
	}

	// Delete plugin options
	// A prefix wildcard instead of an exact-name list, so this never drifts out
	// of sync with new options (e.g. preco_order_bumps, preco_popup_upsells,
	// preco_global_styles, preco_onboarding_status, preco_recommendations_*, the
	// table-version and cache-generation options, and this opt-in flag itself).
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'preco\_%'" );

	// EDD license options don't follow the 'preco_' prefix, delete explicitly.
	delete_option( 'edd_preco_license_key' );
	delete_option( 'edd_preco_license_data' );

	// Delete plugin transients
	// Covers cache (preco_s_*, preco_u_*), co-purchase/top-selling caches,
	// guest-session, preview-mode, durbin-notice, and activation-redirect
	// transients — both the value and timeout rows.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_preco\_%'" );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_timeout\_preco\_%'" );

	// Clear any cached data that has been removed.
	wp_cache_flush();
}
