<?php
/**
 * Fichier  : api/permissions.php
 * Version  : 2.3.0
 * Description : API — Gestion permissions par utilisateur (admin uniquement)
 */
require_once __DIR__.'/../config.php';
requireAuth();
requireAdmin();

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if($method !== 'GET') csrfCheck();

$body = [];
if(in_array($method, ['POST','PUT','PATCH'])){
    $body = json_decode(file_get_contents('php://input'), true) ?: [];
}

switch($method){
    case 'GET':
        // GET ?userId=X => retourne permissions effectives
        $userId = (string)($_GET['userId'] ?? '');
        if(!$userId) jsonError('userId manquant.');
        $permFile = loadPermissions();
        $userOverrides = $permFile['users'][$userId] ?? [];
        $rolePerms = $permFile['roles']['user'] ?? [];
        jsonResponse([
            'rolePerms'     => $rolePerms,
            'userOverrides' => $userOverrides,
        ]);

    case 'PUT':
        // PUT { userId, permissions: { key: bool } }
        $userId = (string)($body['userId'] ?? '');
        $perms  = $body['permissions'] ?? null;
        if(!$userId || !is_array($perms)) jsonError('userId et permissions requis.');
        // Sanitize: only bool values allowed
        $cleaned = [];
        foreach($perms as $k => $v) {
            if(is_string($k) && $k !== '') $cleaned[$k] = (bool)$v;
        }
        $permFile = loadPermissions();
        $permFile['users'][$userId] = $cleaned;
        savePermissions($permFile);
        jsonResponse(['ok' => true, 'userId' => $userId, 'permissions' => $cleaned]);

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