<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

/**
 * Load permissions for a user at login
 */
function loadUserPermissions(int $userId, ?int $companyId): array
{
    $db = db();

$stmt = $db->prepare("
    SELECT DISTINCT p.permission_key
    FROM user_roles ur
    JOIN roles r ON r.id = ur.role_id
    JOIN role_permissions rp ON rp.role_id = r.id
    JOIN permissions p ON p.id = rp.permission_id
    WHERE ur.user_id = :user_id
      AND (r.scope = 'global' OR ur.company_id = :company_id)
");

$stmt->execute([
    'user_id' => $userId,
    'company_id' => $companyId
]);
