<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * This file handles complete cleanup of all plugin data when the plugin is uninstalled.
 * It removes options, transients, and flushes rewrite rules to ensure a clean removal.
 *
 * @since 1.0.0
 */
defined('WP_UNINSTALL_PLUGIN') || exit;

require_once __DIR__ . '/includes/Config.php';

use Storeplugin\PDFInvoice\Config;

/**
 * Clean up plugin data on uninstall.
 */
class NXTPDFUninstaller {
	/**
	 * Run the uninstall process.
	 *
	 * @return void
	 */
	public static function uninstall(): void {
		if (is_multisite()) {
			self::uninstallMultisite();
		} else {
			self::uninstallSingleSite();
		}
	}

	/**
	 * Uninstall for a single site.
	 *
	 * @return void
	 */
	private static function uninstallSingleSite(): void {
		global $wpdb;

		// Delete plugin options
		delete_option(Config::option('activation_info'));

		// Delete any transients
		delete_transient(Config::option('cache'));

		// Get transient names (not the full option names)
		// Uninstall need orgintal database data to remove not cached one as well as caching transient to memcache has no usefulness.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$cache_keys = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT REPLACE(option_name, '_transient_', '') as transient_name
				FROM {$wpdb->options}
				WHERE option_name LIKE %s
				AND option_name NOT LIKE %s",
				$wpdb->esc_like('_transient_' . self::cachePrefix()) . '%',
				$wpdb->esc_like('_transient_timeout_') . '%'
			)
		);

		// Delete each transient using WordPress function (handles caching)
		foreach ($cache_keys as $transient_name) {
			delete_transient($transient_name);
		}

		// Clear any cached data
		wp_cache_flush();

		// Flush rewrite rules
		flush_rewrite_rules();
	}

	/**
	 * Uninstall for multisite installation.
	 *
	 * @return void
	 */
	private static function uninstallMultisite(): void {
		global $wpdb;

		// Get all blog IDs
		// Uninstall need orgintal database data to remove not cached one as well as caching transient to memcache has no usefulness.
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$blog_ids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->blogs}");

		foreach ($blog_ids as $blog_id) {
			switch_to_blog($blog_id);
			self::uninstallSingleSite();
			restore_current_blog();
		}

		// Clean up any network-wide options if needed
		delete_site_option(Config::option('network_activation_info'));
	}

	/**
	 * Autowire cache transient prefix.
	 *
	 * @return string
	 */
	private static function cachePrefix(): string {
		return Config::prefix() . '_autowire_classes_';
	}
}

// Execute the uninstall
NXTPDFUninstaller::uninstall();
