<?php

namespace Modules\Academic\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 Classroom extends Model
{
    use HasFactory;

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

    protected $fillable = [
        'academic_year_id',
        'name',
        'description',
        'capacity',
    ];

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

    /**
     * Get the academic year this classroom belongs to
     */
    public function academicYear(): BelongsTo
    {
        return $this->belongsTo(AcademicYear::class);
    }

    /**
     * Get the enrollments for this classroom
     */
    public function enrollments(): HasMany
    {
        return $this->hasMany(\Modules\Enrollment\Models\Enrollment::class);
    }

    /**
     * Get the students enrolled in this classroom
     */
    public function students(): BelongsToMany
    {
        return $this->belongsToMany(
            \Modules\Students\Models\Student::class,
            'enrollments',
            'classroom_id',
            'student_id'
        )->withPivot(['academic_year_id', 'enrolled_at'])
         ->withTimestamps();
    }

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

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

    /**
     * Get the current enrollment count
     */
    public function getCurrentEnrollmentCount(): int
    {
        return $this->enrollments()
            ->where('academic_year_id', $this->academic_year_id)
            ->count();
    }

    /**
     * Check if classroom is at capacity
     */
    public function isAtCapacity(): bool
    {
        return $this->capacity && $this->getCurrentEnrollmentCount() >= $this->capacity;
    }
}
