<?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_invite_lib.php';

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

$method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$uid = isset($_SESSION['mocker_user_id']) ? (int) $_SESSION['mocker_user_id'] : 0;

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

$settings = mocker_telegram_invite_settings_get($pdo);
$botConfigured = mocker_telegram_is_configured();

if ($method === 'GET') {
    $leaderboard = mocker_telegram_invite_leaderboard($pdo, 10);
    $payload = [
        'ok' => true,
        'csrfToken' => mocker_csrf_token(),
        'campaign' => [
            'active' => $settings['is_active'],
            'coinsPerInvite' => $settings['coins_per_invite'],
            'botConfigured' => $botConfigured,
            'groupConfigured' => $settings['group_chat_id'] !== '',
        ],
        'leaderboard' => $leaderboard,
    ];
    if ($uid > 0) {
        $st = $pdo->prepare(
            'SELECT telegram_verified_at, telegram_username FROM users WHERE id = :id LIMIT 1'
        );
        $st->execute([':id' => $uid]);
        $u = $st->fetch(PDO::FETCH_ASSOC);
        $verified = $u && isset($u['telegram_verified_at']) && (int) $u['telegram_verified_at'] > 0;
        $stats = mocker_telegram_invite_user_stats($pdo, $uid);
        $payload['authenticated'] = true;
        $payload['telegram'] = [
            'verified' => $verified,
            'username' => $verified && !empty($u['telegram_username']) ? (string) $u['telegram_username'] : null,
        ];
        $payload['stats'] = [
            'inviteCount' => $stats['invite_count'],
            'coinsEarned' => $stats['coins_earned'],
            'inviteLink' => $stats['invite_link'],
            'rank' => $stats['rank'],
        ];
    } else {
        $payload['authenticated'] = false;
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

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

mocker_require_csrf_post();

if ($uid <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'auth', 'csrfToken' => mocker_csrf_token()], JSON_UNESCAPED_UNICODE);
    exit;
}

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$action = (string) ($input['action'] ?? 'create_link');

if ($action === 'create_link') {
    $res = mocker_telegram_invite_create_link_for_user($pdo, $uid);
    if (!$res['ok']) {
        $err = (string) ($res['error'] ?? 'fail');
        $code = $err === 'telegram_required' ? 403 : ($err === 'campaign_inactive' || $err === 'group_not_set' ? 503 : 400);
        http_response_code($code);
        echo json_encode(
            [
                'ok' => false,
                'error' => $err,
                'description' => $res['description'] ?? null,
                'csrfToken' => mocker_csrf_token(),
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }
    $stats = mocker_telegram_invite_user_stats($pdo, $uid);
    echo json_encode(
        [
            'ok' => true,
            'inviteLink' => $res['invite_link'],
            'stats' => [
                'inviteCount' => $stats['invite_count'],
                'coinsEarned' => $stats['coins_earned'],
                'inviteLink' => $stats['invite_link'],
                'rank' => $stats['rank'],
            ],
            'csrfToken' => mocker_csrf_token(),
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'action', 'csrfToken' => mocker_csrf_token()], JSON_UNESCAPED_UNICODE);
