<?php
class SuperAuth {
    private static string $sessionsDir;

    public static function startSession(): void {
        self::$sessionsDir = (defined('SESSION_PATH') ? SESSION_PATH : (APP_ROOT . '/storage/sessions')) . '/superadmin';
        if (!is_dir(self::$sessionsDir)) {
             mkdir(self::$sessionsDir, 0755, true);
        }
        ini_set('session.save_path', self::$sessionsDir);
        ini_set('session.name', 'TP_SUPER_SESSION');
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public static function login(array $admin): void {
        $_SESSION['superadmin_id'] = $admin['id'];
        $_SESSION['superadmin_name'] = $admin['name'];
        $_SESSION['is_superadmin'] = true;
    }

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

    public static function check(): bool {
        return isset($_SESSION['is_superadmin']) && $_SESSION['is_superadmin'] === true;
    }

    public static function requireLogin(): void {
        if (!self::check()) {
            redirect('superadmin/login');
        }
    }

    public static function user(): ?array {
        if (!self::check()) return null;
        return [
            'id'   => $_SESSION['superadmin_id'],
            'name' => $_SESSION['superadmin_name']
        ];
    }
}
