<?php

/**
 * Fired when the plugin is uninstalled via Freemius after_uninstall.
 *
 * Freemius calls this once per site on multisite installs, so the logic here
 * only needs to handle a single site.
 *
 * @package Esraw
 */

namespace EasyShippingRate;

class Uninstaller {

	/**
	 * Delete all plugin data for the current site.
	 *
	 * Only runs when the "Delete data on uninstall" checkbox is enabled in the
	 * plugin settings — by default nothing is deleted so an accidental uninstall
	 * loses nothing.
	 *
	 * The plugin classes depend on WooCommerce, which may not be available here,
	 * so the method id and option keys are hardcoded — they mirror
	 * ShippingMethod::METHOD_ID and the option names used throughout the plugin.
	 */
	public static function run() {
		global $wpdb;

		$settings = get_option( 'woocommerce_esraw_settings', array() );
		if ( ! is_array( $settings )
			|| ! isset( $settings['config_remove_data_on_uninstall'] )
			|| 'yes' !== $settings['config_remove_data_on_uninstall']
		) {
			return;
		}

		// Direct queries are unavoidable: there is no WP API to delete options by
		// pattern, and caching is irrelevant during uninstall.

		// Condition rules: one 'esraw{instance_id}' option per method instance.
		$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name REGEXP '^esraw[0-9]+$'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery

		// Instance settings and global plugin settings.
		$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'woocommerce\\_esraw\\_%'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
		delete_option( 'woocommerce_esraw_settings' );
		delete_option( 'esraw_review_snooze_until' );
		delete_option( 'esraw_review_done' );
		delete_option( 'esraw_inline_delete_uses' );
		delete_option( 'esraw_usage_consent' );
		delete_option( 'esraw_notify_pending' );
		delete_option( 'esraw_notify_installed_sent' );
		delete_option( 'esraw_consent_snooze_until' );
		delete_option( 'esraw_consent_declines' );

		// Remove our method rows from WooCommerce zones — the table may be gone if
		// WooCommerce was uninstalled first.
		$table = $wpdb->prefix . 'woocommerce_shipping_zone_methods';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery
			$wpdb->delete( $table, array( 'method_id' => 'esraw' ), array( '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
		}

		wp_cache_flush();
	}
}
