<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;

class FiscalYear extends Model
{
    protected static string $table = 'fiscal_years';
    protected static array $fillable = [
        'name_ar', 'name_en', 'start_date', 'end_date',
        'status', 'is_current', 'closed_at', 'closed_by', 'notes',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;

    public static function current(): ?static
    {
        $row = static::query()->where('is_current', '=', 1)->where('is_archived', '=', 0)->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function findByDate(string $date): ?static
    {
        $row = static::query()
            ->where('start_date', '<=', $date)
            ->where('end_date', '>=', $date)
            ->where('is_archived', '=', 0)
            ->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public function isOpen(): bool
    {
        return $this->status === 'open';
    }
}
