<?php
/**
 * AdminNoticeHook class.
 *
 * Displays admin notices based on query params.
 *
 * @package Ilabs\Firevert\Core\Hooks\Admin
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Hooks\Admin;

/**
 * Class AdminNoticeHook
 *
 * Handles display of Firevert admin notices.
 */
final class AdminNoticeHook {

	/**
	 * Registers the hook.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_notices', array( $this, 'render_notices' ) );
	}

	/**
	 * Displays admin notices based on query args.
	 *
	 * @return void
	 */
	public function render_notices(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET['page'] ) || 'firevert' !== $_GET['page'] ) {
			return;
		}

		$this->render_module_disabled_notice();
		$this->render_form_validation_error_notice();
	}

	/**
	 * Prints a styled WordPress notice.
	 *
	 * @param string $message Message to display.
	 * @param string $type    Type of notice: success, warning, error, info.
	 *
	 * @return void
	 */
	private function print_notice( string $message, string $type = 'info' ): void {
		printf(
			'<div class="notice notice-%1$s"><p>%2$s</p></div>',
			esc_attr( $type ),
			esc_html( $message )
		);
	}

	/**
	 * Renders general module disabled admin notice based on firevert_module_disabled transient.
	 *
	 * @return void
	 */
	private function render_module_disabled_notice(): void {
		$notice = get_transient( 'firevert_module_disabled' );

		if ( $notice ) {
			delete_transient( 'firevert_module_disabled' );

			if ( true === (bool) $notice ) {
				$this->print_notice(
					__( 'Firevert: You must activate the module to access its settings.', 'firevert' ),
					'warning'
				);
			}
		}
	}

	/**
	 * Renders validation error notices stored in firevert_validation_errors transient.
	 *
	 * @return void
	 */
	private function render_form_validation_error_notice(): void {
		$errors = get_transient( 'firevert_validation_errors' );

		if ( ! is_array( $errors ) ) {
			return;
		}

		delete_transient( 'firevert_validation_errors' );

		foreach ( $errors as $field => $messages ) {
			foreach ( $messages as $message ) {
				$this->print_notice(
					sprintf(
						/* translators: %1$s: field name, %2$s: message */
						__( 'Validation error on %1$s: %2$s', 'firevert' ),
						ucfirst( str_replace( '_', ' ', $field ) ),
						$message
					),
					'error'
				);
			}
		}
	}
}
