<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Tournament extends Model
{
    protected $fillable = [
        'title', 'thumbnail', 'description', 'prize', 'prize_1st', 'prize_2nd', 'prize_3rd',
        'rules', 'max_players', 'status', 'format', 'group_count', 'current_phase',
        'groups_per_advance', 'bo_config', 'ban_config', 'tiebreak_mode',
        'registration_opens_at', 'registration_closes_at',
        'starts_at', 'created_by',
    ];

    /**
     * Accessor: prize returns prize_1st for backward compatibility.
     */
    public function getPrizeAttribute(): ?string
    {
        return $this->prize_1st;
    }

    /**
     * Returns true if any prize tier is set.
     */
    public function hasPrize(): bool
    {
        return $this->prize_1st || $this->prize_2nd || $this->prize_3rd;
    }

    protected $casts = [
        'registration_opens_at'  => 'datetime',
        'registration_closes_at' => 'datetime',
        'starts_at'              => 'datetime',
        'bo_config'              => 'array',
        'ban_config'             => 'array',
    ];

    const TIEBREAK_AGGREGATE   = 'aggregate';
    const TIEBREAK_GOLDEN_GOAL = 'golden_goal';

    public function useAggregateTiebreak(): bool
    {
        return ($this->tiebreak_mode ?? self::TIEBREAK_AGGREGATE) === self::TIEBREAK_AGGREGATE;
    }

    public function getTiebreakLabel(): string
    {
        return $this->useAggregateTiebreak()
            ? '⚽ Agregat Gol'
            : '⚡ Langsung Golden Goal';
    }

    /**
     * Get BO (Best of) count for a given phase.
     * phase: 'group' | 'knockout' | 'final'
     */
    public function getBoForPhase(string $phase): int
    {
        $cfg = $this->bo_config ?? [];
        return max(1, (int) ($cfg[$phase] ?? 1));
    }

    /**
     * Get number of bans per player for a given phase.
     */
    public function getBanCountForPhase(string $phase): int
    {
        $cfg = $this->ban_config ?? [];
        return max(0, (int) ($cfg[$phase] ?? 0));
    }

    /**
     * Determine if a given TournamentMatch is the "final" (1 match left in knockout).
     * Used to apply the 'final' BO/ban config.
     */
    public function isFinalMatch(\App\Models\TournamentMatch $match): bool
    {
        if ($match->phase !== 'knockout') return false;

        $totalKnockoutMatches = $this->tournamentMatches()
            ->where('phase', 'knockout')
            ->where('round', $match->round)
            ->where('leg_number', 1)
            ->count();

        return $totalKnockoutMatches === 1;
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function participants(): HasMany
    {
        return $this->hasMany(TournamentParticipant::class);
    }

    public function tournamentMatches(): HasMany
    {
        return $this->hasMany(TournamentMatch::class);
    }

    public function isRegistrationOpen(): bool
    {
        return $this->status === 'registration'
            && now()->between($this->registration_opens_at, $this->registration_closes_at)
            && $this->participants()->count() < $this->max_players;
    }
}
