<?php
// Returns PublicKeyCredentialCreationOptions for registering a passkey.
require_once __DIR__ . '/includes/wa_json_guard.php';
session_start();
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/webauthn.php';

if (empty($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['error' => 'auth']); exit; }
wa_ensure_table($conn);

$uid = (int)$_SESSION['user_id'];
$u = $conn->prepare("SELECT name, email FROM users WHERE id=? LIMIT 1");
$u->bind_param("i", $uid);
$u->execute();
$user = $u->get_result()->fetch_assoc() ?: ['name' => 'Dabil user', 'email' => 'user' . $uid];

$challenge = random_bytes(32);
$_SESSION['wa_reg_challenge'] = wa_b64url_encode($challenge);

$exclude = [];
if ($r = $conn->prepare("SELECT credential_id FROM webauthn_credentials WHERE user_id=?")) {
    $r->bind_param("i", $uid);
    $r->execute();
    $rr = $r->get_result();
    while ($c = $rr->fetch_assoc()) $exclude[] = ['type' => 'public-key', 'id' => $c['credential_id']];
}

echo json_encode([
    'challenge' => $_SESSION['wa_reg_challenge'],
    'rp'        => ['name' => 'Dabil', 'id' => wa_rp_id()],
    'user'      => [
        'id'          => wa_b64url_encode((string)$uid),
        'name'        => $user['email'] ?: ('user' . $uid),
        'displayName' => $user['name'] ?: 'Dabil user',
    ],
    'pubKeyCredParams'       => [['type' => 'public-key', 'alg' => -7]], // ES256
    'timeout'                => 60000,
    'attestation'            => 'none',
    'authenticatorSelection' => ['authenticatorAttachment' => 'platform', 'userVerification' => 'required', 'residentKey' => 'preferred'],
    'excludeCredentials'     => $exclude,
]);
