<?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';

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

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

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$mode = isset($input['mode']) ? strtolower(trim((string) $input['mode'])) : 'login';
if (!in_array($mode, ['login', 'register'], true)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'mode'], 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_telegram_auth_pending_cleanup($pdo);

$token = bin2hex(random_bytes(16));
$hash = mocker_telegram_hash_token($token);
$pollKey = bin2hex(random_bytes(16));
$pollHash = hash('sha256', $pollKey);
$exp = time() + 1800;

$ins = $pdo->prepare(
    'INSERT INTO telegram_auth_pending (token_hash, mode, poll_key_hash, created_at, expires_at)
     VALUES (:h, :m, :p, :c, :e)'
);
try {
    $ins->execute([
        ':h' => $hash,
        ':m' => $mode,
        ':p' => $pollHash,
        ':c' => time(),
        ':e' => $exp,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'db_write'], JSON_UNESCAPED_UNICODE);
    exit;
}

$_SESSION['tg_auth_poll'] = $pollKey;
$_SESSION['tg_auth_token_hash'] = $hash;

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

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