<?php
namespace App\Core;

/** Pesan sekali-tampil (flash message). */
class Flash
{
    private const KEY = '_flash';

    public static function add(string $type, string $message): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) return;
        $_SESSION[self::KEY][] = ['type' => $type, 'message' => $message];
    }

    public static function success(string $m): void { self::add('success', $m); }
    public static function error(string $m): void   { self::add('danger', $m); }
    public static function warning(string $m): void { self::add('warning', $m); }
    public static function info(string $m): void    { self::add('info', $m); }

    public static function pull(): array
    {
        $f = $_SESSION[self::KEY] ?? [];
        unset($_SESSION[self::KEY]);
        return $f;
    }

    /** Menyimpan input lama agar form dapat diisi ulang setelah validasi gagal. */
    public static function keepInput(array $input): void
    {
        unset($input[Csrf::FIELD]);
        $_SESSION['_old'] = $input;
    }

    public static function old(string $key, $default = '')
    {
        return $_SESSION['_old'][$key] ?? $default;
    }

    public static function clearOld(): void { unset($_SESSION['_old']); }

    public static function keepErrors(array $errors): void { $_SESSION['_errors'] = $errors; }

    public static function errors(): array
    {
        $e = $_SESSION['_errors'] ?? [];
        unset($_SESSION['_errors']);
        return $e;
    }
}
