<?php

namespace Modules\Teachers\Models;

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

class Teacher extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'user_id',
        'teacher_id',
        'first_name',
        'last_name',
        'date_of_birth',
        'gender',
        'address',
        'phone',
        'qualification',
        'hire_date',
        'is_active',
    ];

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

    /**
     * Get the user account for this teacher
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class);
    }

    /**
     * Get the subjects this teacher is assigned to
     */
    public function subjects(): BelongsToMany
    {
        return $this->belongsToMany(
            \Modules\Academic\Models\Subject::class,
            'teacher_subjects',
            'teacher_id',
            'subject_id'
        )->withTimestamps();
    }

    /**
     * Get the classroom subjects this teacher teaches
     */
    public function classroomSubjects(): HasMany
    {
        return $this->hasMany(\Modules\Academic\Models\ClassroomSubject::class, 'teacher_id', 'user_id');
    }

    /**
     * Get the full name of the teacher
     */
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

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

    /**
     * Get classrooms this teacher teaches in for a specific academic year
     */
    public function getClassroomsForAcademicYear($academicYearId)
    {
        return \Modules\Academic\Models\Classroom::whereHas('subjects', function ($query) {
            $query->where('teacher_id', $this->user_id);
        })->where('academic_year_id', $academicYearId)->get();
    }

    /**
     * Check if teacher teaches a specific subject in a specific classroom
     */
    public function teachesSubjectInClassroom($subjectId, $classroomId): bool
    {
        return \Modules\Academic\Models\ClassroomSubject::where('teacher_id', $this->user_id)
            ->where('subject_id', $subjectId)
            ->where('classroom_id', $classroomId)
            ->exists();
    }
}
