<?php

declare(strict_types=1);

function renderUserLeaderboard(
    PDO $pdo,
    int $chat_id,
    int $mid,
    int $eid,
    int $uid,
    int $page = 1
): void {
    try {

        $page = max(1, $page);
        $perPage = 10;

        /*
         * ==========================================
         * Event
         * ==========================================
         */
        $st = $pdo->prepare("
            SELECT
                id,
                name
            FROM events
            WHERE id = ?
            LIMIT 1
        ");

        $st->execute([
            $eid
        ]);

        $event =
            $st->fetch(PDO::FETCH_ASSOC);

        if (!$event) {
            throw new RuntimeException(
                'ایونت پیدا نشد.'
            );
        }

        /*
         * ==========================================
         * Tournament Participant
         * ==========================================
         */
        $st = $pdo->prepare("
            SELECT
                tp.id AS tournament_participant_id,
                tp.status AS participant_status
            FROM tournament_participants tp
            INNER JOIN event_players ep
                ON ep.id = tp.event_player_id
            WHERE ep.ev_id = ?
              AND ep.user_id = ?
            ORDER BY tp.id DESC
            LIMIT 1
        ");

        $st->execute([
            $eid,
            $uid
        ]);

        $participant =
            $st->fetch(PDO::FETCH_ASSOC);

        if (!$participant) {
            throw new RuntimeException(
                'شما در این تورنومنت Participant نیستید.'
            );
        }

        $participantId =
            (int) (
                $participant[
                    'tournament_participant_id'
                ]
            );

        /*
         * ==========================================
         * Current Stage
         * ==========================================
         */

        $stage = null;

        /*
         * ابتدا Stageای که Participant در آن فعال است.
         */
        $st = $pdo->prepare("
            SELECT
                ts.*
            FROM tournament_stage_participants tsp
            INNER JOIN tournament_stages ts
                ON ts.id = tsp.stage_id
            WHERE tsp.tournament_participant_id = ?
              AND tsp.status = 'active'
            ORDER BY
                ts.stage_order ASC
            LIMIT 1
        ");

        $st->execute([
            $participantId
        ]);

        $stage =
            $st->fetch(PDO::FETCH_ASSOC);

        /*
         * اگر پیدا نشد → Stage فعال Event
         */
        if (!$stage) {

            $st = $pdo->prepare("
                SELECT
                    *
                FROM tournament_stages
                WHERE ev_id = ?
                  AND status = 'active'
                ORDER BY
                    stage_order ASC
                LIMIT 1
            ");

            $st->execute([
                $eid
            ]);

            $stage =
                $st->fetch(PDO::FETCH_ASSOC);
        }

        /*
         * اگر پیدا نشد → آخرین Stage تکمیل‌شده
         */
        if (!$stage) {

            $st = $pdo->prepare("
                SELECT
                    *
                FROM tournament_stages
                WHERE ev_id = ?
                  AND status = 'completed'
                ORDER BY
                    stage_order DESC
                LIMIT 1
            ");

            $st->execute([
                $eid
            ]);

            $stage =
                $st->fetch(PDO::FETCH_ASSOC);
        }

        if (!$stage) {
            throw new RuntimeException(
                'هیچ Stageای برای نمایش Leaderboard وجود ندارد.'
            );
        }

        $stageId =
            (int) $stage['id'];

        $stageName =
            (string) (
                $stage['name']
                ?? 'Stage'
            );

        $stageFormat =
            (string) (
                $stage['format']
                ?? ''
            );

        /*
         * ==========================================
         * فقط Battle Royale
         * ==========================================
         */
        if (
            $stageFormat !==
            'battle_royale'
        ) {
            throw new RuntimeException(
                'Leaderboard فعلاً برای Battle Royale در دسترس است.'
            );
        }

        /*
         * ==========================================
         * پیدا کردن Group کاربر
         * ==========================================
         *
         * room_number = Group
         *
         * چون Group در تمام Roundها ثابت است،
         * Participant باید فقط یک room_number داشته باشد.
         */
        $st = $pdo->prepare("
            SELECT
                MIN(br.room_number) AS group_number,
                COUNT(
                    DISTINCT br.room_number
                ) AS different_groups
            FROM tournament_br_room_participants rp
            INNER JOIN tournament_br_rooms br
                ON br.id = rp.room_id
            WHERE br.stage_id = ?
              AND rp.tournament_participant_id = ?
        ");

        $st->execute([
            $stageId,
            $participantId
        ]);

        $groupInfo =
            $st->fetch(PDO::FETCH_ASSOC);

        if (
            !$groupInfo
            || empty(
                $groupInfo['group_number']
            )
        ) {
            throw new RuntimeException(
                'Group شما هنوز برای این Stage ساخته نشده است.'
            );
        }

        $groupNumber =
            (int) (
                $groupInfo['group_number']
            );

        $differentGroups =
            (int) (
                $groupInfo['different_groups']
                ?? 0
            );

        if (
            $differentGroups > 1
        ) {
            throw new RuntimeException(
                'Group شما در این Stage ثابت نیست.'
            );
        }

        /*
         * ==========================================
         * Leaderboard Group
         * ==========================================
         *
         * همه اطلاعات بازیکنان را
         * در یک Query می‌گیریم:
         *
         * - IGN
         * - Score
         * - Kills
         * - Games
         * - Placement
         * - Rank
         *
         * فقط بازیکنان همین Group.
         */
        $st = $pdo->prepare("
            SELECT DISTINCT
                bl.tournament_participant_id,

                ep.ign,

                bl.total_score,
                bl.total_kills,
                bl.games_played,
                bl.best_placement,
                bl.rank_position

            FROM tournament_br_leaderboards bl

            INNER JOIN tournament_participants tp
                ON tp.id =
                    bl.tournament_participant_id

            INNER JOIN event_players ep
                ON ep.id =
                    tp.event_player_id

            INNER JOIN tournament_br_room_participants rp
                ON rp.tournament_participant_id =
                    bl.tournament_participant_id

            INNER JOIN tournament_br_rooms br
                ON br.id = rp.room_id

            WHERE bl.stage_id = ?
              AND br.stage_id = ?
              AND br.room_number = ?

            ORDER BY
                bl.rank_position ASC,
                bl.tournament_participant_id ASC
        ");

        $st->execute([
            $stageId,
            $stageId,
            $groupNumber
        ]);

        $players =
            $st->fetchAll(PDO::FETCH_ASSOC);

        /*
         * ==========================================
         * Leaderboard هنوز ساخته نشده
         * ==========================================
         */
        if (!$players) {

            $txt =
                "<blockquote>🏆 <b>رتبه‌بندی | Group $groupNumber</b></blockquote> \n\n"

                . "<blockquote>👤 <b>وضعیت شما</b></blockquote>\n"
                . "⏳ هنوز رتبه‌بندی این Stage آماده نشده است.";

            $keyboard = [
                [
                    [
                        'text' =>
                            '🔄 بروزرسانی',
                        'callback_data' =>
                            'user_leaderboard:' .
                            $eid .
                            ':1'
                    ]
                ],
                [
                    [
                        'text' =>
                            '🔙 وضعیت شما',
                        'callback_data' =>
                            'user_tournament_status:' .
                            $eid
                    ]
                ]
            ];

            editMessageText(
                $chat_id,
                $mid,
                $txt,
                [
                    'inline_keyboard' =>
                        $keyboard
                ]
            );

            return;
        }

        /*
         * ==========================================
         * تعداد بازیکنان Group
         * ==========================================
         */
        $groupTotal =
            count($players);

        /*
         * ==========================================
         * پیدا کردن User
         * ==========================================
         */
        $userRow = null;

        foreach (
            $players as $player
        ) {

            if (
                (int) (
                    $player[
                        'tournament_participant_id'
                    ]
                )
                ===
                $participantId
            ) {
                $userRow =
                    $player;

                break;
            }
        }

        /*
         * ==========================================
         * وضعیت User
         * ==========================================
         */
        if (!$userRow) {

            $userRankText =
                '⏳ هنوز رتبه‌ای برای شما ثبت نشده است.';

            $userScoreText =
                '0';

            $userKills =
                0;

        } else {

            $userRank =
                (int) (
                    $userRow[
                        'rank_position'
                    ]
                    ?? 0
                );

            if (
                $userRank > 0
            ) {

                $userRankText =
                    "#{$userRank} از {$groupTotal}";

            } else {

                $userRankText =
                    '⏳ هنوز رتبه‌ای برای شما ثبت نشده است.';
            }

            $userScore =
                (float) (
                    $userRow[
                        'total_score'
                    ]
                    ?? 0
                );

            $userScoreText =
                rtrim(
                    rtrim(
                        number_format(
                            $userScore,
                            2,
                            '.',
                            ','
                        ),
                        '0'
                    ),
                    '.'
                );

            if (
                $userScoreText === ''
            ) {
                $userScoreText =
                    '0';
            }

            $userKills =
                (int) (
                    $userRow[
                        'total_kills'
                    ]
                    ?? 0
                );
        }

        /*
         * ==========================================
         * Pagination
         * ==========================================
         */
        $totalPages =
            max(
                1,
                (int) ceil(
                    $groupTotal /
                    $perPage
                )
            );

        if (
            $page > $totalPages
        ) {
            $page =
                $totalPages;
        }

        $offset =
            (
                $page - 1
            )
            *
            $perPage;

        $pagePlayers =
            array_slice(
                $players,
                $offset,
                $perPage
            );

        /*
         * ==========================================
         * متن Header
         * ==========================================
         */
        $txt =
            "🏆 <b>رتبه‌بندی</b>\n\n"

            . "🔥 <b>"
            . htmlspecialchars(
                $stageName,
                ENT_QUOTES |
                ENT_SUBSTITUTE,
                'UTF-8'
            )
            . "</b>\n"

            . "👥 <b>Group "
            . $groupNumber
            . "</b>\n\n"

            . "━━━━━━━━━━━━\n\n"

            . "👤 <b>وضعیت شما</b>\n"

            . "🏆 رتبه: <b>"
            . $userRankText
            . "</b>\n"

            . "⭐ امتیاز: <b>"
            . $userScoreText
            . "</b>\n"

            . "💀 Kills: <b>"
            . number_format(
                $userKills
            )
            . "</b>\n\n"

            . "━━━━━━━━━━━━\n\n"

            . "📋 <b>رتبه‌ها</b>\n\n";

        /*
         * ==========================================
         * Players
         * ==========================================
         */
        foreach (
            $pagePlayers as $player
        ) {

            $rank =
                (int) (
                    $player[
                        'rank_position'
                    ]
                    ?? 0
                );

            $playerId =
                (int) (
                    $player[
                        'tournament_participant_id'
                    ]
                );

            $ign =
                trim(
                    (string) (
                        $player['ign']
                        ?? ''
                    )
                );

            if (
                $ign === ''
            ) {
                $ign =
                    'Player #' .
                    $playerId;
            }

            $ign =
                htmlspecialchars(
                    $ign,
                    ENT_QUOTES |
                    ENT_SUBSTITUTE,
                    'UTF-8'
                );

            $score =
                (float) (
                    $player[
                        'total_score'
                    ]
                    ?? 0
                );

            $scoreText =
                rtrim(
                    rtrim(
                        number_format(
                            $score,
                            2,
                            '.',
                            ','
                        ),
                        '0'
                    ),
                    '.'
                );

            if (
                $scoreText === ''
            ) {
                $scoreText =
                    '0';
            }

            $kills =
                (int) (
                    $player[
                        'total_kills'
                    ]
                    ?? 0
                );

            /*
             * User Highlight
             */
            if (
                $playerId ===
                $participantId
            ) {

                $txt .=
                    "👉 <b>#"
                    . $rank
                    . " "
                    . $ign
                    . "</b>\n"

                    . "⭐ "
                    . $scoreText
                    . " | 💀 "
                    . $kills
                    . " Kills\n\n";

            } else {

                $txt .=
                    "<b>#"
                    . $rank
                    . "</b> "
                    . $ign
                    . "\n"

                    . "⭐ "
                    . $scoreText
                    . " | 💀 "
                    . $kills
                    . " Kills\n\n";
            }
        }

        /*
         * ==========================================
         * Page
         * ==========================================
         */
        $txt .=
            "📄 <b>صفحه "
            . $page
            . " از "
            . $totalPages
            . "</b>";

        /*
         * ==========================================
         * Keyboard
         * ==========================================
         */
        $keyboard = [];

        /*
         * Pagination
         */
        $paginationRow = [];

        if (
            $page > 1
        ) {

            $paginationRow[] = [
                'text' =>
                    '⬅️ قبلی',

                'callback_data' =>
                    'user_leaderboard:'
                    . $eid
                    . ':'
                    . (
                        $page - 1
                    )
            ];
        }

        $paginationRow[] = [
            'text' =>
                $page .
                '/' .
                $totalPages,

            'callback_data' =>
                'user_leaderboard:'
                . $eid
                . ':'
                . $page
        ];

        if (
            $page <
            $totalPages
        ) {

            $paginationRow[] = [
                'text' =>
                    'بعدی ➡️',

                'callback_data' =>
                    'user_leaderboard:'
                    . $eid
                    . ':'
                    . (
                        $page + 1
                    )
            ];
        }

        $keyboard[] =
            $paginationRow;

        /*
         * بروزرسانی
         */
        $keyboard[] = [
            [
                'text' =>
                    '🔄 بروزرسانی',

                'callback_data' =>
                    'user_leaderboard:'
                    . $eid
                    . ':'
                    . $page
            ]
        ];

        /*
         * بازگشت
         */
        $keyboard[] = [
            [
                'text' =>
                    '🔙 وضعیت شما',

                'callback_data' =>
                    'user_tournament_status:'
                    . $eid
            ]
        ];

        /*
         * ==========================================
         * Edit Message
         * ==========================================
         */
        $result =
            editMessageText(
                $chat_id,
                $mid,
                $txt,
                [
                    'inline_keyboard' =>
                        $keyboard
                ]
            );

        error_log(
            '[USER LEADERBOARD] API RESULT: '
            . print_r(
                $result,
                true
            )
        );

    } catch (Throwable $e) {

        error_log(
            '[USER LEADERBOARD ERROR] '
            . $e->getMessage()
            . "\n"
            . $e->getTraceAsString()
        );

        editMessageText(
            $chat_id,
            $mid,
            "❌ <b>نمایش رتبه‌بندی انجام نشد.</b>\n\n"
            . "<code>"
            . htmlspecialchars(
                $e->getMessage(),
                ENT_QUOTES |
                ENT_SUBSTITUTE,
                'UTF-8'
            )
            . "</code>",
            [
                'inline_keyboard' => [
                    [
                        [
                            'text' =>
                                '🔙 وضعیت شما',
                            'callback_data' =>
                                'user_tournament_status:' .
                                $eid
                        ]
                    ]
                ]
            ]
        );
    }
}