<?php
/**
 * Admin notice manager for Restaurant Costing.
 *
 * Replaces rc_msg/rc_type URL param pattern with a transient-based
 * system that survives redirects and supports multiple simultaneous notices.
 *
 * @package RestaurantCosting
 */

declare(strict_types=1);

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

/**
 * Manages admin notices via transients.
 *
 * Usage:
 *   RC_Notice::success( 'Item saved.' );
 *   RC_Notice::error( 'Validation failed.' );
 *   RC_Notice::warning( 'File missing.' );
 *   RC_Notice::info( 'Import complete.' );
 */
final class RC_Notice {

	const SUCCESS = 'success';
	const ERROR   = 'error';
	const WARNING = 'warning';
	const INFO    = 'info';

	const TRANSIENT_KEY = 'rc_admin_notices';

	private static bool $registered = false;

	/**
	 * Register the admin_notices render hook (runs once).
	 */
	public static function register(): void {
		if ( self::$registered ) {
			return;
		}
		self::$registered = true;
		add_action( 'admin_notices', array( self::class, 'render' ) );
	}

	/**
	 * Add a notice to be displayed on the next admin page load.
	 */
	public static function add( string $message, string $type = self::INFO, bool $dismissible = true ): void {
		self::register();

		$notices   = get_transient( self::TRANSIENT_KEY ) ?: array();
		$notices[] = array(
			'message'     => $message,
			'type'        => $type,
			'dismissible' => $dismissible,
		);
		set_transient( self::TRANSIENT_KEY, $notices, 120 );
	}

	/**
	 * Render all pending notices and clear them.
	 */
	public static function render(): void {
		$notices = get_transient( self::TRANSIENT_KEY );
		if ( empty( $notices ) || ! is_array( $notices ) ) {
			return;
		}
		delete_transient( self::TRANSIENT_KEY );

		foreach ( $notices as $notice ) {
			$type        = isset( $notice['type'] ) && in_array( $notice['type'], array( self::SUCCESS, self::ERROR, self::WARNING, self::INFO ), true ) ? $notice['type'] : self::INFO;
			$dismissible = ! empty( $notice['dismissible'] ) ? ' is-dismissible' : '';
			$message     = $notice['message'] ?? '';
			if ( '' === $message ) {
				continue;
			}
			printf(
				'<div class="notice notice-%s%s"><p>%s</p></div>',
				esc_attr( $type ),
				$dismissible,
				esc_html( $message )
			);
		}
	}

	public static function success( string $message, bool $dismissible = true ): void {
		self::add( $message, self::SUCCESS, $dismissible );
	}

	public static function error( string $message, bool $dismissible = true ): void {
		self::add( $message, self::ERROR, $dismissible );
	}

	public static function warning( string $message, bool $dismissible = true ): void {
		self::add( $message, self::WARNING, $dismissible );
	}

	public static function info( string $message, bool $dismissible = true ): void {
		self::add( $message, self::INFO, $dismissible );
	}
}
