<?php
/**
 * Admin notification system.
 *
 * @package Kutby
 * @since   2.5.0
 */

declare(strict_types=1);

namespace Kutby\Admin\Notifications;

use Kutby\Admin\UI\Components;

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

/**
 * Class Notices
 */
final class Notices {

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

	/**
	 * Transient key for flash notices.
	 */
	private const FLASH_KEY = 'kutby_admin_notice';

	/**
	 * Queue a flash notice for the next admin page load.
	 *
	 * @param string $message  Message (Arabic).
	 * @param string $type     Type.
	 * @param bool   $autohide Auto-hide.
	 * @return void
	 */
	public static function flash( string $message, string $type = self::SUCCESS, bool $autohide = true ): void {
		set_transient(
			self::FLASH_KEY . '_' . get_current_user_id(),
			array(
				'message'  => $message,
				'type'     => $type,
				'autohide' => $autohide,
			),
			60
		);
	}

	/**
	 * Render and clear flash notice.
	 *
	 * @return void
	 */
	public static function render_flash(): void {
		$key  = self::FLASH_KEY . '_' . get_current_user_id();
		$data = get_transient( $key );
		if ( ! is_array( $data ) || empty( $data['message'] ) ) {
			return;
		}
		delete_transient( $key );
		Components::notice(
			(string) $data['message'],
			(string) ( $data['type'] ?? self::SUCCESS ),
			true,
			! empty( $data['autohide'] )
		);
	}

	/**
	 * Immediate notice.
	 *
	 * @param string $message  Message.
	 * @param string $type     Type.
	 * @param bool   $dismiss  Dismissible.
	 * @param bool   $autohide Auto-hide.
	 * @return void
	 */
	public static function render( string $message, string $type = self::SUCCESS, bool $dismiss = false, bool $autohide = false ): void {
		Components::notice( $message, $type, $dismiss, $autohide );
	}
}
