<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;
use App\Core\App;

class PeriodClosing extends Model
{
    protected static string $table = 'period_closings';
    protected static array $fillable = [
        'fiscal_year_id', 'period', 'period_start', 'period_end',
        'closing_type', 'status', 'total_debit', 'total_credit',
        'journal_count', 'closing_entry_id', 'closed_at', 'closed_by',
        'reopened_at', 'reopened_by', 'reopen_reason', 'notes',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;

    public static function findByPeriod(int $fiscalYearId, string $period): ?static
    {
        $row = static::query()
            ->where('fiscal_year_id', '=', $fiscalYearId)
            ->where('period', '=', $period)
            ->where('is_archived', '=', 0)
            ->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function isPeriodClosed(int $fiscalYearId, string $period): bool
    {
        $pc = self::findByPeriod($fiscalYearId, $period);
        return $pc !== null && $pc->status === 'closed';
    }

    public static function getForFiscalYear(int $fiscalYearId): array
    {
        return static::query()
            ->where('fiscal_year_id', '=', $fiscalYearId)
            ->where('is_archived', '=', 0)
            ->orderBy('period', 'ASC')
            ->get();
    }
}
