<?php
/**
 * Generate a single-use WebAuthn challenge.
 * POST: (no body parameters required)
 * Auth: admin/headteacher (enrollment) OR canteen_staff_authenticated (verification)
 * Returns: { challenge: "base64url", expires_in: 60 }
 */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');
header('Cache-Control: no-store');

require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_active();

$is_staff = !empty($_SESSION['canteen_staff_authenticated']);
$is_role  = !empty($_SESSION['user_id']);
if (!$is_staff && !$is_role) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit;
}

// Generate 32-byte cryptographically random challenge
$raw = random_bytes(32);
$challenge_b64u = base64url_encode($raw);

// Store in session as single-use: value + expiry
$_SESSION['webauthn_challenge']         = $challenge_b64u;
$_SESSION['webauthn_challenge_expires'] = time() + 60;

echo json_encode([
    'success'    => true,
    'challenge'  => $challenge_b64u,
    'expires_in' => 60,
]);
