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

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

if (!isset($_SESSION['user_id']) || !isset($_SESSION['passkey_challenge'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Session invalide']);
    exit;
}

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

    // Récupérer les données de la requête
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!$data) {
        throw new Exception('Données invalides');
    }

    // Vérifier et enregistrer la passkey
    try {
        $stmt = $conn->prepare("
            INSERT INTO passkeys (user_id, credential_id, public_key, created_at)
            VALUES (?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $_SESSION['user_id'],
            $data['id'],
            $data['response']['clientDataJSON']
        ]);

        // Activer passkey pour l'utilisateur
        $stmt = $conn->prepare("
            UPDATE utilisateurs 
            SET passkey_enabled = TRUE 
            WHERE id = ?
        ");
        $stmt->execute([$_SESSION['user_id']]);

        // Nettoyer la session
        unset($_SESSION['passkey_challenge']);

        echo json_encode(['success' => true]);

    } catch (PDOException $e) {
        throw new Exception('Erreur lors de l\'enregistrement de la passkey');
    }

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