<?php
declare(strict_types=1);

namespace App\Modules\Tournaments\Models;

use App\Core\Model;
use App\Core\App;

class TournamentMatch extends Model
{
    protected static string $table = 'tournament_matches';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'tournament_id',
        'round_number',
        'match_number',
        'group_name',
        'participant_a_id',
        'participant_b_id',
        'scheduled_date',
        'scheduled_time',
        'facility_id',
        'score_a',
        'score_b',
        'winner_participant_id',
        'is_draw',
        'status',
        'referee_name',
        'match_notes',
        'completed_at',
    ];

    /**
     * Get match statuses with Arabic labels.
     */
    public static function getStatuses(): array
    {
        return [
            'scheduled'   => 'مجدول',
            'in_progress' => 'جاري',
            'completed'   => 'منتهي',
            'cancelled'   => 'ملغي',
            'walkover'    => 'انسحاب',
        ];
    }

    /**
     * Get status badge color.
     */
    public static function getStatusColor(string $status): string
    {
        $colors = [
            'scheduled'   => '#0284C7',
            'in_progress' => '#7C3AED',
            'completed'   => '#059669',
            'cancelled'   => '#DC2626',
            'walkover'    => '#D97706',
        ];
        return $colors[$status] ?? '#6B7280';
    }

    /**
     * Get all matches for a tournament.
     */
    public static function getForTournament(int $tournamentId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tm.*,
                    pa.player_id AS player_a_id,
                    COALESCE(pa.team_name, pla.full_name_ar) AS participant_a_name,
                    pb.player_id AS player_b_id,
                    COALESCE(pb.team_name, plb.full_name_ar) AS participant_b_name,
                    COALESCE(pw.team_name, plw.full_name_ar) AS winner_name
             FROM tournament_matches tm
             LEFT JOIN tournament_participants pa ON pa.id = tm.participant_a_id
             LEFT JOIN players pla ON pla.id = pa.player_id
             LEFT JOIN tournament_participants pb ON pb.id = tm.participant_b_id
             LEFT JOIN players plb ON plb.id = pb.player_id
             LEFT JOIN tournament_participants pw ON pw.id = tm.winner_participant_id
             LEFT JOIN players plw ON plw.id = pw.player_id
             WHERE tm.tournament_id = ?
             ORDER BY tm.round_number ASC, tm.match_number ASC",
            [$tournamentId]
        );
    }

    /**
     * Get matches for a specific round.
     */
    public static function getForRound(int $tournamentId, int $round): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tm.*,
                    COALESCE(pa.team_name, pla.full_name_ar) AS participant_a_name,
                    COALESCE(pb.team_name, plb.full_name_ar) AS participant_b_name,
                    COALESCE(pw.team_name, plw.full_name_ar) AS winner_name
             FROM tournament_matches tm
             LEFT JOIN tournament_participants pa ON pa.id = tm.participant_a_id
             LEFT JOIN players pla ON pla.id = pa.player_id
             LEFT JOIN tournament_participants pb ON pb.id = tm.participant_b_id
             LEFT JOIN players plb ON plb.id = pb.player_id
             LEFT JOIN tournament_participants pw ON pw.id = tm.winner_participant_id
             LEFT JOIN players plw ON plw.id = pw.player_id
             WHERE tm.tournament_id = ? AND tm.round_number = ?
             ORDER BY tm.match_number ASC",
            [$tournamentId, $round]
        );
    }

    /**
     * Get bracket structure for a knockout tournament.
     * Returns matches grouped by round.
     */
    public static function getBracket(int $tournamentId): array
    {
        $db = App::getInstance()->db();
        $matches = $db->select(
            "SELECT tm.*,
                    COALESCE(pa.team_name, pla.full_name_ar) AS participant_a_name,
                    pa.seed_number AS seed_a,
                    COALESCE(pb.team_name, plb.full_name_ar) AS participant_b_name,
                    pb.seed_number AS seed_b,
                    COALESCE(pw.team_name, plw.full_name_ar) AS winner_name
             FROM tournament_matches tm
             LEFT JOIN tournament_participants pa ON pa.id = tm.participant_a_id
             LEFT JOIN players pla ON pla.id = pa.player_id
             LEFT JOIN tournament_participants pb ON pb.id = tm.participant_b_id
             LEFT JOIN players plb ON plb.id = pb.player_id
             LEFT JOIN tournament_participants pw ON pw.id = tm.winner_participant_id
             LEFT JOIN players plw ON plw.id = pw.player_id
             WHERE tm.tournament_id = ?
             ORDER BY tm.round_number ASC, tm.match_number ASC",
            [$tournamentId]
        );

        // Group by round
        $bracket = [];
        foreach ($matches as $match) {
            $round = (int) $match['round_number'];
            $bracket[$round][] = $match;
        }

        return $bracket;
    }
}
