<?php

namespace App\Models;

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

/**
 * نسخه به‌روزشده Phase 13 — نسخه Phase 5 را جایگزین کنید.
 * تغییر: افزوده شدن reviews() (hasManyThrough)، averageRating()، reviewsCount().
 */
class Coach extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'photo_path',
        'bio',
        'work_history',
        'experience_years',
        'status',
        'status_reason',
        'approved_at',
        'approved_by',
        'program_price',
    ];

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

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    public function goals()
    {
        return $this->belongsToMany(Goal::class, 'coach_goal');
    }

    public function documents()
    {
        return $this->hasMany(CoachDocument::class);
    }

    public function certificates()
    {
        return $this->documents()->where('type', 'certificate');
    }

    public function bankAccount()
    {
        return $this->hasOne(BankAccount::class);
    }

    public function coachRequests()
    {
        return $this->hasMany(CoachRequest::class);
    }

    public function pendingRequests()
    {
        return $this->coachRequests()->where('status', CoachRequestStatus::Pending);
    }

    public function activeAthletes()
    {
        return $this->belongsToMany(Athlete::class, 'coach_requests')
            ->wherePivot('status', CoachRequestStatus::Accepted->value);
    }

    public function reviews()
    {
        return $this->hasManyThrough(Review::class, CoachRequest::class);
    }

    public function approvedReviews()
    {
        return $this->reviews()->approved()->latest();
    }

    public function averageRating(): ?float
    {
        $avg = $this->approvedReviews()->avg('rating');

        return $avg ? round($avg, 1) : null;
    }

    public function reviewsCount(): int
    {
        return $this->approvedReviews()->count();
    }

    public function scopeApproved($query)
    {
        return $query->where('status', CoachStatus::Approved);
    }

    public function isApproved(): bool
    {
        return $this->status === CoachStatus::Approved;
    }

    public function approve(User $admin): void
    {
        $this->update([
            'status' => CoachStatus::Approved,
            'status_reason' => null,
            'approved_at' => now(),
            'approved_by' => $admin->id,
        ]);
    }

    public function reject(User $admin, string $reason): void
    {
        $this->update([
            'status' => CoachStatus::Rejected,
            'status_reason' => $reason,
            'approved_at' => null,
            'approved_by' => $admin->id,
        ]);
    }

    public function disable(User $admin, ?string $reason = null): void
    {
        $this->update([
            'status' => CoachStatus::Disabled,
            'status_reason' => $reason,
            'approved_by' => $admin->id,
        ]);
    }
}
