<?php

namespace App\Models;

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

class Course extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'code',
        'description',
        'instructor_id',
        'credits',
        'fees',
        'is_active',
        'academic_session',
        'session_period',
        'from_month',
        'to_month',
        'number_of_sessions',
        'number_of_weeks',
        'schedule_info',
        'schedule_days',
        'start_time',
        'end_time',
        'session_duration_minutes',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'fees' => 'decimal:2',
        'is_active' => 'boolean',
        'schedule_days' => 'array',
    ];

    /**
     * Get the instructor that teaches this course.
     */
    public function instructor()
    {
        return $this->belongsTo(User::class, 'instructor_id');
    }

    /**
     * Get the enrollments for this course.
     */
    public function enrollments()
    {
        return $this->hasMany(Enrollment::class, 'course_id');
    }

    /**
     * Get the students enrolled in this course.
     */
    public function students()
    {
        return $this->belongsToMany(User::class, 'enrollments', 'course_id', 'student_id')
                    ->withPivot('enrollment_date', 'status')
                    ->withTimestamps();
    }

    /**
     * Get the chapters for this course.
     */
    public function chapters()
    {
        return $this->hasMany(CourseChapter::class, 'course_id')->orderBy('order');
    }

    /**
     * Get the published chapters for this course.
     */
    public function publishedChapters()
    {
        return $this->hasMany(CourseChapter::class, 'course_id')
                    ->where('is_published', true)
                    ->orderBy('order');
    }

    /**
     * Get the course offerings for this course.
     */
    public function courseOfferings()
    {
        return $this->hasMany(CourseOffering::class, 'course_id');
    }

    /**
     * Get the assignments for this course.
     */
    public function assignments()
    {
        return $this->hasMany(Assignment::class, 'course_id');
    }
}

