<?php

declare(strict_types=1);

function can(array $user, string $module, string $action, PDO $pdo): bool
{
    if (empty($user['role'])) return false;

    $sql = "
        SELECT 
            p.can_view,
            p.can_create,
            p.can_edit,
            p.can_delete
        FROM permissions p
        JOIN roles r ON r.id = p.role_id
        JOIN modules m ON m.id = p.module_id
        WHERE r.role_key = ?
          AND m.module_key = ?
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$user['role'], $module]);

    $perm = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$perm) return false;

    return match ($action) {
        'view'   => (bool)$perm['can_view'],
        'create' => (bool)$perm['can_create'],
        'edit'   => (bool)$perm['can_edit'],
        'delete' => (bool)$perm['can_delete'],
        default  => false,
    };
}