<?php

namespace App\Models;

use App\Enums\CoachRequestStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * نسخه به‌روزشده Phase 13 — نسخه Phase 11 را جایگزین کنید.
 * تغییر: افزوده شدن رابطه‌ی review().
 */
class CoachRequest extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'athlete_id',
        'coach_id',
        'status',
        'athlete_message',
        'coach_response_note',
        'price',
        'responded_at',
    ];

    protected function casts(): array
    {
        return [
            'status' => CoachRequestStatus::class,
            'responded_at' => 'datetime',
        ];
    }

    public function athlete()
    {
        return $this->belongsTo(Athlete::class);
    }

    public function coach()
    {
        return $this->belongsTo(Coach::class);
    }

    public function payment()
    {
        return $this->hasOne(Payment::class);
    }

    public function review()
    {
        return $this->hasOne(Review::class);
    }

    public function messages()
    {
        return $this->hasMany(Message::class)->orderBy('created_at');
    }

    public function unreadCountFor(User $user): int
    {
        return $this->messages()
            ->whereNull('read_at')
            ->where('sender_id', '!=', $user->id)
            ->count();
    }

    public function isActive(): bool
    {
        return $this->status === CoachRequestStatus::Accepted;
    }

    public function scopePending($query)
    {
        return $query->where('status', CoachRequestStatus::Pending);
    }

    public function scopeAccepted($query)
    {
        return $query->where('status', CoachRequestStatus::Accepted);
    }
}
