<?php
declare( strict_types=1 );

namespace FiboFilters\Config;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Uninstall
 */
class Uninstall {
	public static function after_uninstall() {
		/**
		 * Single site.
		 */
		self::wipe_tables();
		self::wipe_options();
		self::wipe_transients();
		self::wipe_action_scheduler_logs();
		self::wipe_wc_logs();
		self::wipe_descriptors_cache();

		/**
		 * Multisite.
		 */
		if ( is_multisite() ) {
			$current_site_id = get_current_blog_id();

			foreach ( get_sites() as $site ) {
				if ( is_numeric( $site->blog_id ) && $site->blog_id > 1 ) {
					switch_to_blog( $site->blog_id );

					self::wipe_tables();
					self::wipe_options();
					self::wipe_transients();
					self::wipe_action_scheduler_logs();
					self::wipe_wc_logs();
					self::wipe_descriptors_cache();
				}
			}

			// Switch back to the original site.
			switch_to_blog( ( $current_site_id ) );
		}
	}

	/**
	 * Wipe database tables.
	 */
	private static function wipe_tables() {
		global $wpdb;

		$plugin_tables = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $wpdb->prefix . 'fibofilters_' ) . '%' ) );
		foreach ( $plugin_tables as $table ) {
			// Skip storage table, because it is used for storing filter settings.
			if ( strpos( $table, 'fibofilters_storage' ) !== false ) {
				continue;
			}
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$wpdb->query( "DROP TABLE IF EXISTS {$table}" );
		}
	}

	/**
	 * Wipe options.
	 */
	private static function wipe_options() {
		global $wpdb;

		$wpdb->query( "DELETE FROM {$wpdb->prefix}options WHERE option_name LIKE 'fibofilters_indexer_last_build_%'" );
	}

	/**
	 * Wipe transients.
	 */
	private static function wipe_transients() {
		$transient_keys = [
			'fibofilters_sources_analyse_data',
			'fibofilters_dismissed_tests',
			'fibofilters_troubleshooting_async_tests_results',
		];
		foreach ( $transient_keys as $transient ) {
			delete_transient( $transient );
		}
	}

	/**
	 * Wipe Action Scheduler actions and its logs.
	 */
	private static function wipe_action_scheduler_logs() {
		global $wpdb;

		$action_ids = $wpdb->get_col( "SELECT action_id FROM {$wpdb->prefix}actionscheduler_actions WHERE hook = 'fibofilters/indexer/updater/background_product_update'" );
		if ( ! empty( $action_ids ) ) {
			$placeholders = array_fill( 0, count( $action_ids ), '%d' );
			$format       = implode( ', ', $placeholders );
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
			$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}actionscheduler_logs WHERE action_id IN ($format)", $action_ids ) );
		}
		$wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE hook = 'fibofilters/indexer/updater/background_product_update'" );
	}

	/**
	 * Wipe logs.
	 */
	private static function wipe_wc_logs() {
		if ( class_exists( 'WC_Log_Handler_File' ) ) {
			$wc_log_handler = new \WC_Log_Handler_File();
			foreach ( [ 'fibofilters-updater', 'fibofilters-indexer', 'fibofilters-fail-indexer' ] as $source ) {
				$files = $wc_log_handler->get_log_files();
				foreach ( $files as $handle => $filename ) {
					if ( strpos( $handle, $source ) !== false ) {
						$wc_log_handler->remove( $handle );
					}
				}
			}
		}
	}

	/**
	 * Wipe descriptors cache.
	 */
	private static function wipe_descriptors_cache() {
		/** @var \WP_Filesystem_Base $wp_filesystem */
		global $wp_filesystem;

		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . '/wp-admin/includes/file.php';
		}

		$upload_dir = wp_get_upload_dir();
		$cache_dir  = $upload_dir['basedir'] . '/fibofilters';

		if ( WP_Filesystem() && is_dir( $cache_dir ) ) {
			$wp_filesystem->rmdir( $cache_dir, true );
		}
	}
}
