<?php
function getUserRoleFromSession(): ?string {
    if (!isset($_SESSION['user'])) return null;

    if (method_exists($_SESSION['user'], 'getRole')) {
        return strtolower((string)$_SESSION['user']->getRole());
    }
    if (method_exists($_SESSION['user'], 'getId_rolle')) {
        switch ((int)$_SESSION['user']->getId_rolle()) {
            case 1: return 'admin';
            case 2: return 'ca';
            case 3: return 'bureau';
            default: return 'user';
        }
    }
    return null;
}

function canReturnEmprunt(string $userRole = null, int $currentUserId = null, int $borrowerId = null): bool {
    $authorizedRoles = ['admin','ca','bureau'];
    if ($userRole && in_array($userRole, $authorizedRoles, true)) return true;
    if ($currentUserId !== null && $borrowerId !== null && $currentUserId === $borrowerId) return true;
    return false;
}
