<?php
/**
 * PowerSuite admin notices.
 *
 * @package WP_PowerSuite\Core
 * @since 1.0.0
 */

namespace WP_PowerSuite\Core;

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

final class AdminNotices {

	public static function init(): void {
		add_action( 'admin_notices', [ self::class, 'renderModuleCapNotice' ] );
		add_action( 'admin_notices', [ self::class, 'renderDisableApplicationPasswordsNotice' ] );
		add_action( 'admin_notices', [ self::class, 'renderDisablePasswordResetNotice' ] );
	}

	private const DISABLE_APP_PASSWORDS_NOTICE_TRANSIENT = 'wpps_dap_enabled_notice_';

	private const DISABLE_PASSWORD_RESET_NOTICE_TRANSIENT = 'wpps_dpr_enabled_notice_';

	/**
	 * Show a one-time admin notice after Disable Application Passwords is enabled.
	 */
	public static function queueDisableApplicationPasswordsEnabledNotice( int $user_id ): void {
		if ( $user_id <= 0 ) {
			return;
		}

		set_transient( self::DISABLE_APP_PASSWORDS_NOTICE_TRANSIENT . $user_id, '1', WEEK_IN_SECONDS );
	}

	/**
	 * Show a one-time admin notice after Disable Password Reset is enabled.
	 */
	public static function queueDisablePasswordResetEnabledNotice( int $user_id ): void {
		if ( $user_id <= 0 ) {
			return;
		}

		set_transient( self::DISABLE_PASSWORD_RESET_NOTICE_TRANSIENT . $user_id, '1', WEEK_IN_SECONDS );
	}

	public static function renderModuleCapNotice(): void {
		if ( ! self::isPowerSuiteAdminPage() ) {
			return;
		}

		$warning = get_transient( ModuleManager::MODULE_CAP_WARNING_TRANSIENT );
		if ( ! is_array( $warning ) || empty( $warning['modules'] ) || ! is_array( $warning['modules'] ) ) {
			return;
		}

		$cap     = isset( $warning['cap'] ) ? (int) $warning['cap'] : 0;
		$modules = array_values( array_filter( array_map( 'strval', $warning['modules'] ) ) );
		if ( $modules === [] ) {
			return;
		}

		$registry = ModuleRegistry::getInstance();
		$registry->init();
		$labels = [];
		foreach ( $modules as $module_id ) {
			$meta     = $registry->getModuleMetadata( $module_id );
			$labels[] = $meta['name'] ?? $module_id;
		}

		printf(
			'<div class="notice notice-warning is-dismissible"%1$s><p><strong>%2$s</strong> %3$s</p></div>',
			function_exists( 'wp_powersuite_plugin_notice_attr' ) ? wp_powersuite_plugin_notice_attr() : '',
			esc_html( WhiteLabel::pluginName() ),
			esc_html(
				sprintf(
					/* translators: 1: module load cap, 2: comma-separated module names */
					_n(
						'Only %1$d modules can load per request. The following enabled module was skipped: %2$s.',
						'Only %1$d modules can load per request. The following enabled modules were skipped: %2$s.',
						count( $labels ),
						'wp-powersuite'
					),
					$cap,
					implode( ', ', $labels )
				)
			)
		);
	}

	public static function renderDisableApplicationPasswordsNotice(): void {
		if ( ! self::isPowerSuiteAdminPage() || ! NetworkScope::canManagePlugin() ) {
			return;
		}

		if ( ! ApplicationPasswordConflictPolicy::isDisableApplicationPasswordsEnabled() ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( $user_id > 0 ) {
			$notice_key = self::DISABLE_APP_PASSWORDS_NOTICE_TRANSIENT . $user_id;
			if ( get_transient( $notice_key ) ) {
				delete_transient( $notice_key );
				printf(
					'<div class="notice notice-info is-dismissible"%1$s><p><strong>%2$s</strong> %3$s</p></div>',
					function_exists( 'wp_powersuite_plugin_notice_attr' ) ? wp_powersuite_plugin_notice_attr() : '',
					esc_html__( 'Application Passwords are disabled', 'wp-powersuite' ),
					esc_html__(
						'REST/XML-RPC login with application tokens is blocked on this site. Normal login and cookie-based REST access are unaffected.',
						'wp-powersuite'
					)
				);
			}
		}

		if ( ApplicationPasswordConflictPolicy::hasRuntimeConflict() ) {
			printf(
				'<div class="notice notice-error"%1$s><p><strong>%2$s</strong> %3$s</p></div>',
				function_exists( 'wp_powersuite_plugin_notice_attr' ) ? wp_powersuite_plugin_notice_attr() : '',
				esc_html__( 'Configuration conflict', 'wp-powersuite' ),
				esc_html__(
					'2-Factor Authentication is configured to require application passwords for REST/XML-RPC, but Application Passwords are disabled. Enforced roles cannot use the REST API or XML-RPC until you turn off one of these options.',
					'wp-powersuite'
				)
			);
		}
	}

	public static function renderDisablePasswordResetNotice(): void {
		if ( ! self::isPowerSuiteAdminPage() || ! NetworkScope::canManagePlugin() ) {
			return;
		}

		if ( ! OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-password-reset' ) ) {
			return;
		}

		$user_id = get_current_user_id();
		if ( $user_id <= 0 ) {
			return;
		}

		$notice_key = self::DISABLE_PASSWORD_RESET_NOTICE_TRANSIENT . $user_id;
		if ( ! get_transient( $notice_key ) ) {
			return;
		}

		delete_transient( $notice_key );

		printf(
			'<div class="notice notice-warning is-dismissible"%1$s><p><strong>%2$s</strong> %3$s</p></div>',
			function_exists( 'wp_powersuite_plugin_notice_attr' ) ? wp_powersuite_plugin_notice_attr() : '',
			esc_html__( 'Password reset is disabled for visitors', 'wp-powersuite' ),
			esc_html__(
				'Public “forgot password” flows are blocked. Users cannot recover accounts by email on their own. Use user profile password fields, admin reset links (if enabled in module settings), or WP-CLI for recovery.',
				'wp-powersuite'
			)
		);
	}

	private static function isPowerSuiteAdminPage(): bool {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && is_string( $screen->id ) && str_contains( $screen->id, 'powersuite' ) ) {
			return true;
		}

		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( (string) $_GET['page'] ) ) : '';
		return $page !== '' && ( str_starts_with( $page, 'powersuite' ) || str_starts_with( $page, 'wpps-' ) );
	}
}
