<?php
class Session {
    public static function checkActivity() {
        if (isset($_SESSION['login_time'])) {
            if (time() - $_SESSION['login_time'] > LOGGED_TIME_OUT) {
                self::logOut();
                Router::redirect("gatewayAccess");
            } else {
                self::setLoginTime();
            }
        }
    }

    public static function setLoginTime() {
        $_SESSION['login_time'] = time();
    }

    public static function logOut() {
        $_SESSION = [];
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 42000);
        }
        session_destroy();
    }

    public static function njeNdani() {
        if (isset($_SESSION['username'])) {
            if (empty($_SESSION['username'])) {
                self::logOut();
                Router::redirect("gatewayAccess");
            } else {
                self::checkActivity();
            }
        }
    }

    public static function checkUsername() {
        $_SESSION['username'] = isset($_SESSION['username']) ? $_SESSION['username'] : "";
    }

    public static function exists($name) { return isset($_SESSION[$name]); }
    public static function get($name)    { return $_SESSION[$name] ?? null; }
    public static function set($name, $value) { $_SESSION[$name] = $value; }
    public static function delete($name) { unset($_SESSION[$name]); }

    /**
     * Set a one-shot flash message read on the next request by flashHtml().
     * Realm-scoped so super-admin actions never leak into tenant pages.
     * $type: success | danger | warning | info
     */
    public static function flash(string $type, string $msg, ?string $realm = null): void {
        $realm = $realm ?: (self::isSuperAdmin() ? 'super' : 'tenant');
        $_SESSION['flash_' . $realm . '_msg']  = $msg;
        $_SESSION['flash_' . $realm . '_type'] = $type;
    }

    public static function isLoggedIn() {
        return !empty($_SESSION['username']);
    }

    public static function tenantId(): int {
        return (int)($_SESSION['tenant_id'] ?? 0);
    }

    public static function tenantCode(): string {
        return (string)($_SESSION['tenant_code'] ?? '');
    }

    public static function tenantNo(): int {
        return (int)($_SESSION['tenant_no'] ?? 0);
    }

    public static function tenantName(): string {
        return (string)($_SESSION['tenant_name'] ?? '');
    }

    public static function isSuperAdmin(): bool {
        return !empty($_SESSION['super_admin_id']);
    }
}
