<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/telegram_invite_lib.php';
require_once __DIR__ . '/telegram_lib.php';

mocker_admin_require_permission('telegram-invites');

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

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

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

if ($method === 'GET') {
    $settings = mocker_telegram_invite_settings_get($pdo);
    $leaderboard = mocker_telegram_invite_leaderboard($pdo, 10);
    $eventsSt = $pdo->query(
        'SELECT e.id, e.inviter_user_id, u.username AS inviter_username,
                e.invitee_telegram_user_id, e.invitee_username, e.coins_awarded, e.created_at
         FROM telegram_invite_events e
         INNER JOIN users u ON u.id = e.inviter_user_id
         ORDER BY e.id DESC LIMIT 100'
    );
    $events = [];
    foreach ($eventsSt ? $eventsSt->fetchAll(PDO::FETCH_ASSOC) : [] as $r) {
        $events[] = [
            'id' => (int) $r['id'],
            'inviterUserId' => (int) $r['inviter_user_id'],
            'inviterUsername' => (string) $r['inviter_username'],
            'inviteeTelegramUserId' => (int) $r['invitee_telegram_user_id'],
            'inviteeUsername' => $r['invitee_username'] !== null ? (string) $r['invitee_username'] : '',
            'coinsAwarded' => (int) $r['coins_awarded'],
            'createdAt' => (int) $r['created_at'],
        ];
    }
    $totalSt = $pdo->query('SELECT COUNT(*) FROM telegram_invite_events');
    $totalInvites = $totalSt ? (int) $totalSt->fetchColumn() : 0;

    echo json_encode(
        [
            'ok' => true,
            'settings' => [
                'isActive' => $settings['is_active'],
                'groupChatId' => $settings['group_chat_id'],
                'coinsPerInvite' => $settings['coins_per_invite'],
                'updatedAt' => $settings['updated_at'],
            ],
            'botConfigured' => mocker_telegram_is_configured(),
            'botUsername' => mocker_telegram_bot_username(),
            'widgetDomain' => mocker_telegram_widget_domain(),
            'leaderboard' => $leaderboard,
            'events' => $events,
            'totalInvites' => $totalInvites,
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

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

mocker_require_csrf_post();

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

if ($action === 'save_settings') {
    mocker_telegram_invite_settings_save($pdo, [
        'is_active' => !empty($input['isActive']),
        'group_chat_id' => (string) ($input['groupChatId'] ?? ''),
        'coins_per_invite' => (int) ($input['coinsPerInvite'] ?? 50),
    ]);
    $settings = mocker_telegram_invite_settings_get($pdo);
    echo json_encode(
        [
            'ok' => true,
            'settings' => [
                'isActive' => $settings['is_active'],
                'groupChatId' => $settings['group_chat_id'],
                'coinsPerInvite' => $settings['coins_per_invite'],
                'updatedAt' => $settings['updated_at'],
            ],
        ],
        JSON_UNESCAPED_UNICODE
    );
    exit;
}

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