<?php
/**
 * Fichier  : api/permissions.php
 * Version  : 2.6.113
 * Date     : 2026-07-22
 * Description : Gestion des permissions par utilisateur. Les comptes LDAP peuvent utiliser
 *               les mappings d’annuaire ou une surcharge locale explicitement activée.
 *               Le rôle Magasinier conserve des exclusions système non contournables.
 */
require_once __DIR__.'/../config.php';
require_once __DIR__.'/../includes/ldap-helper.php';
requireAuth();
requireAdmin();
requirePerm('users.manage');

$method = $_SERVER['REQUEST_METHOD'];
if($method !== 'GET') csrfCheck();
$body = in_array($method, ['POST','PUT','PATCH'], true) ? (json_decode(file_get_contents('php://input'), true) ?: []) : [];

function permissionsApiUser(string $userId): ?array {
    foreach(loadData('users') as $user) if((string)($user['id']??'')===$userId) return $user;
    return null;
}

switch($method){
    case 'GET':
        $userId = (string)($_GET['userId'] ?? '');
        if(!$userId) jsonError('userId manquant.');
        $user = permissionsApiUser($userId);
        if(!$user) jsonError('Utilisateur introuvable.',404);
        $permFile = loadPermissions();
        jsonResponse([
            'role'=>magestockNormalizeRole($user['role']??'user'),
            'rolePerms'=>$permFile['roles'][magestockNormalizeRole($user['role']??'user')] ?? [],
            'userOverrides'=>$permFile['users'][$userId] ?? [],
            'managedByDirectory'=>(($user['authSource']??'local')==='ldap' && magestockLdapAuthorizationSource($user)!=='local'),
            'authorizationSource'=>magestockLdapAuthorizationSource($user),
        ]);

    case 'PUT':
        $userId = (string)($body['userId'] ?? '');
        $perms  = $body['permissions'] ?? null;
        if(!$userId || !is_array($perms)) jsonError('userId et permissions requis.');
        $user = permissionsApiUser($userId);
        if(!$user) jsonError('Utilisateur introuvable.',404);
        if(($user['authSource']??'local')==='ldap' && magestockLdapAuthorizationSource($user)!=='local') jsonError('Activez d’abord la surcharge locale des autorisations pour modifier ces permissions.',422);
        $cleaned = magestockLdapNormalizePermissions($perms);
        if(magestockNormalizeRole($user['role']??'user') === 'magasinier'){
            foreach(magestockMagasinierDeniedPermissions() as $denied) $cleaned[$denied] = false;
            $cleaned['admin.access'] = true;
            $cleaned['documentation.read'] = true;
        }
        $permFile = loadPermissions();
        $permFile['users'][$userId] = $cleaned;
        savePermissions($permFile);
        if(($user['authSource']??'local')==='ldap'){
            magestockLdapAudit('local_permissions_updated', [
                'targetUserId'=>$userId,
                'username'=>$user['username']??'',
                'permissionCount'=>count($cleaned),
            ], currentUser());
        }
        jsonResponse(['ok'=>true,'userId'=>$userId,'permissions'=>$cleaned]);

    default:
        jsonError('Méthode non supportée.',405);
}
