<?php
/**
 * ActiveTrail WooCommerce Uninstall
 *
 * @package ActiveTrail_WooCommerce
 * @since 1.0.0
 */

// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

/**
 * Clean up plugin data on uninstall
 */
function activetrail_wc_uninstall() {
	global $wpdb;

	// Send disconnect API call before cleanup.
	// Note: WordPress is already loaded when uninstall.php runs, but we need to load plugin files.
	$plugin_file = dirname( __FILE__ ) . '/activetrail-for-woocommerce.php';
	if ( file_exists( $plugin_file ) ) {
		// Load the main plugin file which defines activetrail_wc_send_disconnect.
		require_once $plugin_file;
		
		// Call disconnect if function exists.
		if ( function_exists( 'activetrail_wc_send_disconnect' ) ) {
			activetrail_wc_send_disconnect();
		}
	}

	// Remove plugin options
	delete_option( 'activetrail_wc_settings' );

	// Remove individual WooCommerce settings
	$wc_options = array(
		'activetrail_api_key',
		'activetrail_group_id',
		'activetrail_order_statuses',
		'activetrail_enable_checkout_consent',
		'activetrail_consent_text',
		'activetrail_consent_checked_by_default',
		'activetrail_consent_required',
		'activetrail_sync_without_consent',
		'activetrail_enable_cart_tracking',
		'activetrail_enable_product_feed',
		'activetrail_feed_title',
		'activetrail_feed_description',
		'activetrail_debug_mode',
	);

	foreach ( $wc_options as $option ) {
		delete_option( $option );
	}

	// Remove custom post meta
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for uninstall cleanup
	$wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE '_activetrail_%'" );

	// Remove custom user meta
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for uninstall cleanup
	$wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE '_activetrail_%'" );

	// Drop custom tables
	$table_name = $wpdb->prefix . 'activetrail_cart_tracking';
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Direct query needed for uninstall, table name is safe (built from $wpdb->prefix)
	$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );

	// Clear scheduled events
	wp_clear_scheduled_hook( 'activetrail_sync_abandoned_carts' );
	wp_clear_scheduled_hook( 'activetrail_clean_expired_coupons' );

	// Remove transients
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for uninstall cleanup
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_activetrail_%'" );
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Direct query needed for uninstall cleanup
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_activetrail_%'" );

	// Remove ActiveTrail coupons (optional - user might want to keep them)
	$remove_coupons = get_option( 'activetrail_remove_coupons_on_uninstall', false );
	if ( $remove_coupons ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Direct query needed for uninstall cleanup
		$coupon_ids = $wpdb->get_col(
			"SELECT post_id FROM {$wpdb->postmeta} 
             WHERE meta_key = '_activetrail_coupon' 
             AND meta_value = 'yes'"
		);

		foreach ( $coupon_ids as $coupon_id ) {
			wp_delete_post( $coupon_id, true );
		}
	}

	// Flush rewrite rules
	flush_rewrite_rules();

	// Log uninstall (if debug mode was enabled)
    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Uninstall script, logger may not be available
	if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Uninstall script, logger may not be available
		error_log( '[ActiveTrail WC] Plugin uninstalled and data cleaned up' );
	}
}

// Run uninstall
activetrail_wc_uninstall();
