<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Services\PeriodeService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class Periode extends Model
{
    use HasFactory;

    protected $fillable = [
        'tahun_pelajaran',
        'semester',
        'status',
    ];

    public const STATUS_AKTIF = 'aktif';
    public const STATUS_TIDAK_AKTIF = 'tidak aktif';

    public const SEMESTER_GANJIL = 'Ganjil';
    public const SEMESTER_GENAP = 'Genap';

    /**
     * Scope: only active periodes
     */
    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_AKTIF);
    }

    /**
     * Check if this periode is active
     */
    public function isActive(): bool
    {
        return $this->status === self::STATUS_AKTIF;
    }

    /**
     * Return start Carbon for this periode (1 July year1)
     */
    public function getStartAttribute(): Carbon
    {
        return $this->range()[0];
    }

    /**
     * Return end Carbon for this periode (30 June year2 end of day)
     */
    public function getEndAttribute(): Carbon
    {
        return $this->range()[1];
    }

    /**
     * Make this periode active and deactivate other periodes.
     */
    public function makeActive(): void
    {
        DB::transaction(function () {
            static::where('status', self::STATUS_AKTIF)->where('id', '!=', $this->id)->update(['status' => self::STATUS_TIDAK_AKTIF]);
            $this->status = self::STATUS_AKTIF;
            $this->save();
        });
    }

    /**
     * Return the start and end Carbon objects for this periode's tahun_pelajaran.
     * start = 1 July of first year, end = 30 June of second year.
     * @return array [startCarbon, endCarbon]
     */
    public function range(): array
    {
        return PeriodeService::rangeFromTahunPelajaran($this->tahun_pelajaran);
    }
}
