<?php

namespace App\Models;

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

class Course extends Model
{
    use HasFactory;

    protected $fillable = ['lead_teacher', 'description', 'subject_id', 'level_id'];

    public function subject()
    {
        return $this->belongsTo(Subject::class);
    }

    public function level()
    {
        return $this->belongsTo(Level::class);
    }

    public function modules()
    {
        return $this->hasMany(Module::class)->orderBy('order');
    }
	
	public function lessonSections()
	{
		return $this->hasManyThrough(LessonSection::class, Module::class);
	}
	
	protected static function booted()
	{
		static::creating(function ($course) {
			$subject = $course->subject?->name ?? 'unknown-subject';
			$level = $course->level?->name ?? 'unknown-level';
			$course->slug = \Illuminate\Support\Str::slug($subject . '-' . $level);
		});
	}
	
	public function getRouteKeyName(): string
	{
		return 'slug';
	}	
}
