<?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'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

$token = isset($_GET['token']) ? trim((string) $_GET['token']) : '';
$token = mocker_telegram_normalize_verify_token($token) ?? '';
if ($token === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'token'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pollKey = isset($_SESSION['tg_auth_poll']) ? (string) $_SESSION['tg_auth_poll'] : '';
if ($pollKey === '') {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'session'], JSON_UNESCAPED_UNICODE);
    exit;
}

$hash = mocker_telegram_hash_token($token);
$pollHash = hash('sha256', $pollKey);
$now = time();

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 mode, expires_at, completed_user_id, poll_key_hash, completed_at, completed_is_new
     FROM telegram_auth_pending WHERE token_hash = :h LIMIT 1'
);
$st->execute([':h' => $hash]);
$pending = $st->fetch(PDO::FETCH_ASSOC);

if (!$pending || !hash_equals((string) ($pending['poll_key_hash'] ?? ''), $pollHash)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'session'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ((int) ($pending['expires_at'] ?? 0) <= $now) {
    $pdo->prepare('DELETE FROM telegram_auth_pending WHERE token_hash = :h')->execute([':h' => $hash]);
    unset($_SESSION['tg_auth_poll'], $_SESSION['tg_auth_token_hash']);
    http_response_code(410);
    echo json_encode(['ok' => false, 'error' => 'expired'], JSON_UNESCAPED_UNICODE);
    exit;
}

$uid = (int) ($pending['completed_user_id'] ?? 0);
if ($uid <= 0) {
    echo json_encode(['ok' => true, 'pending' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

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

$isNew = (int) ($pending['completed_is_new'] ?? 0) === 1;

session_regenerate_id(true);
$_SESSION['mocker_user_id'] = $uid;
unset($_SESSION['tg_auth_poll'], $_SESSION['tg_auth_token_hash']);

$pdo->prepare('DELETE FROM telegram_auth_pending WHERE token_hash = :h')->execute([':h' => $hash]);

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