<?php

namespace App\Models;

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

class TahunAjaran extends Model
{
    use HasFactory;

    protected $table = 'tahun_ajaran';

    protected $fillable = [
        'nama',
        'semester',
        'tanggal_mulai',
        'tanggal_selesai',
        'is_aktif',
    ];

    protected function casts(): array
    {
        return [
            'tanggal_mulai'   => 'date',
            'tanggal_selesai' => 'date',
            'is_aktif'        => 'boolean',
        ];
    }

    public function kelas()
    {
        return $this->hasMany(Kelas::class);
    }

    public function ujian()
    {
        return $this->hasMany(Ujian::class);
    }

    public function guruMengajar()
    {
        return $this->hasMany(GuruMengajar::class);
    }

    public function scopeAktif($query)
    {
        return $query->where('is_aktif', true);
    }

    // Nonaktifkan semua, lalu aktifkan yang dipilih
    public static function aktifkan(int $id): void
    {
        self::query()->update(['is_aktif' => false]);
        self::query()->where('id', $id)->update(['is_aktif' => true]);
    }
}
