<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class TahunAjaran extends Model
{
    protected $table = 'tahun_ajaran';

    protected $fillable = ['tahun', 'status', 'bulan_mulai_spp', 'bulan_selesai_spp', 'tanggal_jatuh_tempo_spp'];

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

    /**
     * Daftar bulan SPP berdasarkan periode yang diatur.
     * Contoh: mulai=7, selesai=6 → [7,8,9,10,11,12,1,2,3,4,5,6]
     * Contoh: mulai=1, selesai=12 → [1,2,3,4,5,6,7,8,9,10,11,12]
     */
    public function getBulanSppList(): array
    {
        $mulai = $this->bulan_mulai_spp ?: 7;

        $bulanList = [];
        $current = $mulai;
        for ($i = 0; $i < 12; $i++) {
            $bulanList[] = $current;
            $current = ($current % 12) + 1;
        }
        return $bulanList;
    }

    /**
     * Nama bulan Indonesia
     */
    public static function namaBulan(int $bulan): string
    {
        $names = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember',
        ];
        return $names[$bulan] ?? '-';
    }

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

    public function siswaKelas(): HasMany
    {
        return $this->hasMany(SiswaKelas::class);
    }

    public function tarifPembayaran(): HasMany
    {
        return $this->hasMany(TarifPembayaran::class);
    }

    public function tagihan(): HasMany
    {
        return $this->hasMany(Tagihan::class);
    }

    /**
     * Scope: hanya tahun ajaran aktif
     */
    public function scopeAktif($query)
    {
        return $query->where('tahun_ajaran.status', 'aktif');
    }
}
