<?php
/**
 * Retire the Backup & Restore module when its directory has been removed.
 *
 * Kept outside the module tree so cleanup still runs after the module folder is deleted.
 *
 * @package WP_PowerSuite
 * @since 1.10.2
 */

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

/**
 * When the Backup & Restore module directory is absent, drop it from enabled list, favorites,
 * order, clear its cron event, and flush module metadata cache.
 */
function wp_powersuite_retire_backup_restore_module_run(): void {
	if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) || is_dir( WP_POWERSUITE_MODULES_DIR . 'backup-restore' ) ) {
		return;
	}
	if ( ! function_exists( 'wp_powersuite_load_bootstrap' ) || ! wp_powersuite_load_bootstrap() ) {
		return;
	}
	if ( ! function_exists( 'wp_powersuite_register_autoloader' ) || ! wp_powersuite_register_autoloader() ) {
		return;
	}
	if ( ! class_exists( \WP_PowerSuite\Core\OptionStore::class, true ) ) {
		return;
	}

	$store = \WP_PowerSuite\Core\OptionStore::getInstance();
	$store->disableModule( 'backup-restore' );

	$favorites = $store->getFavorites();
	if ( in_array( 'backup-restore', $favorites, true ) ) {
		$store->setFavorites( array_values( array_diff( $favorites, [ 'backup-restore' ] ) ) );
	}

	$order = $store->getModuleOrder();
	if ( in_array( 'backup-restore', $order, true ) ) {
		$store->setModuleOrder( array_values( array_diff( $order, [ 'backup-restore' ] ) ) );
	}

	wp_clear_scheduled_hook( 'wpps_br_scheduled_backup' );

	if ( class_exists( \WP_PowerSuite\Core\DataRegistry::class, true ) ) {
		\WP_PowerSuite\Core\DataRegistry::clearCaches();
	}
}
