<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

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

class JournalType extends Model
{
    protected static string $table = 'journal_types';
    protected static array $fillable = [
        'code', 'name_ar', 'name_en', 'short_name_ar', 'short_name_en',
        'numbering_method', 'number_prefix', 'number_length',
        'is_auto_generated', 'is_default', 'is_active',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    public static function findByCode(string $code): ?static
    {
        $row = static::query()->where('code', '=', $code)->first();
        if ($row === null) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function getActive(): array
    {
        return static::query()
            ->where('is_active', '=', 1)
            ->orderBy('code', 'ASC')
            ->get();
    }

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

    public function generateNextNumber(?int $fiscalYearId = null): string
    {
        $db = App::getInstance()->db();
        $prefix = $this->number_prefix ?? $this->code . '-';
        $length = (int) ($this->number_length ?? 6);

        if ($this->numbering_method === 'monthly') {
            $period = date('Ym');
            $likePattern = $prefix . $period . '%';
        } else {
            $year = date('Y');
            $likePattern = $prefix . $year . '%';
        }

        $last = $db->selectOne(
            "SELECT entry_number FROM journal_entries
             WHERE entry_number LIKE ?
             ORDER BY entry_number DESC LIMIT 1",
            [$likePattern]
        );

        if ($last) {
            $lastNum = (int) substr($last['entry_number'], -$length);
            $nextNum = $lastNum + 1;
        } else {
            $nextNum = 1;
        }

        if ($this->numbering_method === 'monthly') {
            return $prefix . date('Ym') . str_pad((string) $nextNum, $length, '0', STR_PAD_LEFT);
        }

        return $prefix . date('Y') . str_pad((string) $nextNum, $length, '0', STR_PAD_LEFT);
    }
}
