<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 401 Unauthorized');
    exit(json_encode(['error' => 'Non autorisé']));
}

if (!isset($_GET['id'])) {
    header('HTTP/1.1 400 Bad Request');
    exit(json_encode(['error' => 'ID utilisateur manquant']));
}

try {
    $db = getDB1Connection();

    $query = $db->prepare("SELECT id, username, email, role, roleinimators, permissions, profile_picture, note 
                          FROM utilisateurs 
                          WHERE id = ?");
    $query->execute([$_GET['id']]);
    $user = $query->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        header('HTTP/1.1 404 Not Found');
        exit(json_encode(['error' => 'Utilisateur non trouvé']));
    }

    $response = [
        'id' => $user['id'],
        'username' => $user['username'],
        'email' => $user['email'],
        'role' => $user['role'],
        'roleinimators' => $user['roleinimators'],
        'permissions' => $user['permissions'],
        'note' => $user['note'],
        'profile_picture' => $user['profile_picture'] ? 
            htmlspecialchars($user['profile_picture']) : 
            'https://cdn.imators.com/default-avatar.png'
    ];

    header('Content-Type: application/json');
    echo json_encode($response);

} catch (PDOException $e) {
    header('HTTP/1.1 500 Internal Server Error');
    exit(json_encode(['error' => 'Erreur serveur']));
}