<?php
// =============================================================
//  POST /api/v1/auth/setup_2fa_start
//
//  Mobile equivalent of app/setup_2fa.php's 'start_setup' action —
//  self-service TOTP enrollment for staff accounts. Generates a fresh
//  secret and returns it (with an otpauth:// URI for QR rendering)
//  directly to the client, rather than the desktop's approach of
//  holding it in $_SESSION until confirmed: a bearer-token API request
//  carries no cookie session across separate calls, so there is no
//  server-side session to hold it in. Nothing is persisted here —
//  the secret only reaches the users table in setup_2fa_confirm.php,
//  once a real code from the account holder's authenticator app has
//  verified it. That is the same "nothing saved until confirmed"
//  security property the desktop's session-held approach has, just
//  carried by the client instead of a session.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/Totp.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_staff_role($account, ['Admin', 'Chief_Preceptor', 'Preceptor', 'Nurse_Manager', 'In_Charge']);

if (!Totp::columnsExist($conn)) {
    Api::error(503, 'NotConfigured', 'Two-factor authentication is not set up on this server yet.');
}
if (Totp::isEnabledFor($conn, $account->getId())) {
    Api::error(409, 'AlreadyEnabled', 'Two-factor authentication is already enabled for this account.');
}

$secret = Totp::generateSecret();
$uri    = Totp::getOtpAuthUri($secret, $account->getEmail(), 'STH NRMS');

Api::success(['secret' => $secret, 'otpauth_uri' => $uri]);
