<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/user_auth_lib.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_admin_require_permission('member-twofa');
mocker_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$userId = isset($input['userId']) ? (int) $input['userId'] : 0;
$action = (string) ($input['action'] ?? '');

if ($userId <= 0 || $action !== 'disable') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'bad_request'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_user_auth_migrate($pdo);

$st = $pdo->prepare('SELECT id, COALESCE(twofa_enabled, 0) AS twofa_enabled FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $userId]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    http_response_code(404);
    echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ((int) ($row['twofa_enabled'] ?? 0) !== 1) {
    echo json_encode(['ok' => true, 'twofaEnabled' => false], JSON_UNESCAPED_UNICODE);
    exit;
}

$up = $pdo->prepare(
    'UPDATE users SET twofa_enabled = 0, twofa_secret = NULL, twofa_backup_codes_json = :codes WHERE id = :id'
);
$up->execute([
    ':codes' => json_encode([], JSON_UNESCAPED_UNICODE),
    ':id' => $userId,
]);

echo json_encode(['ok' => true, 'twofaEnabled' => false], JSON_UNESCAPED_UNICODE);
