<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/telegram_lib.php';
require_once __DIR__ . '/telegram_auth_lib.php';
require_once __DIR__ . '/user_auth_lib.php';
require_once __DIR__ . '/admin_2fa_lib.php';
require_once __DIR__ . '/ip.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_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'payload'], JSON_UNESCAPED_UNICODE);
    exit;
}

$twofaCode = trim((string) ($input['twofaCode'] ?? ''));
$twofaChallenge = trim((string) ($input['twofaChallenge'] ?? ''));
$now = time();

$completeTelegramLogin = static function (PDO $pdo, array $row, bool $isNew): void {
    $uid = (int) ($row['id'] ?? 0);
    if ($uid <= 0) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    unset($_SESSION['mocker_user_2fa_pending']);
    session_regenerate_id(true);
    $_SESSION['mocker_user_id'] = $uid;
    $_SESSION['mocker_telegram_miniapp'] = true;

    $lip = mocker_client_ip();
    $upd = $pdo->prepare(
        'UPDATE users SET last_login_at = :t, last_seen_at = :t2, last_login_ip = :lip WHERE id = :id'
    );
    $upd->execute([
        ':t' => time(),
        ':t2' => time(),
        ':lip' => $lip !== '' ? $lip : null,
        ':id' => $uid,
    ]);

    mocker_telegram_auth_json_success($pdo, $row, $isNew);
    exit;
};

if ($twofaChallenge !== '') {
    $pending = $_SESSION['mocker_user_2fa_pending'] ?? null;
    if (!is_array($pending) || ($pending['via'] ?? '') !== 'telegram_miniapp') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'twofa_missing_challenge'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $expiresAt = (int) ($pending['expiresAt'] ?? 0);
    if ($expiresAt <= $now) {
        unset($_SESSION['mocker_user_2fa_pending']);
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'twofa_expired'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $expectedChallenge = (string) ($pending['challenge'] ?? '');
    if ($expectedChallenge === '' || !hash_equals($expectedChallenge, $twofaChallenge)) {
        http_response_code(401);
        echo json_encode(['ok' => false, 'error' => 'twofa_invalid_challenge'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $attemptCount = (int) ($pending['attempts'] ?? 0);
    if ($attemptCount >= 5) {
        unset($_SESSION['mocker_user_2fa_pending']);
        http_response_code(429);
        echo json_encode(['ok' => false, 'error' => 'too_many_attempts'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $pending['attempts'] = $attemptCount + 1;
    $_SESSION['mocker_user_2fa_pending'] = $pending;

    $secret = (string) ($pending['secret'] ?? '');
    $ok = $twofaCode !== '' && $secret !== '' && mocker_admin_twofa_verify_code($secret, $twofaCode, 1);
    if (!$ok) {
        http_response_code(401);
        echo json_encode(
            ['ok' => false, 'error' => 'twofa_invalid', 'remaining' => max(0, 5 - (int) $pending['attempts'])],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }

    $row = is_array($pending['row'] ?? null) ? $pending['row'] : null;
    $isNew = !empty($pending['isNew']);
    if (!$row) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'twofa_missing_challenge'], 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;
    }

    $completeTelegramLogin($pdo, $row, $isNew);
}

if (!mocker_telegram_is_configured()) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'telegram_config'], JSON_UNESCAPED_UNICODE);
    exit;
}

$initData = isset($input['initData']) && is_string($input['initData']) ? trim($input['initData']) : '';
if ($initData === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'init_data_missing'], JSON_UNESCAPED_UNICODE);
    exit;
}

$verified = mocker_telegram_verify_webapp_init_data($initData, 86400);
if ($verified === null) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'telegram_invalid'], JSON_UNESCAPED_UNICODE);
    exit;
}

$user = is_array($verified['user'] ?? null) ? $verified['user'] : null;
if (!$user || !isset($user['id'])) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'user_missing'], JSON_UNESCAPED_UNICODE);
    exit;
}

$tgUid = (int) $user['id'];
if ($tgUid <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'payload'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!empty($user['is_bot'])) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'bot_user'], JSON_UNESCAPED_UNICODE);
    exit;
}

$tgUsername = isset($user['username']) ? trim((string) $user['username']) : '';
$firstName = isset($user['first_name']) ? trim((string) $user['first_name']) : '';

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

try {
    $result = mocker_telegram_auth_upsert_from_telegram($pdo, $tgUid, $tgUsername, $firstName);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
    exit;
}

$isNew = $result['is_new'];
$uid = (int) ($result['row']['id'] ?? 0);

$st = $pdo->prepare('SELECT ' . mocker_user_select_auth_columns() . ' FROM users WHERE id = :id LIMIT 1');
$st->execute([':id' => $uid]);
$row = $st->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'server'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ((int) ($row['is_active'] ?? 1) !== 1) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'inactive'], JSON_UNESCAPED_UNICODE);
    exit;
}

$twofaEnabled = (int) ($row['twofa_enabled'] ?? 0) === 1;
$twofaSecret = trim((string) ($row['twofa_secret'] ?? ''));
if ($twofaEnabled && $twofaSecret !== '') {
    $challenge = rtrim(strtr(base64_encode(random_bytes(24)), '+/', '-_'), '=');
    $_SESSION['mocker_user_2fa_pending'] = [
        'challenge' => $challenge,
        'expiresAt' => $now + 300,
        'attempts' => 0,
        'secret' => $twofaSecret,
        'userId' => $uid,
        'row' => $row,
        'isNew' => $isNew,
        'via' => 'telegram_miniapp',
    ];
    echo json_encode(['ok' => true, 'requires2fa' => true, 'twofaChallenge' => $challenge], JSON_UNESCAPED_UNICODE);
    exit;
}

$completeTelegramLogin($pdo, $row, $isNew);
