<?php

namespace App\Models;

use CodeIgniter\Model;

class JournalEntryModel extends Model
{
    protected $table         = 'journal_entries';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'number', 'entry_date', 'fiscal_year_id', 'reference', 'description',
        'status', 'total_debit', 'total_credit', 'posted_by', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'     => 'required|max_length[40]',
        'entry_date' => 'required|valid_date',
        'status'     => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $dateFrom = null, ?string $dateTo = null): self
    {
        $this->select('journal_entries.*, fiscal_years.name as fiscal_year_name, fiscal_years.code as fiscal_year_code')
            ->join('fiscal_years', 'fiscal_years.id = journal_entries.fiscal_year_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('journal_entries.number', $search)
                ->orLike('journal_entries.reference', $search)
                ->orLike('journal_entries.description', $search)
                ->groupEnd();
        }

        if ($status) {
            $this->where('journal_entries.status', $status);
        }

        if ($dateFrom) {
            $this->where('journal_entries.entry_date >=', $dateFrom);
        }

        if ($dateTo) {
            $this->where('journal_entries.entry_date <=', $dateTo);
        }

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'JE-' . date('Ymd') . '-';
        $row = $this->like('number', $prefix, 'after')
            ->orderBy('id', 'DESC')
            ->first();

        $seq = 1;
        if ($row && preg_match('/-(\d+)$/', $row['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }
}
