<?php

declare(strict_types=1);

function renderUserGames(
    PDO $pdo,
    int $chat_id,
    int $mid,
    int $eid,
    int $uid
): void {
    try {

        /*
         * ==========================================
         * 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
            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
        ]);

        $participantId =
            (int) (
                $st->fetchColumn()
                ?: 0
            );

        if ($participantId <= 0) {
            throw new RuntimeException(
                'شما در این تورنومنت Participant نیستید.'
            );
        }

        /*
         * ==========================================
         * 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ای برای نمایش بازی‌ها وجود ندارد.'
            );
        }

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

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

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

        if (
            $stageFormat !==
            'battle_royale'
        ) {
            throw new RuntimeException(
                'بازی‌های شخصی فعلاً برای Battle Royale در دسترس است.'
            );
        }

        /*
         * ==========================================
         * Group
         * ==========================================
         */
        $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 ثابت نیست.'
            );
        }

        /*
         * ==========================================
         * Games
         * ==========================================
         *
         * اطلاعات Room + Schedule + Map +
         * Credential + Result
         */
        $st = $pdo->prepare("
            SELECT
                br.id AS room_id,
                br.round_number,
                br.room_number,
                br.status AS room_status,

                br.scheduled_at,
                br.room_game_id,
                br.room_password,
                br.map_name,

                r.placement,
                r.kills,
                r.score,
                r.status AS result_status

            FROM tournament_br_rooms br

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

            LEFT JOIN tournament_br_results r
                ON r.room_id = br.id
                AND r.tournament_participant_id = ?

            WHERE br.stage_id = ?
              AND br.room_number = ?
              AND rp.tournament_participant_id = ?

            ORDER BY
                br.round_number ASC
        ");

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

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

        if (!$games) {
            throw new RuntimeException(
                'هنوز بازی‌ای برای شما ساخته نشده است.'
            );
        }

        /*
         * ==========================================
         * Current Leaderboard
         * ==========================================
         */
        $st = $pdo->prepare("
            SELECT
                r.tournament_participant_id,

                COALESCE(
                    SUM(r.score),
                    0
                ) AS total_score,

                COALESCE(
                    SUM(r.kills),
                    0
                ) AS total_kills,

                MIN(r.placement)
                    AS best_placement,

                COUNT(r.id)
                    AS games_played

            FROM tournament_br_results r

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

            WHERE br.stage_id = ?
              AND br.room_number = ?
              AND r.status = 'confirmed'

            GROUP BY
                r.tournament_participant_id

            ORDER BY
                total_score DESC,
                total_kills DESC,
                best_placement ASC,
                r.tournament_participant_id ASC
        ");

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

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

        /*
         * ==========================================
         * User Current Rank
         * ==========================================
         */
        $currentRank = null;
        $currentScore = 0.0;
        $currentKills = 0;
        $currentPlayed = 0;

        foreach (
            $currentLeaderboard as $index =>
            $row
        ) {

            $rowParticipantId =
                (int) (
                    $row[
                        'tournament_participant_id'
                    ]
                );

            if (
                $rowParticipantId ===
                $participantId
            ) {

                $currentRank =
                    $index + 1;

                $currentScore =
                    (float) (
                        $row[
                            'total_score'
                        ]
                        ?? 0
                    );

                $currentKills =
                    (int) (
                        $row[
                            'total_kills'
                        ]
                        ?? 0
                    );

                $currentPlayed =
                    (int) (
                        $row[
                            'games_played'
                        ]
                        ?? 0
                    );

                break;
            }
        }

        /*
         * ==========================================
         * Group Total
         * ==========================================
         */
        $st = $pdo->prepare("
            SELECT COUNT(*)
            FROM tournament_br_room_participants rp

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

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

              AND br.round_number = (
                  SELECT MIN(round_number)
                  FROM tournament_br_rooms
                  WHERE stage_id = ?
              )
        ");

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

        $groupTotal =
            (int) $st->fetchColumn();

        /*
         * ==========================================
         * Total Games
         * ==========================================
         */
        $totalGames =
            max(
                1,
                (int) (
                    $stage[
                        'matches_per_player'
                    ]
                    ?? count($games)
                )
            );

        /*
         * ==========================================
         * Score
         * ==========================================
         */
        $scoreText =
            rtrim(
                rtrim(
                    number_format(
                        $currentScore,
                        2,
                        '.',
                        ','
                    ),
                    '0'
                ),
                '.'
            );

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

        /*
         * ==========================================
         * Rank
         * ==========================================
         */
        if (
            $currentRank !== null
        ) {

            $rankText =
                "#{$currentRank} از {$groupTotal}";

        } else {

            $rankText =
                'هنوز رتبه‌ای ثبت نشده';
        }

        /*
         * ==========================================
         * Header
         * ==========================================
         */
        $txt =
            "<blockquote>🎮 <b>بازی‌های من | Group "
            . $groupNumber
            . "</b></blockquote>\n\n"

            . "<blockquote>📊 <b>وضعیت فعلی</b></blockquote>\n"

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

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

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

            . "🎯 پیشرفت: <b>"
            . $currentPlayed
            . "/"
            . $totalGames
            . " بازی</b>\n\n"

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

        /*
         * ==========================================
         * Games
         * ==========================================
         */
        foreach (
            $games as $game
        ) {

            $round =
                (int) (
                    $game[
                        'round_number'
                    ]
                    ?? 0
                );

            $roomStatus =
                (string) (
                    $game[
                        'room_status'
                    ]
                    ?? ''
                );

            $resultStatus =
                (string) (
                    $game[
                        'result_status'
                    ]
                    ?? ''
                );

            $scheduledAt =
                trim(
                    (string) (
                        $game[
                            'scheduled_at'
                        ]
                        ?? ''
                    )
                );

            $roomGameId =
                trim(
                    (string) (
                        $game[
                            'room_game_id'
                        ]
                        ?? ''
                    )
                );

            $roomPassword =
                trim(
                    (string) (
                        $game[
                            'room_password'
                        ]
                        ?? ''
                    )
                );

            $mapName =
                trim(
                    (string) (
                        $game[
                            'map_name'
                        ]
                        ?? ''
                    )
                );

            /*
             * ======================================
             * Round Header
             * ======================================
             */
            $txt .=
                "<blockquote>🎮 <b>بازی "
                . $round
                . "</b></blockquote>\n";

            /*
             * ======================================
             * Map
             * ======================================
             */
            if (
                $mapName !== ''
            ) {

                $txt .=
                    "🗺 مپ: <b>"
                    . htmlspecialchars(
                        $mapName,
                        ENT_QUOTES |
                        ENT_SUBSTITUTE,
                        'UTF-8'
                    )
                    . "</b>\n";
            }

            /*
             * ======================================
             * Schedule
             * ======================================
             */
            if (
                $scheduledAt !== ''
            ) {

                $timestamp =
                    strtotime(
                        $scheduledAt
                    );

                if (
                    $timestamp !== false
                ) {

                    $jalaliDate =
                        jdate(
                            'j F Y',
                            $timestamp,
                            '',
                            'Asia/Tehran'
                        );

                    $jalaliTime =
                        jdate(
                            'H:i',
                            $timestamp,
                            '',
                            'Asia/Tehran'
                        );

                    $txt .=
                        "📅 تاریخ: <b>"
                        . htmlspecialchars(
                            $jalaliDate,
                            ENT_QUOTES |
                            ENT_SUBSTITUTE,
                            'UTF-8'
                        )
                        . "</b>\n"

                        . "🕒 ساعت: <b>"
                        . $jalaliTime
                        . "</b>\n";
                }

            } else {

                $txt .=
                    "📅 زمان برگزاری: <b>هنوز مشخص نشده</b>\n";
            }

            /*
             * ======================================
             * Credentials
             * ======================================
             */
            if (
                $roomGameId !== ''
                || $roomPassword !== ''
            ) {

                $txt .= "\n";
                $txt .= "🎫 <b>اطلاعات روم</b>\n";

                if (
                    $roomGameId !== ''
                ) {

                    $txt .=
                        "<blockquote>🆔 ID: <code>"
                        . htmlspecialchars(
                            $roomGameId,
                            ENT_QUOTES |
                            ENT_SUBSTITUTE,
                            'UTF-8'
                        )
                        . "</code></blockquote>\n";
                }

                if (
                    $roomPassword !== ''
                ) {

                    $txt .=
                        "<blockquote>🔐 Password: <code>"
                        . htmlspecialchars(
                            $roomPassword,
                            ENT_QUOTES |
                            ENT_SUBSTITUTE,
                            'UTF-8'
                        )
                        . "</code></blockquote>\n";
                }

            } else {

                $txt .=
                    "🎫 اطلاعات روم: <b>هنوز تنظیم نشده</b>\n";
            }

            /*
             * ======================================
             * Room Status
             * ======================================
             */
            $statusText =
                match (
                    $roomStatus
                ) {
                    'pending' =>
                        '⏳ در انتظار',

                    'ready' =>
                        '🟡 آماده برگزاری',

                    'active' =>
                        '🟢 در حال برگزاری',

                    'completed' =>
                        '✅ تکمیل شده',

                    'cancelled' =>
                        '❌ لغو شده',

                    default =>
                        '⚪ نامشخص',
                };

            $txt .=
                "📌 وضعیت: <b>"
                . $statusText
                . "</b>\n";

            /*
             * ======================================
             * Result
             * ======================================
             */
            $txt .= "\n";

            if (
                $resultStatus ===
                'confirmed'
            ) {

                $placement =
                    (int) (
                        $game[
                            'placement'
                        ]
                        ?? 0
                    );

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

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

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

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

                $txt .=
                    "✅ <b>نتیجه ثبت شده</b>\n\n"

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

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

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

            } elseif (
                $roomStatus ===
                'completed'
            ) {

                $txt .=
                    "🟡 <b>نتیجه در حال بررسی است.</b>\n";

            } elseif (
                $roomStatus ===
                'active'
            ) {

                $txt .=
                    "🟢 <b>بازی در حال برگزاری است.</b>\n";

            } elseif (
                $roomStatus ===
                'ready'
            ) {

                $txt .=
                    "🟡 <b>بازی آماده برگزاری است.</b>\n";

            } elseif (
                $roomStatus ===
                'cancelled'
            ) {

                $txt .=
                    "❌ <b>این بازی لغو شده است.</b>\n";

            } else {

                $txt .=
                    "⏳ <b>این بازی هنوز برگزار نشده است.</b>\n";
            }

            $txt .=
                "\n━━━━━━━━━━━━\n\n";
        }

        /*
         * ==========================================
         * Footer
         * ==========================================
         */

        $txt .=
            "<blockquote>📊 <b>مجموع عملکرد</b></blockquote>\n"

            . "🎮 "
            . $currentPlayed
            . "/"
            . $totalGames
            . " بازی\n"

            . "💀 "
            . number_format(
                $currentKills
            )
            . " Kills\n"

            . "⭐ "
            . $scoreText
            . " امتیاز";

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

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

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

    } catch (Throwable $e) {

        error_log(
            '[USER GAMES 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
                        ]
                    ]
                ]
            ]
        );
    }
}