<?php

namespace App\Models;

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

class SportsTeam extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'sport_id',
        'team_name',
        'team_code',
        'category',
        'age_group',
        'gender',
        'establishment_date',
        'is_active',
    ];

    protected $casts = [
        'establishment_date' => 'date',
        'is_active' => 'boolean',
    ];

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

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

    public function players()
    {
        return $this->belongsToMany(SportsPlayer::class, 'team_players')
                    ->withPivot('jersey_number', 'position', 'is_captain', 'joined_date')
                    ->withTimestamps();
    }

    public function coaches()
    {
        return $this->belongsToMany(SportsCoach::class, 'sports_team_coaches')
                    ->withPivot('role', 'from_date', 'to_date')
                    ->withTimestamps();
    }

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

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

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

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

    public function scopeByCategory($query, $category)
    {
        return $query->where('category', $category);
    }

    public function scopeByGender($query, $gender)
    {
        return $query->where('gender', $gender);
    }

    // Accessors
    public function getPlayerCountAttribute()
    {
        return $this->players()->count();
    }
}
