<?php

use WP_science\Engine\Optimization\RUCSS\Database\Tables\UsedCSS;

use WP_science\Engine\Preload\Database\Tables\Cache;

/**
 * Manages the deletion of WP science data and files on uninstall.
 */
class WPscienceUninstall {

	/**
	 * Path to the cache folder.
	 *
	 * @var string
	 */
	private $cache_path;

	/**
	 * Path to the config folder.
	 *
	 * @var string
	 */
	private $config_path;

	/**
	 * WP science options.
	 *
	 * @var array
	 */
	private $options = [
		'wp_science_settings',
		'science_analytics_notice_displayed',
		'sciencecdn_user_token',
		'sciencecdn_process',
		'wp_science_hide_deactivation_form',
		'wp_science_last_base_url',
		'wp_science_no_licence',
		'wp_science_last_option_hash',
	];

	/**
	 * WP science transients.
	 *
	 * @var array
	 */
	private $transients = [
		'wp_science_customer_data',
		'science_notice_missing_tags',
		'science_clear_cache',
		'science_check_key_errors',
		'science_send_analytics_data',
		'science_critical_css_generation_process_running',
		'science_critical_css_generation_process_complete',
		'science_critical_css_generation_triggered',
		'sciencecdn_status',
		'sciencecdn_pricing',
		'sciencecdn_purge_cache_response',
		'science_cloudflare_ips',
		'science_cloudflare_is_api_keys_valid',
		'science_preload_triggered',
		'science_preload_complete',
		'science_preload_complete_time',
		'science_preload_errors',
		'science_database_optimization_process',
		'science_database_optimization_process_complete',
		'science_hide_deactivation_form',
		'wpr_preload_running',
		'science_preload_as_tables_count',
		'wpr_dynamic_lists',
		'wpr_dynamic_lists_delayjs',
		'science_domain_changed',
		'wp_science_rucss_errors_count',
		'wpr_dynamic_lists_incompatible_plugins',
		'science_divi_notice',
	];

	/**
	 * WP science scheduled events.
	 *
	 * @var array
	 */
	private $events = [
		'science_purge_time_event',
		'science_database_optimization_time_event',
		'science_cache_dir_size_check',
		'sciencecdn_check_subscription_status_event',
		'science_cron_deactivate_cloudflare_devmode',
	];

	/**
	 * WP science cache directories.
	 *
	 * @var array
	 */
	private $cache_dirs = [
		'wordpress',
		'min',
		'busting',
		'critical-css',
		'used-css',
	];

	/**
	 * WP science Post MetaData Entries
	 *
	 * @var array
	 */
	private $post_meta = [
		'minify_css',
		'minify_js',
		'cdn',
		'lazyload',
		'lazyload_iframes',
		'async_css',
		'defer_all_js',
		'delay_js',
		'remove_unused_css',
		'lazyload_css_bg_img',
	];

	/**
	 * Instance of RUCSS used_css table.
	 *
	 * @var WP_science\Engine\Optimization\RUCSS\Database\Tables\UsedCSS
	 */
	private $rucss_usedcss_table;

	/**
	 * Instance of Preload science_cache table.
	 *
	 * @var Cache
	 */
	private $science_cache;

	/**
	 * Constructor.
	 *
	 * @param string  $cache_path            Path to the cache folder.
	 * @param string  $config_path           Path to the config folder.
	 * @param UsedCSS $rucss_usedcss_table   RUCSS used_css table.
	 * @param Cache   $science_cache   Preload science_cache table.
	 */
	public function __construct( $cache_path, $config_path, $rucss_usedcss_table, $science_cache ) {
		$this->cache_path          = trailingslashit( $cache_path );
		$this->config_path         = $config_path;
		$this->rucss_usedcss_table = $rucss_usedcss_table;
		$this->science_cache        = $science_cache;
	}

	/**
	 * Deletes all plugin data and files on uninstall.
	 *
	 * @since 3.5.2
	 * @author Remy Perona
	 *
	 * @return void
	 */
	public function uninstall() {
		$this->delete_plugin_data();
		$this->delete_cache_files();
		$this->delete_config_files();
		$this->drop_rucss_database_tables();
		$this->delete_preload_table();
	}

	/**
	 * Drop RUCSS database tables.
	 *
	 * @return void
	 */
	private function drop_rucss_database_tables() {
		// If the table exist, then drop the table.
		$this->drop_rucss_current_site_tables();

		if ( ! is_multisite() ) {
			return;
		}

		foreach ( get_sites( [ 'fields' => 'ids' ] ) as $site_id ) {
			switch_to_blog( $site_id );

			$this->drop_rucss_current_site_tables();

			restore_current_blog();
		}
	}

	/**
	 * Drop RUCSS tables for current active site.
	 */
	private function drop_rucss_current_site_tables() {
		if ( $this->rucss_usedcss_table->exists() ) {
			$this->rucss_usedcss_table->uninstall();
		}
	}

	/**
	 * Deletes WP science options, transients and events.
	 *
	 * @since 3.5.2
	 * @author Remy Perona
	 *
	 * @return void
	 */
	private function delete_plugin_data() {
		delete_site_transient( 'wp_science_update_data' );

		// Delete all user meta related to WP science.
		delete_metadata( 'user', '', 'science_boxes', '', true );

		// Delete all post meta related to WP science.
		foreach ( $this->post_meta as $post_meta ) {
			delete_post_meta_by_key( "_science_exclude_{$post_meta}" );
		}

		array_walk( $this->transients, 'delete_transient' );
		array_walk( $this->options, 'delete_option' );

		foreach ( $this->events as $event ) {
			wp_clear_scheduled_hook( $event );
		}
	}

	/**
	 * Deletes all WP science cache files.
	 *
	 * @since 3.5.2
	 * @author Remy Perona
	 *
	 * @return void
	 */
	private function delete_cache_files() {
		foreach ( $this->cache_dirs as $dir ) {
			$this->delete( $this->cache_path . $dir );
		}
	}

	/**
	 * Deletes all WP science config files.
	 *
	 * @since 3.5.2
	 * @author Remy Perona
	 *
	 * @return void
	 */
	private function delete_config_files() {
		$this->delete( $this->config_path );
	}

	/**
	 * Drop preload tables.
	 */
	private function delete_preload_table() {
		// If the table exist, then drop the table.

		if ( $this->science_cache->exists() ) {
			$this->science_cache->uninstall();
		}

		if ( ! is_multisite() ) {
			return;
		}

		foreach ( get_sites( [ 'fields' => 'ids' ] ) as $site_id ) {
			switch_to_blog( $site_id );

			if ( $this->science_cache->exists() ) {
				$this->science_cache->uninstall();
			}

			restore_current_blog();
		}
	}

	/**
	 * Recursively deletes files and directories.
	 *
	 * @since 3.5.2
	 * @author Remy Perona
	 *
	 * @param string $file Path to file or directory.
	 */
	private function delete( $file ) {
		if ( ! is_dir( $file ) ) {
			wp_delete_file( $file );
			return;
		}

		try {
			$iterator = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator( $file, FilesystemIterator::SKIP_DOTS ),
				RecursiveIteratorIterator::CHILD_FIRST
			);
		} catch ( UnexpectedValueException $e ) {
			return;
		}

		foreach ( $iterator as $item ) {
			if ( $item->isDir() ) {
				@rmdir( $item ); //phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_rmdir

				continue;
			}

			wp_delete_file( $item );
		}

		@rmdir( $file ); //phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
	}
}
