<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Review extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'doctor_id','patient_id','appointment_id',
        'rating','comment','is_approved','is_anonymous',
    ];
    protected $casts = [
        'is_approved'  => 'boolean',
        'is_anonymous' => 'boolean',
        'rating'       => 'integer',
    ];

    public function doctor()      { return $this->belongsTo(Doctor::class); }
    public function patient()     { return $this->belongsTo(Patient::class); }
    public function appointment() { return $this->belongsTo(Appointment::class); }

    public function scopeApproved($q) { return $q->where('is_approved', true); }

    // تحديث تقييم الطبيب بعد كل مراجعة
    protected static function boot()
    {
        parent::boot();
        static::saved(function ($review) {
            $doctor = $review->doctor;
            $avg    = Review::where('doctor_id', $doctor->id)->approved()->avg('rating');
            $count  = Review::where('doctor_id', $doctor->id)->approved()->count();
            $doctor->update(['rating' => round($avg, 2), 'total_reviews' => $count]);
        });
    }
}
