<?php
/**
 * Module enable/disable lifecycle cleanup.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

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

/**
 * Centralizes side effects when modules are toggled on or off.
 */
final class ModuleLifecycleListener {

	public static function init(): void {
		add_action( 'wp_powersuite_module_toggled', [ self::class, 'handleModuleToggled' ], 10, 3 );
	}

	/**
	 * @param string               $module_id
	 * @param bool                 $enable
	 * @param array<string, mixed> $module_metadata
	 */
	public static function handleModuleToggled( string $module_id, bool $enable, array $module_metadata = [] ): void {
		unset( $module_metadata );

		if ( $module_id === 'download-media-library' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'wpps_dml_cleanup_expired_zips' );
				delete_transient( 'wpps_dml_stats_cache' );
				return;
			}
			if ( ! wp_next_scheduled( 'wpps_dml_cleanup_expired_zips' ) ) {
				wp_schedule_event( time(), 'hourly', 'wpps_dml_cleanup_expired_zips' );
			}
			return;
		}

		if ( $module_id === 'track-404s' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_track_404s_cleanup' );
			return;
		}

		if ( $module_id === 'broken-link-checker' && ! $enable ) {
			delete_transient( 'wpps_blc_scan_lock_' . get_current_user_id() );
			return;
		}

		if ( $module_id === 'redirect-manager' && ! $enable ) {
			delete_transient( 'wp_powersuite_redirect_rules' );
			return;
		}

		if ( $module_id === 'link-shortener' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'wpps_link_shortener_analytics_cleanup' );
				set_transient( 'wpps_link_shortener_flush_rewrite', 1, 60 );
				return;
			}
			if ( ! wp_next_scheduled( 'wpps_link_shortener_analytics_cleanup' ) ) {
				wp_schedule_event( time(), 'daily', 'wpps_link_shortener_analytics_cleanup' );
			}
			return;
		}

		if ( $module_id === 'coming-soon-maintenance' && ! $enable ) {
			$repo     = OptionStoreModuleSettingsRepository::forModule( 'coming-soon-maintenance' );
			$settings = $repo->all( [] );
			$settings['enabled'] = 0;
			$repo->save( $settings );
			if ( ! class_exists( \ComingSoonMaintenance\Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'coming-soon-maintenance' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( \ComingSoonMaintenance\Module::class, false ) ) {
				\ComingSoonMaintenance\Module::purgeCaches();
			}
			return;
		}

		if ( $module_id === 'content-expiration' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_content_expiration_check' );
			delete_transient( 'wpps_expiration_cron_checked' );
			delete_transient( 'wpps_ce_admin_scan' );
			delete_transient( 'wpps_ce_run_lock' );
			return;
		}

		if ( $module_id === 'backup-restore' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_br_scheduled_backup' );
			if ( class_exists( \BackupRestore\Includes\BackupService::class, false ) ) {
				delete_transient( \BackupRestore\Includes\BackupService::TRANSIENT_CRON_BACKUP_JOB );
			} else {
				delete_transient( 'wpps_br_cron_backup_job_v1' );
			}
			return;
		}

		if ( $module_id === 'avif-conversion' && ! $enable ) {
			wp_clear_scheduled_hook( 'wp_powersuite_avif_process_attachment' );
			delete_transient( 'wp_powersuite_avif_library_summary_v1' );
			delete_transient( 'wp_powersuite_avif_restorable_count_v1' );
			return;
		}

		if ( $module_id === 'system-summary' && ! $enable ) {
			delete_transient( 'wpps_system_summary_widget' );
			return;
		}

		if ( $module_id === 'auto-publish-missed-schedule' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_auto_publish_missed_schedule' );
			delete_transient( 'wpps_missed_schedule_last_check' );
			delete_transient( 'wpps_missed_schedule_last_check_front' );
			delete_transient( 'wpps_missed_schedule_cron_guard' );
			delete_transient( 'wpps_missed_schedule_running' );
			return;
		}

		if ( $module_id === 'temporary-login' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'tl_cleanup_expired_logins' );
				wp_clear_scheduled_hook( 'tl_cleanup_activity_logs' );
				self::loadTemporaryLoginModule();
				if ( class_exists( \TemporaryLogin\Module::class, false ) ) {
					\TemporaryLogin\Module::cleanupOnDisable();
				}
				return;
			}

			if ( class_exists( 'TemporaryLogin\\Module' ) ) {
				$module = ModuleManager::getInstance()->getModule( 'temporary-login' );
				if ( $module instanceof \TemporaryLogin\Module ) {
					delete_option( 'wpps_tl_db_ready' );
					$module->setupDatabase();
				}
			}
			if ( ! wp_next_scheduled( 'tl_cleanup_activity_logs' ) ) {
				wp_schedule_event( time(), 'daily', 'tl_cleanup_activity_logs' );
			}
			if ( ! wp_next_scheduled( 'tl_cleanup_expired_logins' ) ) {
				wp_schedule_event( time(), 'hourly', 'tl_cleanup_expired_logins' );
			}
			return;
		}

		if ( $module_id === 'login-as-user' && ! $enable ) {
			self::loadLoginAsUserModule();
			if ( class_exists( \LoginAsUser\Module::class, false ) ) {
				\LoginAsUser\Module::cleanupOnDisable();
			} else {
				wp_clear_scheduled_hook( 'wpps_login_as_cleanup_sessions' );
			}
			return;
		}

		if ( $module_id === 'database-cleanup' && ! $enable ) {
			if ( ! class_exists( \DatabaseCleanup\Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'database-cleanup' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( \DatabaseCleanup\Module::class, false ) ) {
				\DatabaseCleanup\Module::cleanupOnDisable();
			} else {
				wp_clear_scheduled_hook( 'wpps_dc_scheduled_cleanup' );
				wp_clear_scheduled_hook( 'wpps_dc_scheduled_cleanup_continue' );
				if ( class_exists( \DatabaseCleanup\Includes\Database_Cleaner::class, false ) ) {
					\DatabaseCleanup\Includes\Database_Cleaner::clear_all_runtime_state();
				}
			}
			return;
		}

		if ( $module_id === 'database-cleanup' && $enable ) {
			if ( ! class_exists( \DatabaseCleanup\Includes\Database_Cleaner::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'database-cleanup' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( \DatabaseCleanup\Includes\Database_Cleaner::class, false ) ) {
				\DatabaseCleanup\Includes\Database_Cleaner::clear_all_runtime_state();
			}
			return;
		}

		if ( $module_id === 'login-session-manager' && ! $enable ) {
			if ( ! class_exists( \LoginSessionManager\Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'login-session-manager' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( \LoginSessionManager\Module::class, false ) ) {
				\LoginSessionManager\Module::cleanupOnDisable();
			}
			return;
		}

		if ( $module_id === 'login-email-notification' && ! $enable ) {
			if ( ! class_exists( \LoginEmailNotification\Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'login-email-notification' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( \LoginEmailNotification\Module::class, false ) ) {
				\LoginEmailNotification\Module::clearGeoTransients();
			}
			return;
		}

		if ( $module_id === 'two-factor-authentication' && ! $enable ) {
			if ( class_exists( \TwoFactorAuthentication\Module::class, false ) ) {
				\TwoFactorAuthentication\Module::clearPendingSessionTransients();
			}
			return;
		}

		if ( $module_id === ApplicationPasswordConflictPolicy::MODULE_DISABLE_APP_PASSWORDS && $enable ) {
			ApplicationPasswordConflictPolicy::clearTwoFactorRestrictWhenDisableEnabled();
			AdminNotices::queueDisableApplicationPasswordsEnabledNotice( get_current_user_id() );
			return;
		}

		if ( $module_id === 'disable-password-reset' && $enable ) {
			AdminNotices::queueDisablePasswordResetEnabledNotice( get_current_user_id() );
			return;
		}

		if ( $module_id === 'magic-login' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'wpps_magic_links_cleanup' );
				return;
			}

			if ( ! wp_next_scheduled( 'wpps_magic_links_cleanup' ) ) {
				wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpps_magic_links_cleanup' );
			}

			delete_option( 'wpps_ml_db_ready' );
			if ( class_exists( 'MagicLogin\\Module' ) ) {
				$module = ModuleManager::getInstance()->getModule( 'magic-login' );
				if ( $module instanceof \MagicLogin\Module ) {
					$module->maybeInstallTable();
				}
			}
			return;
		}

		if ( $module_id === 'ai-alt-text-generator' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_ai_alt_purge_logs' );
			wp_clear_scheduled_hook( 'wpps_ai_alt_process_queue' );
			wp_clear_scheduled_hook( 'wpps_ai_alt_scheduled_scan' );
			delete_option( 'wpps_ai_alt_queue' );
			delete_transient( 'wpps_ai_alt_scan_summary_v2' );
			delete_transient( 'wpps_ai_alt_duplicates_v1' );
			delete_transient( 'wpps_ai_alt_content_scan_v1' );
			delete_option( 'wpps_ai_alt_content_scan_progress' );
			delete_transient( 'wpps_ai_alt_perf_v1' );
			wp_clear_scheduled_hook( 'wpps_ai_alt_content_scan_batch' );
		}

		if ( $module_id === 'obfuscate-author-slugs' && ! $enable ) {
			wp_clear_scheduled_hook( 'wpps_author_slugs_backfill_batch' );
			delete_transient( 'wpps_author_slugs_generated' );
			delete_transient( 'wpps_author_slugs_batch_lock' );
			if ( class_exists( \ObfuscateAuthorSlugs\Module::class, false ) ) {
				\ObfuscateAuthorSlugs\Module::clearObfuscatedSlugs();
			}
			return;
		}

		if ( $module_id === 'password-protection' && ! $enable ) {
			if ( ! class_exists( '\PasswordProtection\Module' ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
				$mod = WP_POWERSUITE_MODULES_DIR . 'password-protection' . DIRECTORY_SEPARATOR . 'module.php';
				if ( is_readable( $mod ) ) {
					require_once $mod;
				}
			}
			if ( class_exists( '\PasswordProtection\Module' ) ) {
				\PasswordProtection\Module::clearAllRateLimitTransients();
			}
			return;
		}

		if ( $module_id === 'limit-login-attempts' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'wpps_login_attempts_prune' );
				if ( class_exists( 'LimitLoginAttempts\\Module' ) ) {
					\LimitLoginAttempts\Module::clearAllLockoutTransients();
				}
				return;
			}

			if ( ! wp_next_scheduled( 'wpps_login_attempts_prune' ) ) {
				wp_schedule_event( time(), 'daily', 'wpps_login_attempts_prune' );
			}
			return;
		}

		if ( $module_id === 'disable-auto-embeds' && $enable ) {
			flush_rewrite_rules( false );
			return;
		}

		if ( $module_id === 'email-logs' ) {
			if ( ! $enable ) {
				wp_clear_scheduled_hook( 'wpps_email_logs_prune' );
				return;
			}
			if ( ! wp_next_scheduled( 'wpps_email_logs_prune' ) ) {
				wp_schedule_event( time(), 'daily', 'wpps_email_logs_prune' );
			}
			return;
		}

		if ( $module_id === 'email-reports' ) {
			if ( ! $enable ) {
				self::loadEmailReportsService();
				if ( class_exists( \EmailReports\Includes\ReportService::class, false ) ) {
					\EmailReports\Includes\ReportService::clearScheduledHooks();
				} else {
					wp_clear_scheduled_hook( 'wpps_email_reports_daily' );
					wp_clear_scheduled_hook( 'wpps_email_reports_weekly' );
					wp_clear_scheduled_hook( 'wpps_email_reports_monthly' );
				}
				return;
			}

			self::loadEmailReportsService();
			if ( class_exists( \EmailReports\Includes\ReportService::class, false ) ) {
				\EmailReports\Includes\ReportService::scheduleReports();
			}
			return;
		}

		if ( $module_id === 'disable-all-updates' ) {
			self::loadDisableAllUpdatesModule();

			if ( ! $enable ) {
				\DisableAllUpdates\Module::restoreWordPressUpdateCronEvents();
				return;
			}

			$settings = OptionStoreModuleSettingsRepository::forModule( 'disable-all-updates' )->all( [] );
			\DisableAllUpdates\Module::syncUpdateCronSchedule(
				\DisableAllUpdates\Module::sanitizeSettings( is_array( $settings ) ? $settings : [] )
			);
		}
	}

	private static function loadLoginAsUserModule(): void {
		if ( class_exists( \LoginAsUser\Module::class, false ) ) {
			return;
		}

		if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			return;
		}

		$module_file = WP_POWERSUITE_MODULES_DIR . 'login-as-user' . DIRECTORY_SEPARATOR . 'module.php';
		if ( is_readable( $module_file ) ) {
			require_once $module_file;
		}
	}

	private static function loadTemporaryLoginModule(): void {
		if ( class_exists( \TemporaryLogin\Module::class, false ) ) {
			return;
		}

		if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			return;
		}

		$module_file = WP_POWERSUITE_MODULES_DIR . 'temporary-login' . DIRECTORY_SEPARATOR . 'module.php';
		if ( is_readable( $module_file ) ) {
			require_once $module_file;
		}
	}

	private static function loadDisableAllUpdatesModule(): void {
		if ( class_exists( \DisableAllUpdates\Module::class, false ) ) {
			return;
		}

		if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			return;
		}

		$module_file = WP_POWERSUITE_MODULES_DIR . 'disable-all-updates' . DIRECTORY_SEPARATOR . 'module.php';
		if ( is_readable( $module_file ) ) {
			require_once $module_file;
		}
	}

	private static function loadEmailReportsService(): void {
		if ( class_exists( \EmailReports\Includes\ReportService::class, false ) ) {
			return;
		}

		if ( ! defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
			return;
		}

		$service_file = WP_POWERSUITE_MODULES_DIR . 'email-reports' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'ReportService.php';
		if ( is_readable( $service_file ) ) {
			require_once $service_file;
		}
	}
}
