<?php

namespace App\Models\Courses;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;


class CourseReview extends Model
{
    protected $fillable = [
        'enrollment_id', 'rating', 'review', 'is_approved'
    ];

    protected $casts = [
        'is_approved' => 'boolean',
    ];

    public function enrollment()
    {
        return $this->belongsTo(CourseEnrollment::class);
    }

    public function user()
    {
        return $this->hasOneThrough(
            User::class,
            CourseEnrollment::class,
            'id',
            'id',
            'enrollment_id',
            'user_id'
        );
    }

    public function course()
    {
        return $this->hasOneThrough(
            Course::class,
            CourseEnrollment::class,
            'id',
            'id',
            'enrollment_id',
            'course_id'
        );
    }

    protected static function boot()
    {
        parent::boot();
        
        // Update course statistics when a review is added or updated
        static::saved(function ($review) {
            if ($review->course) {
                $review->course->updateCourseStats();
            }
        });
        
        static::deleted(function ($review) {
            if ($review->course) {
                $review->course->updateCourseStats();
            }
        });
    }
}
