<?php
declare(strict_types=1);

namespace Core;

final class Session
{
    public static function start(): void
    {
        if (session_status() === PHP_SESSION_ACTIVE) return;
        session_start();
        self::touch();
    }

    public static function touch(): void
    {
        $ttl = (int) env('SESSION_LIFETIME', 1800);
        $now = time();
        $last = $_SESSION['_last_activity'] ?? $now;
        if ($now - $last > $ttl) {
            self::destroy();
            return;
        }
        $_SESSION['_last_activity'] = $now;
    }

    public static function login(array $user, array $perms = []): void
    {
        session_regenerate_id(true);
        $_SESSION['user'] = [
            'user_id'        => $user['user_id'],
            'tenant_id'      => $user['tenant_id'] ?? null,
            'username'       => $user['username'],
            'full_name'      => trim(($user['f_name'] ?? '') . ' ' . ($user['l_name'] ?? '')),
            'email'          => $user['email'] ?? null,
            'role'           => $user['role'] ?? null,
            'role_code'      => $user['role_code'] ?? null,
            'is_super_admin' => !empty($user['is_super_admin']) ? 1 : 0,
            'perms'          => array_values($perms),
        ];
        if (!empty($user['tenant_id'])) {
            $_SESSION['tenant_id'] = (int) $user['tenant_id'];
        }
        $_SESSION['_last_activity'] = time();
    }

    /** True if the logged-in user has the given permission code. */
    public static function can(string $code): bool
    {
        $perms = $_SESSION['user']['perms'] ?? [];
        return in_array($code, $perms, true);
    }

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

    public static function check(): bool
    {
        return isset($_SESSION['user']);
    }

    public static function destroy(): void
    {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $p = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000,
                $p['path'], $p['domain'], $p['secure'], $p['httponly']);
        }
        session_destroy();
    }

    public static function flash(string $key, ?string $msg = null): ?string
    {
        if ($msg !== null) { $_SESSION['_flash'][$key] = $msg; return null; }
        $v = $_SESSION['_flash'][$key] ?? null;
        unset($_SESSION['_flash'][$key]);
        return $v;
    }
}
