<?php

declare(strict_types=1);

namespace Tournament\User;

use PDO;

class UserTournamentStatus
{
    public function __construct(
        private PDO $pdo
    ) {
    }


    public function get(
        int $eventId,
        int $userId
    ): array {

        /*
         * پیدا کردن بازیکن
         */
        $st = $this->pdo->prepare("
            SELECT
                ep.id AS event_player_id,
                tp.id AS tournament_participant_id,
                tp.status

            FROM event_players ep

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

            WHERE ep.ev_id = ?
              AND ep.user_id = ?

            LIMIT 1
        ");

        $st->execute([
            $eventId,
            $userId
        ]);

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


        if (!$player) {

            return [
                'status' => 'not_joined'
            ];
        }


        /*
         * Stage فعلی
         */
        $st = $this->pdo->prepare("
            SELECT
                id,
                name,
                type,
                format,
                stage_order,
                status

            FROM tournament_stages

            WHERE ev_id = ?

            ORDER BY stage_order ASC
        ");

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

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



        $currentStage = null;


        foreach ($stages as $stage) {

            if (
                $stage['status'] === 'active'
            ) {
                $currentStage = $stage;
                break;
            }
        }


        /*
         * اگر Stage فعال نبود
         */
        if (!$currentStage && $stages) {

            foreach ($stages as $stage) {

                if (
                    $stage['status'] !== 'completed'
                ) {
                    $currentStage = $stage;
                    break;
                }
            }
        }



        /*
         * Progress
         */
        $played = 0;
        $total = 0;


        if (
            $currentStage
            &&
            $currentStage['format'] === 'battle_royale'
        ) {


            $st = $this->pdo->prepare("
                SELECT
                    COUNT(*) 

                FROM tournament_br_rooms r

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

                WHERE r.stage_id = ?
                  AND rp.tournament_participant_id = ?
                  AND r.status = 'completed'
            ");

            $st->execute([
                $currentStage['id'],
                $player['tournament_participant_id']
            ]);

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



            $st = $this->pdo->prepare("
                SELECT
                    matches_per_player

                FROM tournament_stages

                WHERE id = ?

            ");

            $st->execute([
                $currentStage['id']
            ]);

            $total =
                (int)$st->fetchColumn();
        }



        /*
         * Score
         */
        $score = 0;


        if ($currentStage) {

            $st = $this->pdo->prepare("
                SELECT
                    COALESCE(
                        SUM(score),
                        0
                    )

                FROM tournament_br_results br

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

                WHERE br.tournament_participant_id = ?
                  AND br.status = 'confirmed'

            ");

            $st->execute([
                $player['tournament_participant_id']
            ]);

            $score =
                (float)$st->fetchColumn();
        }



        /*
         * Rank
         */
        $rank = null;


        if ($currentStage) {


            $st = $this->pdo->prepare("
                SELECT
                    tournament_participant_id,
                    SUM(score) total_score

                FROM tournament_br_results

                WHERE status = 'confirmed'

                GROUP BY tournament_participant_id

                ORDER BY total_score DESC
            ");

            $st->execute();


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


            $position = 1;

            foreach ($rows as $row) {

                if (
                    (int)$row['tournament_participant_id']
                    ===
                    (int)$player['tournament_participant_id']
                ) {

                    $rank = $position;
                    break;
                }

                $position++;
            }
        }



        return [
            'joined' =>
                true,

            'status' =>
                $status,

            'current_stage' =>
                $currentStage,

            'stages' =>
                $stages,

            'played' =>
                $played,

            'total' =>
                $total,

            'rank' =>
                $rank,

            'score' =>
                $score,

            'participant_id' =>
                (int)$player['tournament_participant_id']
        ];
    }
}