<?php
/**
 * GGM Commerce Uninstall
 *
 * Fired when the plugin is deleted (not just deactivated).
 * Checks user preference for data cleanup.
 *
 * @package GGM_Commerce
 */

// Exit if not called by WordPress uninstaller.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Check the user's cleanup preference.
$cleanup_setting = get_option( 'ggm_commerce_cleanup_on_uninstall', 'keep' );

if ( 'remove' === $cleanup_setting ) {
	// User has chosen to remove all data.

	// Include the database class for cleanup methods.
	require_once plugin_dir_path( __FILE__ ) . 'includes/class-database.php';

	// Run full uninstall (drops tables, deletes options, removes roles, clears cron).
	if ( class_exists( 'GGM_Commerce_Database' ) ) {
		GGM_Commerce_Database::uninstall();
	}

	// Also delete the cleanup preference option itself.
	delete_option( 'ggm_commerce_cleanup_on_uninstall' );

	// Delete any transients.
	global $wpdb;

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_ggmc_%'" );

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_ggmc_%'" );

	// Delete any user meta related to the plugin.
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'ggmc_%'" );

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'ggm_commerce_%'" );
}

// If 'keep' is set, do nothing - data remains for potential reinstall.
