<?php
declare(strict_types=1);

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

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!mocker_telegram_is_configured()) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'telegram_config'], 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;
}

$st = $pdo->prepare(
    'SELECT id, telegram_verified_at, telegram_username FROM users WHERE id = :id LIMIT 1'
);
$st->execute([':id' => $uid]);
$row = $st->fetch();

if (!$row) {
    unset($_SESSION['mocker_user_id']);
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth'], JSON_UNESCAPED_UNICODE);
    exit;
}

$verifiedAt = $row['telegram_verified_at'] ?? null;
if ($verifiedAt !== null && (int) $verifiedAt > 0) {
    $tu = isset($row['telegram_username']) && $row['telegram_username'] !== null && $row['telegram_username'] !== ''
        ? (string) $row['telegram_username']
        : '';
    echo json_encode(
        [
            'ok' => true,
            'verified' => true,
            'telegramUsername' => $tu,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

$token = bin2hex(random_bytes(16));
$hash = mocker_telegram_hash_token($token);
$exp = time() + 1800;

$upd = $pdo->prepare(
    'UPDATE users SET telegram_pending_token_hash = :h, telegram_pending_expires = :e WHERE id = :id'
);
$upd->execute([':h' => $hash, ':e' => $exp, ':id' => $uid]);
if ($upd->rowCount() < 1) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'db_write'], JSON_UNESCAPED_UNICODE);
    exit;
}

$check = $pdo->prepare(
    'SELECT telegram_pending_token_hash FROM users WHERE id = :id AND telegram_pending_expires = :e LIMIT 1'
);
$check->execute([':id' => $uid, ':e' => $exp]);
$saved = $check->fetch(PDO::FETCH_ASSOC);
if (!$saved || (string) ($saved['telegram_pending_token_hash'] ?? '') !== $hash) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'db_write'], JSON_UNESCAPED_UNICODE);
    exit;
}

$bot = mocker_telegram_bot_username();
$deepLink = 'https://t.me/' . rawurlencode($bot) . '?start=' . rawurlencode($token);

echo json_encode(
    [
        'ok' => true,
        'verified' => false,
        'deepLink' => $deepLink,
        'botUsername' => $bot,
        'expiresAt' => $exp,
    ],
    JSON_UNESCAPED_UNICODE
);
