<?php
/**
 * Uninstall cleanup.
 *
 * This used to live in a root uninstall.php. It does not any more, because WordPress
 * runs EITHER uninstall.php OR the registered uninstall hooks — never both. With the
 * file present, Freemius's own uninstall handler never ran, so its account data was
 * left behind and its API never learned the plugin had been removed.
 *
 * The logic is registered two ways, because not every build ships Freemius:
 *
 *   Freemius builds   edfw_fs()->add_action( 'after_uninstall', … )
 *   WooCommerce build register_uninstall_hook(), since there is no SDK to hook into
 *
 * Only one ever fires, so the cleanup cannot run twice — and it is idempotent anyway.
 *
 * @package EstimatedDeliveryDateWC
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'edfw_run_uninstall' ) ) {

	/**
	 * Remove everything this plugin stored, but only if the store owner asked for it.
	 *
	 * Off by default: uninstalling to troubleshoot, or to move to another host, should
	 * not silently destroy a carefully built rule set. The opt-in lives under
	 * Advanced → When uninstalling.
	 *
	 * @since 1.1.0
	 */
	function edfw_run_uninstall() {
		$settings = (array) get_option( 'edfw_settings', array() );

		if ( 'yes' !== ( $settings['uninstall_cleanup'] ?? 'no' ) ) {
			return;
		}

		delete_option( 'edfw_settings' );
		delete_option( 'edfw_rules' );
		delete_option( 'edfw_cache_ver' );

		// Premium settings live in their own option. Removed here too: the premium code
		// may already be gone from disk, so it cannot clean up after itself.
		delete_option( 'edfwp_settings' );

		// Per-product overrides.
		delete_post_meta_by_key( '_edfw_enable' );
		delete_post_meta_by_key( '_edfw_rules' );

		// Computed-date transients.
		global $wpdb;
		$like         = $wpdb->esc_like( '_transient_edfw_d_' ) . '%';
		$like_timeout = $wpdb->esc_like( '_transient_timeout_edfw_d_' ) . '%';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- One-off bulk cleanup on uninstall; no caching applicable.
		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
				$like,
				$like_timeout
			)
		);
	}
}

/*
 * Freemius owns the uninstall lifecycle when it is present, so its handler runs and
 * ours is invoked from it. Without the SDK — the WooCommerce.com build — fall back to
 * WordPress's own registration.
 */
if ( function_exists( 'edfw_fs' ) ) {
	edfw_fs()->add_action( 'after_uninstall', 'edfw_run_uninstall' );
} else {
	register_uninstall_hook( EDFW_FILE, 'edfw_run_uninstall' );
}
