<?php

declare(strict_types=1);
if (file_exists('../../' . ($_POST['tenant'] ?? '') . '/config.php')) require_once('../../' . $_POST['tenant'] . '/config.php');
if (file_exists('/config.php')) require_once('/config.php');
require_once(__DIR__ . '/security/2fa_lib.php');
header('Content-Type: application/json');

$code = trim($_POST['code'] ?? '');
if (!isset($_SESSION['admin_pending'])) {
    echo json_encode(['status' => 'error', 'error' => 'no_pending']);
    exit;
}
$admin_id = (int)$_SESSION['admin_pending'];

$stmt = $con->prepare("SELECT id, expires_at, used FROM admin_2fa_codes WHERE admin_id=? AND code=? ORDER BY id DESC LIMIT 1");
$stmt->bind_param('is', $admin_id, $code);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
if (!$row) {
    echo json_encode(['status' => 'error', 'error' => 'invalid']);
    exit;
}
if ((int)$row['used'] === 1) {
    echo json_encode(['status' => 'error', 'error' => 'used']);
    exit;
}
if (new DateTime() > new DateTime($row['expires_at'])) {
    echo json_encode(['status' => 'error', 'error' => 'expired']);
    exit;
}

$u = $con->prepare("UPDATE admin_2fa_codes SET used=1 WHERE id=?");
$u->bind_param('i', $row['id']);
$u->execute();

tenant_2fa_set_trusted($con, $admin_id);
unset($_SESSION['admin_pending']);
$_SESSION['admin_id'] = $admin_id;

echo json_encode(['status' => 'ok']);