<?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) ?: [];
if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'payload'], JSON_UNESCAPED_UNICODE);
    exit;
}

$widget = [];
foreach (['id', 'first_name', 'last_name', 'username', 'photo_url', 'auth_date', 'hash'] as $key) {
    if (!array_key_exists($key, $input)) {
        continue;
    }
    $val = $input[$key];
    if ($val === null || $val === '') {
        continue;
    }
    $widget[$key] = is_scalar($val) ? (string) $val : '';
}

if (!isset($widget['id'], $widget['auth_date'], $widget['hash'])) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'payload'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!mocker_telegram_verify_login_widget($widget)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'telegram_invalid'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

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

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

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

session_regenerate_id(true);
$_SESSION['mocker_user_id'] = $uid;

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