<?php
session_start();
require_once '../db.php';
require_once '../vendor/autoload.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Non authentifié']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->connect();

    // Récupérer les informations de l'utilisateur
    $stmt = $conn->prepare("SELECT id, email, username FROM utilisateurs WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        throw new Exception('Utilisateur non trouvé');
    }

    // Générer le challenge
    $challenge = random_bytes(32);
    $_SESSION['passkey_challenge'] = base64_encode($challenge);

    echo json_encode([
        'success' => true,
        'challenge' => base64_encode($challenge),
        'userId' => base64_encode((string)$user['id']),
        'userEmail' => $user['email'],
        'userName' => $user['username']
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}