<?php
// =============================================================
//  POST /api/v1/auth/disable_2fa
//
//  Mobile equivalent of app/setup_2fa.php's 'disable_2fa' action.
//  Body: { "current_password": "..." } — requires the account's own
//  current password, same as the desktop confirm step, so a
//  momentarily-unlocked device can't be used to strip 2FA off an
//  account without knowing its password.
// =============================================================

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']);

$userId = $account->getId();
if (!Totp::isEnabledFor($conn, $userId)) {
    Api::error(409, 'NotEnabled', 'Two-factor authentication is not enabled for this account.');
}

$body     = Api::body();
$password = (string)($body['current_password'] ?? '');
if ($password === '') {
    Api::error(422, 'ValidationError', 'current_password is required');
}

$stmt = $conn->prepare('SELECT password FROM users WHERE id = ?');
$stmt->bind_param('i', $userId);
$stmt->execute();
$hash = $stmt->get_result()->fetch_assoc()['password'] ?? '';
$stmt->close();

if (!password_verify($password, $hash)) {
    Api::error(401, 'IncorrectPassword', 'Incorrect password.');
}

$stmt = $conn->prepare('UPDATE users SET totp_secret = NULL, totp_enabled = 0, totp_recovery_codes = NULL WHERE id = ?');
$stmt->bind_param('i', $userId);
$stmt->execute();
$stmt->close();

$perm_manager->logAudit($userId, 'disable_2fa', 'user', $userId, null, null);

Api::success(['message' => 'Two-factor authentication disabled.']);
