<?php
/**
 * BaseCloud Boost — Deactivator
 *
 * @package BaseCloud\Boost
 */

declare( strict_types=1 );

namespace BaseCloud\Boost;

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

/**
 * Handles plugin deactivation tasks.
 */
class Deactivator {

	/**
	 * Run deactivation tasks.
	 *
	 * @return void
	 */
	public static function deactivate(): void {
		self::remove_advanced_cache();
		self::clear_all_cache();
		self::unschedule_cron();
	}

	/**
	 * Remove the advanced-cache.php drop-in.
	 *
	 * @return void
	 */
	private static function remove_advanced_cache(): void {
		$drop_in = WP_CONTENT_DIR . '/advanced-cache.php';

		if ( file_exists( $drop_in ) ) {
			$content = file_get_contents( $drop_in );
			// Only remove if it's ours.
			if ( $content !== false && strpos( $content, 'BaseCloud Boost' ) !== false ) {
				unlink( $drop_in );
			}
		}

		// Disable WP_CACHE constant.
		self::disable_wp_cache_constant();
	}

	/**
	 * Set WP_CACHE to false in wp-config.php.
	 *
	 * @return void
	 */
	private static function disable_wp_cache_constant(): void {
		$config_file = ABSPATH . 'wp-config.php';

		if ( ! file_exists( $config_file ) || ! is_writable( $config_file ) ) {
			return;
		}

		$config = file_get_contents( $config_file );

		if ( $config !== false ) {
			$config = preg_replace(
				"/define\s*\(\s*['\"]WP_CACHE['\"]\s*,\s*true\s*\)\s*;?\s*\/\/\s*Added by BaseCloud Boost\n?/",
				'',
				$config
			);
			file_put_contents( $config_file, $config );
		}
	}

	/**
	 * Clear all cached pages.
	 *
	 * @return void
	 */
	private static function clear_all_cache(): void {
		if ( ! is_dir( BCBOOST_CACHE_DIR ) ) {
			return;
		}

		$iterator = new \RecursiveIteratorIterator(
			new \RecursiveDirectoryIterator( BCBOOST_CACHE_DIR, \FilesystemIterator::SKIP_DOTS ),
			\RecursiveIteratorIterator::CHILD_FIRST
		);

		foreach ( $iterator as $item ) {
			/** @var \SplFileInfo $item */
			$item->isDir() ? rmdir( $item->getPathname() ) : unlink( $item->getPathname() );
		}
	}

	/**
	 * Unschedule all plugin cron events.
	 *
	 * @return void
	 */
	private static function unschedule_cron(): void {
		$hooks = [ 'BCBOOST_expire_cache', 'BCBOOST_preload_batch', 'BCBOOST_minify_cache_cleanup', 'BCBOOST_webhook_daily', 'BCBOOST_lighthouse_daily', 'BCBOOST_db_cleanup' ];
		foreach ( $hooks as $hook ) {
			wp_clear_scheduled_hook( $hook );
		}
	}
}
