<?php
declare(strict_types=1);

namespace App\Modules\Tournaments\Models;

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

class TournamentParticipant extends Model
{
    protected static string $table = 'tournament_participants';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = false;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'tournament_id',
        'player_id',
        'team_name',
        'team_members_json',
        'seed_number',
        'registration_date',
        'status',
        'final_position',
        'points',
        'wins',
        'losses',
        'draws',
        'payment_id',
        'notes',
    ];

    /**
     * Get participant statuses with Arabic labels.
     */
    public static function getStatuses(): array
    {
        return [
            'registered'   => 'مسجل',
            'confirmed'    => 'مؤكد',
            'withdrawn'    => 'منسحب',
            'disqualified' => 'مستبعد',
            'eliminated'   => 'خارج البطولة',
            'winner'       => 'فائز',
            'runner_up'    => 'وصيف',
        ];
    }

    /**
     * Get all participants for a tournament.
     */
    public static function getForTournament(int $tournamentId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tp.*, p.full_name_ar AS player_name, p.date_of_birth, p.gender
             FROM tournament_participants tp
             LEFT JOIN players p ON p.id = tp.player_id
             WHERE tp.tournament_id = ?
             ORDER BY tp.seed_number ASC, tp.registration_date ASC",
            [$tournamentId]
        );
    }

    /**
     * Get standings for a tournament (ordered by points, then wins, then goal diff).
     */
    public static function getStandings(int $tournamentId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT tp.*, p.full_name_ar AS player_name
             FROM tournament_participants tp
             LEFT JOIN players p ON p.id = tp.player_id
             WHERE tp.tournament_id = ? AND tp.status NOT IN ('withdrawn', 'disqualified')
             ORDER BY tp.points DESC, tp.wins DESC, (tp.wins - tp.losses) DESC, tp.id ASC",
            [$tournamentId]
        );
    }

    /**
     * Get status badge color.
     */
    public static function getStatusColor(string $status): string
    {
        $colors = [
            'registered'   => '#0284C7',
            'confirmed'    => '#059669',
            'withdrawn'    => '#6B7280',
            'disqualified' => '#DC2626',
            'eliminated'   => '#D97706',
            'winner'       => '#7C3AED',
            'runner_up'    => '#1e3a5f',
        ];
        return $colors[$status] ?? '#6B7280';
    }
}
