<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class AnnoTeocratico extends Model
{
    protected $table = 'anni_teocratici';

    protected $fillable = ['label', 'start_date', 'end_date'];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
        ];
    }

    /**
     * Get or create the theocratic year for a given date.
     */
    public static function perData(Carbon $date = null): static
    {
        $date = $date ?? now();

        if ($date->month >= 9) {
            $startYear = $date->year;
            $endYear = $date->year + 1;
        } else {
            $startYear = $date->year - 1;
            $endYear = $date->year;
        }

        $label = "{$startYear}-{$endYear}";

        return static::firstOrCreate(
            ['label' => $label],
            [
                'start_date' => Carbon::create($startYear, 9, 1),
                'end_date' => Carbon::create($endYear, 8, 31),
            ]
        );
    }

    /**
     * Get the current theocratic year.
     */
    public static function corrente(): static
    {
        return static::perData(now());
    }

    /**
     * Number of months elapsed since start of this theocratic year.
     */
    public function getMesiTrascorsiAttribute(): int
    {
        $start = $this->start_date;
        $end = now()->lt($this->end_date) ? now() : $this->end_date;
        return max(1, $start->diffInMonths($end));
    }

    public function assegnazioni()
    {
        return $this->hasMany(Assegnazione::class, 'anno_teocratico_id');
    }
}
