<?php

namespace Modules\Academic\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

class Subject extends Model
{
    use HasFactory;

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory()
    {
        return \Database\Factories\SubjectFactory::new();
    }

    protected $fillable = [
        'name',
        'code',
        'description',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

    /**
     * Get the classrooms this subject is assigned to
     */
    public function classrooms(): BelongsToMany
    {
        return $this->belongsToMany(
            Classroom::class,
            'classroom_subjects',
            'subject_id',
            'classroom_id'
        )->withPivot(['teacher_id'])
         ->withTimestamps();
    }

    /**
     * Get the teachers assigned to this subject
     */
    public function teachers(): BelongsToMany
    {
        return $this->belongsToMany(
            \Modules\Teachers\Models\Teacher::class,
            'teacher_subjects',
            'subject_id',
            'teacher_id'
        )->withTimestamps();
    }

    /**
     * Get the classroom subject assignments for this subject
     */
    public function classroomSubjects(): HasMany
    {
        return $this->hasMany(ClassroomSubject::class);
    }

    /**
     * Get the results for this subject
     */
    public function results(): HasMany
    {
        return $this->hasMany(\Modules\Results\Models\Result::class);
    }

    /**
     * Scope to get only active subjects
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the subject code with name
     */
    public function getFullNameAttribute(): string
    {
        return $this->code ? "{$this->code} - {$this->name}" : $this->name;
    }
}
