<?php
/**
 * BaseCloud Boost — Uninstall
 *
 * Runs when the plugin is deleted from the WordPress admin.
 *
 * @package BaseCloud\Boost
 */

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

// ─── Helper: recursively delete a directory ────────────────────────────────────

function BCBOOST_uninstall_rmdir( string $dir ): void {
	if ( ! is_dir( $dir ) ) {
		return;
	}
	$iterator = new RecursiveIteratorIterator(
		new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS ),
		RecursiveIteratorIterator::CHILD_FIRST
	);
	foreach ( $iterator as $item ) {
		$item->isDir() ? rmdir( $item->getPathname() ) : unlink( $item->getPathname() );
	}
	rmdir( $dir );
}

// ─── Remove page cache files ───────────────────────────────────────────────────

BCBOOST_uninstall_rmdir( WP_CONTENT_DIR . '/cache/basecloud-boost/' );

// ─── Remove minify cache files ─────────────────────────────────────────────────

BCBOOST_uninstall_rmdir( WP_CONTENT_DIR . '/cache/basecloud-boost-min/' );

// ─── Remove advanced-cache.php drop-in ────────────────────────────────────────

$drop_in = WP_CONTENT_DIR . '/advanced-cache.php';
if ( file_exists( $drop_in ) ) {
	$content = file_get_contents( $drop_in );
	if ( $content !== false && strpos( $content, 'BaseCloud Boost' ) !== false ) {
		unlink( $drop_in );
	}
}

// ─── Remove WP_CACHE constant from wp-config.php ──────────────────────────────

$config_file = ABSPATH . 'wp-config.php';
if ( file_exists( $config_file ) && is_writable( $config_file ) ) {
	$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 );
	}
}

// ─── Remove WP options ────────────────────────────────────────────────────────

delete_option( 'BCBOOST_options' );
delete_option( 'BCBOOST_preload_queue' );
delete_option( 'BCBOOST_preload_progress' );
delete_option( 'BCBOOST_critical_css' );
delete_option( 'bcboost_compress_progress' );
delete_option( 'bcboost_compress_stats' );
delete_option( 'bcboost_version' );

// ─── Unschedule all cron events ───────────────────────────────────────────────

wp_clear_scheduled_hook( 'BCBOOST_expire_cache' );
wp_clear_scheduled_hook( 'BCBOOST_preload_batch' );
wp_clear_scheduled_hook( 'BCBOOST_minify_cache_cleanup' );
wp_clear_scheduled_hook( 'BCBOOST_webhook_daily' );
