<?php

namespace App\Models;

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

class Teacher extends Model
{
    use HasFactory;

    protected $fillable = [
        'nip',
        'name',
        'gender',
        'is_homeroom',
        'phone',
    ];

    protected $casts = [
        'is_homeroom' => 'boolean',
    ];

    public function schedules()
    {
        return $this->hasMany(Schedule::class);
    }

    public function subjects()
    {
        return $this->belongsToMany(Subject::class);
    }

    public function homeroomClass()
    {
        return $this->hasOne(SchoolClass::class, 'homeroom_teacher_id');
    }

    public function attendances()
    {
        return $this->hasMany(TeacherAttendance::class);
    }

    public function todayAttendance()
    {
        return $this->hasOne(TeacherAttendance::class)->whereDate('date', today());
    }

    /**
     * Sinkronkan mapel: wali kelas otomatis ampu semua mapel non-khusus,
     * ditambah pilihan manual dari form.
     */
    public function syncSubjects(array $manualSubjectIds = []): void
    {
        if ($this->is_homeroom) {
            $defaultIds = Subject::where('is_special', false)->pluck('id')->all();
            $subjectIds = array_unique(array_merge($defaultIds, $manualSubjectIds));
        } else {
            $subjectIds = $manualSubjectIds;
        }

        $this->subjects()->sync($subjectIds);
    }
}
