<?php

namespace Modules\Accounts\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Modules\Accounts\Enums\FiscalYearStatusEnum;
use Modules\Accounts\Models\Traits\FiscalYearRelationshipTrait;
use Modules\Core\Traits\HasStatus;

class FiscalYear extends Model
{
    use FiscalYearRelationshipTrait;

    protected $fillable = [
        'code',
        'name',
        'start_date',
        'end_date',
        'is_current',
        'status',
        'lock_date',
        'locked_at',
        'closed_at',
        'opened_by',
        'closed_by',
        'closed_to_fiscal_year_id',
        'opening_entries_generated_at',
        'closed_by',
        'note',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'lock_date' => 'date',

        'is_current' => 'boolean',
        'opening_entries_generated' => 'boolean',

        'locked_at' => 'datetime',
        'closed_at' => 'datetime',
        'opening_entries_generated_at' => 'datetime',
    ];

    public function getDurationInDaysAttribute(): int
    {
        return $this->start_date->diffInDays($this->end_date) + 1;
    }

    public function getFormattedDateRangeAttribute(): string
    {
        return sprintf(
            '%s to %s',
            $this->start_date->format('d M Y'),
            $this->end_date->format('d M Y')
        );
    }

    public function getIsLockedAttribute(): bool
    {
        return $this->status === FiscalYearStatusEnum::LOCKED->value;
    }

    public function getIsClosedAttribute(): bool
    {
        return $this->status === FiscalYearStatusEnum::CLOSED->value;
    }

    public function getIsOpenAttribute(): bool
    {
        return $this->status === FiscalYearStatusEnum::OPEN->value;
    }

    public function scopeCurrent(Builder $query): Builder
    {
        return $query->where('is_current', true);
    }

    public function scopeOpen(Builder $query): Builder
    {
        return $query->where(
            'status',
            FiscalYearStatusEnum::OPEN->value
        );
    }

    public function scopeLocked(Builder $query): Builder
    {
        return $query->where(
            'status',
            FiscalYearStatusEnum::LOCKED->value
        );
    }

    public function scopeClosed(Builder $query): Builder
    {
        return $query->where(
            'status',
            FiscalYearStatusEnum::CLOSED->value
        );
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query
            ->current()
            ->open();
    }

    public function scopeByDate(Builder $query, string|Carbon $date): Builder
    {
        return $query
            ->whereDate('start_date', '<=', $date)
            ->whereDate('end_date', '>=', $date);
    }

    public function scopeLatestFirst(Builder $query): Builder
    {
        return $query->orderByDesc('start_date');
    }
}
