<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class SportsTournament extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'sport_id',
        'tournament_name',
        'tournament_type',
        'start_date',
        'end_date',
        'venue',
        'organizer',
        'description',
        'registration_fee',
        'winner_team_id',
        'runner_up_team_id',
        'status',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'registration_fee' => 'decimal:2',
    ];

    // Relationships
    public function school()
    {
        return $this->belongsTo(School::class);
    }

    public function sport()
    {
        return $this->belongsTo(Sport::class);
    }

    public function matches()
    {
        return $this->hasMany(SportsMatch::class, 'tournament_id');
    }

    public function winnerTeam()
    {
        return $this->belongsTo(SportsTeam::class, 'winner_team_id');
    }

    public function runnerUpTeam()
    {
        return $this->belongsTo(SportsTeam::class, 'runner_up_team_id');
    }

    public function participatingTeams()
    {
        return $this->belongsToMany(SportsTeam::class, 'tournament_teams')
                    ->withPivot('registration_date', 'status')
                    ->withTimestamps();
    }

    // Scopes
    public function scopeForSport($query, $sportId)
    {
        return $query->where('sport_id', $sportId);
    }

    public function scopeUpcoming($query)
    {
        return $query->where('start_date', '>', now());
    }

    public function scopeOngoing($query)
    {
        return $query->where('start_date', '<=', now())
                     ->where('end_date', '>=', now());
    }

    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }
}
