<?php
// Returns PublicKeyCredentialRequestOptions for a passkey sign-in.
require_once __DIR__ . '/includes/wa_json_guard.php';
session_start();
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/webauthn.php';
wa_ensure_table($conn);

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

// If an identifier was supplied, scope to that account's credentials;
// otherwise rely on discoverable credentials (usernameless).
$allow = [];
$identifier = trim($_POST['identifier'] ?? '');
if ($identifier !== '') {
    $q = $conn->prepare(
        "SELECT wc.credential_id FROM webauthn_credentials wc
         JOIN users u ON wc.user_id = u.id
         WHERE u.email = ? OR u.phone = ?"
    );
    $q->bind_param("ss", $identifier, $identifier);
    $q->execute();
    $rr = $q->get_result();
    while ($c = $rr->fetch_assoc()) $allow[] = ['type' => 'public-key', 'id' => $c['credential_id']];
}

echo json_encode([
    'challenge'        => $_SESSION['wa_login_challenge'],
    'rpId'             => wa_rp_id(),
    'timeout'          => 60000,
    'userVerification' => 'required',
    'allowCredentials' => $allow,
]);
