<?php

namespace Modules\Enrollment\Models;

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

class Enrollment extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'student_id',
        'classroom_id',
        'academic_year_id',
        'enrolled_at',
        'is_active',
    ];

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

    /**
     * Get the student for this enrollment
     */
    public function student(): BelongsTo
    {
        return $this->belongsTo(\Modules\Students\Models\Student::class);
    }

    /**
     * Get the classroom for this enrollment
     */
    public function classroom(): BelongsTo
    {
        return $this->belongsTo(\Modules\Academic\Models\Classroom::class);
    }

    /**
     * Get the academic year for this enrollment
     */
    public function academicYear(): BelongsTo
    {
        return $this->belongsTo(\Modules\Academic\Models\AcademicYear::class);
    }

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

    /**
     * Scope to get enrollments for a specific academic year
     */
    public function scopeForAcademicYear($query, $academicYearId)
    {
        return $query->where('academic_year_id', $academicYearId);
    }

    /**
     * Scope to get enrollments for a specific classroom
     */
    public function scopeForClassroom($query, $classroomId)
    {
        return $query->where('classroom_id', $classroomId);
    }

    /**
     * Check if student is enrolled in a specific classroom for an academic year
     */
    public static function isStudentEnrolled($studentId, $classroomId, $academicYearId): bool
    {
        return static::where('student_id', $studentId)
            ->where('classroom_id', $classroomId)
            ->where('academic_year_id', $academicYearId)
            ->where('is_active', true)
            ->exists();
    }
}
