<?php
/**
 * One-shot admin notices.
 *
 * @package TextTango
 */

declare( strict_types=1 );

namespace TextTango\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Carries messages across the redirect that follows a settings save.
 *
 * Scoped per user and short-lived, so one admin's message never surfaces on
 * another's screen.
 */
final class Notices {

	/**
	 * How long a queued notice survives.
	 */
	private const TTL = 60;

	/**
	 * Queue a notice for the current user.
	 *
	 * @param string $type    One of ok, warn, error.
	 * @param string $message Already-translated message.
	 */
	public static function add( string $type, string $message ): void {
		$key     = self::key();
		$notices = get_transient( $key );
		$notices = is_array( $notices ) ? $notices : array();

		$notices[] = array(
			'type'    => $type,
			'message' => $message,
		);

		set_transient( $key, $notices, self::TTL );
	}

	/**
	 * Read and clear the current user's queued notices.
	 *
	 * @return array<int, array{type: string, message: string}>
	 */
	public static function take(): array {
		$key     = self::key();
		$notices = get_transient( $key );

		delete_transient( $key );

		return is_array( $notices ) ? $notices : array();
	}

	/**
	 * Transient key for the current user.
	 */
	private static function key(): string {
		return 'texttango_notices_' . get_current_user_id();
	}
}
