<?php

namespace MintyPHP\Http;

class SessionStore implements SessionStoreInterface
{
    public function get(string $key, mixed $default = null): mixed
    {
        $session = $this->all();
        if (!array_key_exists($key, $session)) {
            return $default;
        }

        return $session[$key];
    }

    public function set(string $key, mixed $value): void
    {
        if (!is_array($_SESSION ?? null)) {
            $_SESSION = [];
        }

        $_SESSION[$key] = $value;
    }

    public function has(string $key): bool
    {
        $session = $this->all();
        return array_key_exists($key, $session);
    }

    public function remove(string $key): void
    {
        if (!is_array($_SESSION ?? null)) {
            $_SESSION = [];
        }

        unset($_SESSION[$key]);
    }

    /**
     * @return array<string, mixed>
     */
    public function all(): array
    {
        /** @var array<string, mixed> $session */
        $session = $_SESSION;
        return $session;
    }
}
