<?php
declare(strict_types=1);

namespace App\Core\Support;

final class Flash
{
    private const FLASH_KEY = '_flash';

    public static function set(string $key, mixed $value): void
    {
        if (!isset($_SESSION[self::FLASH_KEY]) || !is_array($_SESSION[self::FLASH_KEY])) {
            $_SESSION[self::FLASH_KEY] = [];
        }

        $_SESSION[self::FLASH_KEY][$key] = $value;
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        if (
            !isset($_SESSION[self::FLASH_KEY]) ||
            !is_array($_SESSION[self::FLASH_KEY]) ||
            !array_key_exists($key, $_SESSION[self::FLASH_KEY])
        ) {
            return $default;
        }

        $value = $_SESSION[self::FLASH_KEY][$key];
        unset($_SESSION[self::FLASH_KEY][$key]);

        if (empty($_SESSION[self::FLASH_KEY])) {
            unset($_SESSION[self::FLASH_KEY]);
        }

        return $value;
    }
}
