<?php

namespace App\Models;

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

class SportsMatch extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'sport_id',
        'tournament_id',
        'home_team_id',
        'away_team_id',
        'match_date',
        'match_time',
        'venue',
        'home_team_score',
        'away_team_score',
        'winner_team_id',
        'match_status',
        'remarks',
    ];

    protected $casts = [
        'match_date' => 'date',
        'match_time' => 'datetime',
    ];

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

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

    public function tournament()
    {
        return $this->belongsTo(SportsTournament::class, 'tournament_id');
    }

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

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

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

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

    public function scopeForTournament($query, $tournamentId)
    {
        return $query->where('tournament_id', $tournamentId);
    }

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

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

    public function scopeForTeam($query, $teamId)
    {
        return $query->where('home_team_id', $teamId)
                     ->orWhere('away_team_id', $teamId);
    }
}
