<?php
/**
 * Plugin uninstall: drop all custom tables, delete options, remove capabilities.
 *
 * @package SuiteMkt3k
 */

if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange

if ( defined( 'WPMU_PLUGIN_DIR' ) ) {
	$legacy_mu = WPMU_PLUGIN_DIR . '/suitemkt3k-guard.php';
	if ( is_file( $legacy_mu ) ) {
		// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
		@unlink( $legacy_mu );
	}
}

global $wpdb;

$shop_coupon_meta_keys = array( '_suitemkt3k_campaign_id', '_suitemkt3k_cart_id' );
foreach ( $shop_coupon_meta_keys as $meta_key ) {
	$ids = $wpdb->get_col(
		$wpdb->prepare(
			"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s",
			$meta_key
		)
	);
	foreach ( (array) $ids as $post_id ) {
		wp_delete_post( (int) $post_id, true );
	}
}

$tables = array(
	'wmk_coupons',
	'wmk_coupon_designs',
	'wmk_subscribers',
	'wmk_newsletters',
	'wmk_newsletter_recipients',
	'wmk_newsletter_forms',
	'wmk_abandoned_carts',
	'wmk_cart_email_templates',
	'wmk_events',
	'wmk_stats_daily',
	'wmk_rate_limits',
	'wmk_logs',
);
foreach ( $tables as $t ) {
	$table = $wpdb->prefix . $t;
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$wpdb->query( "DROP TABLE IF EXISTS `{$table}`" );
}

$options = array(
	'suitemkt3k_settings',
	'suitemkt3k_db_version',
	'suitemkt3k_activated_at',
	'suitemkt3k_secret_key',
	'suitemkt3k_boot_error',
	'suitemkt3k_fatal_error',
	'suitemkt3k_pending_setup',
	'suitemkt3k_setup_log',
	'suitemkt3k_guard_active',
	'suitemkt3k_debug_log',
	'suitemkt3k_activation_trace',
	'suitemkt3k_file_loaded_trace',
	'suitemkt3k_fix_false_cart_recoveries_v1',
);
foreach ( $options as $opt ) {
	delete_option( $opt );
	delete_site_option( $opt );
}

delete_metadata( 'user', 0, 'suitemkt3k_locale', '', true );

if ( function_exists( 'wp_roles' ) ) {
	$caps = array( 'manage_suitemkt3k', 'edit_suitemkt3k_campaigns', 'view_suitemkt3k_stats', 'edit_suitemkt3k_settings' );
	foreach ( wp_roles()->roles as $role_key => $role_data ) {
		$role = get_role( $role_key );
		if ( ! $role ) {
			continue;
		}
		foreach ( $caps as $cap ) {
			$role->remove_cap( $cap );
		}
	}
}

foreach ( array( 'suitemkt3k_cron_5min', 'suitemkt3k_cron_15min', 'suitemkt3k_cron_hourly', 'suitemkt3k_cron_daily', 'suitemkt3k_send_newsletter_batch' ) as $hook ) {
	wp_clear_scheduled_hook( $hook );
}
