<?php
/**
 * Runs when the plugin is deleted via WP Admin > Plugins.
 * @package CartCue
 */
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;

/* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange */

global $wpdb;

$tables = [
	$wpdb->prefix . 'ap_workflows',
	$wpdb->prefix . 'ap_logs',
	$wpdb->prefix . 'ap_carts',
	$wpdb->prefix . 'ap_play_runs',
	$wpdb->prefix . 'ap_email_tracking',
	$wpdb->prefix . 'ap_conversions',
	$wpdb->prefix . 'ap_consents',
	$wpdb->prefix . 'ap_campaigns',
];

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

foreach (
	[
		'cartcue_db_version',
		'cartcue_settings',
		'cartcue_marketing_suppressions',
		'cartcue_marketing_consents',
		'cartcue_guest_import_stats',
	] as $opt
) {
	delete_option( $opt );
}

// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->usermeta} WHERE meta_key = %s", 'cartcue_marketing_consent' ) );

// User meta written by Pro card-expiry plays.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE '_ap\_card\_expiry\_fired\_%'" );

// Plugin transients.
$like = $wpdb->esc_like( '_transient_cartcue_' ) . '%';
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $like, $wpdb->esc_like( '_transient_timeout_cartcue_' ) . '%' ) );

if ( class_exists( 'ActionScheduler' ) && ActionScheduler::is_initialized() && function_exists( 'as_unschedule_all_actions' ) ) {
	as_unschedule_all_actions( '', [], 'cartcue' );
}

/* phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange */
