<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/telegram_lib.php';
require_once __DIR__ . '/user_auth_lib.php';
require_once __DIR__ . '/level_lib.php';

header('Content-Type: application/json; charset=utf-8');

$telegramAuth = [
    'enabled' => mocker_telegram_is_configured(),
    'botUsername' => mocker_telegram_bot_username(),
    'widgetDomain' => mocker_telegram_widget_domain(),
];

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(
        ['ok' => false, 'error' => 'method', 'csrfToken' => mocker_csrf_token(), 'telegramAuth' => $telegramAuth],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;
if ($uid <= 0) {
    echo json_encode(
        [
            'ok' => true,
            'authenticated' => false,
            'csrfToken' => mocker_csrf_token(),
            'telegramAuth' => $telegramAuth,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

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

mocker_user_auth_migrate($pdo);

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

if (!$row) {
    unset($_SESSION['mocker_user_id']);
    echo json_encode(
        [
            'ok' => true,
            'authenticated' => false,
            'csrfToken' => mocker_csrf_token(),
            'telegramAuth' => $telegramAuth,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

$upd = $pdo->prepare('UPDATE users SET last_seen_at = :t WHERE id = :id');
$upd->execute([':t' => time(), ':id' => $uid]);
try {
    mocker_level_award_site_daily($pdo, $uid);
} catch (Throwable $e) {
    /* ignore */
}

$userPayload = mocker_user_auth_payload($pdo, $row);

echo json_encode(
    [
        'ok' => true,
        'authenticated' => true,
        'csrfToken' => mocker_csrf_token(),
        'needsProfileCompletion' => !empty($userPayload['needsProfileCompletion']),
        'needsPasswordChange' => !empty($userPayload['needsPasswordChange']),
        'telegramAuth' => $telegramAuth,
        'user' => $userPayload,
    ],
    JSON_UNESCAPED_UNICODE
);
