<?php
class Roles {
    public static function isSystemAdmin(): bool { return !empty($_SESSION['user']['is_system_admin']); }

    public static function inProject(PDO $pdo, int $projectId, ?int $userId=null): ?array {
        $uid = $userId ?? ($_SESSION['user']['id'] ?? 0);
        $s = $pdo->prepare('SELECT * FROM project_memberships WHERE user_id=? AND project_id=?');
        $s->execute([$uid, $projectId]);
        return $s->fetch() ?: null;
    }

    public static function requireRole(PDO $pdo, int $projectId, array $allowedRoles): void {
        if (self::isSystemAdmin()) return;
        $m = self::inProject($pdo, $projectId);
        if (!$m || !in_array($m['role'], $allowedRoles, true)) {
            http_response_code(403); exit('Forbidden');
        }
    }
}