<?php

declare(strict_types=1);

namespace Core;

final class Session
{
    public static function flash(string $key, mixed $value): void
    {
        $_SESSION['_flash_next'][$key] = $value;
    }

    public static function getFlash(string $key, mixed $default = null): mixed
    {
        return $_SESSION['_flash'][$key] ?? $default;
    }

    public static function sweepFlash(): void
    {
        $_SESSION['_flash'] = $_SESSION['_flash_next'] ?? [];
        unset($_SESSION['_flash_next']);

        $_SESSION['_old_input'] = $_SESSION['_old_input_next'] ?? [];
        unset($_SESSION['_old_input_next']);
    }

    public static function putOldInput(array $input): void
    {
        unset($input['_token']);
        $_SESSION['_old_input_next'] = $input;
    }

    public static function getOldInput(): array
    {
        return $_SESSION['_old_input'] ?? [];
    }

    public static function clearOldInput(): void
    {
        unset($_SESSION['_old_input'], $_SESSION['_old_input_next']);
    }

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

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

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

    public static function set(string $key, mixed $value): void
    {
        $_SESSION[$key] = $value;
    }

    public static function get(string $key, mixed $default = null): mixed
    {
        return $_SESSION[$key] ?? $default;
    }

    public static function forget(string $key): void
    {
        unset($_SESSION[$key]);
    }

    public static function regenerate(bool $deleteOldSession = false): void
    {
        if (session_status() === PHP_SESSION_ACTIVE) {
            session_regenerate_id($deleteOldSession);
        }
    }

    public static function invalidate(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            return;
        }

        $_SESSION = [];
        unset($_SESSION['_flash'], $_SESSION['_flash_next'], $_SESSION['_old_input'], $_SESSION['_old_input_next'], $_SESSION['_errors']);

        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', [
                'expires' => time() - 42000,
                'path' => $params['path'] ?? '/',
                'domain' => $params['domain'] ?? '',
                'secure' => (bool) ($params['secure'] ?? false),
                'httponly' => (bool) ($params['httponly'] ?? true),
                'samesite' => $params['samesite'] ?? 'Lax',
            ]);
        }

        session_destroy();
    }
}
