<?php

declare(strict_types=1);

header('Content-Type: application/json');

/* include tenant config + 2FA lib */
$tenant = $_POST['tenant'] ?? '';
$cfgA = __DIR__ . '/../../' . $tenant . '/config.php';
$cfgB = __DIR__ . '/../'   . $tenant . '/config.php';
if (is_file($cfgA)) {
    require_once $cfgA;
} elseif (is_file($cfgB)) {
    require_once $cfgB;
} elseif (is_file('/config.php')) {
    require_once '/config.php';
} else {
    echo json_encode(['status' => 'error', 'error' => 'no_config']);
    exit;
}

require_once('security/2fa_lib.php');

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

/* DB-side rate limit: 60s since last code for this admin */
$wait_s = 0;
$chk = $con->prepare("SELECT GREATEST(0, 60 - TIMESTAMPDIFF(SECOND, MAX(created_at), NOW())) AS wait_s
                      FROM admin_2fa_codes WHERE admin_id=?");
if ($chk) {
    $chk->bind_param('i', $admin_id);
    $chk->execute();
    $chk->bind_result($wait_s);
    $chk->fetch();
    $chk->close();
}
if ($wait_s > 0) {
    echo json_encode(['status' => 'error', 'error' => 'rate_limited', 'retry_in' => $wait_s]);
    exit;
}

/* load email */
$s = $con->prepare("SELECT email FROM admins WHERE id=? LIMIT 1");
if (!$s) {
    echo json_encode(['status' => 'error', 'error' => 'sql_prepare']);
    exit;
}
$s->bind_param('i', $admin_id);
if (!$s->execute()) {
    echo json_encode(['status' => 'error', 'error' => 'sql_exec']);
    exit;
}
$row = $s->get_result()->fetch_assoc();
$email = $row['email'] ?? '';
if ($email === '') {
    echo json_encode(['status' => 'error', 'error' => 'no_email']);
    exit;
}

/* send */
echo json_encode(
    tenant_2fa_send_code($con, $admin_id, $email)
        ? ['status' => 'ok']
        : ['status' => 'error', 'error' => 'send_failed']
);