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

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

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

try {
    $db = new Database();
    $conn = $db->connect();
    
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!$data) {
        throw new Exception('Données invalides');
    }

    // Vérifier la passkey
    $stmt = $conn->prepare("
        SELECT * FROM passkeys 
        WHERE user_id = ? AND credential_id = ?
    ");
    $stmt->execute([$_SESSION['pending_login_id'], $data['id']]);
    $passkey = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$passkey) {
        throw new Exception('Passkey non trouvée');
    }

    // Si la vérification réussit
    $_SESSION['user_id'] = $_SESSION['pending_login_id'];
    
    // Mettre à jour la dernière utilisation
    $stmt = $conn->prepare("
        UPDATE passkeys 
        SET last_used_at = NOW() 
        WHERE id = ?
    ");
    $stmt->execute([$passkey['id']]);
    
    // Nettoyer la session
    unset($_SESSION['pending_login_id']);
    unset($_SESSION['pending_auth']);
    
    echo json_encode(['success' => true]);

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