<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'from_type', 'from_id', 'to_type', 'to_id', 'transfer_date',
        'amount', 'reference', 'notes', 'status', 'journal_entry_id', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'        => 'required|max_length[40]',
        'from_type'     => 'required|in_list[bank,cash]',
        'from_id'       => 'required|is_natural_no_zero',
        'to_type'       => 'required|in_list[bank,cash]',
        'to_id'         => 'required|is_natural_no_zero',
        'transfer_date' => 'required|valid_date',
        'amount'        => 'required|decimal',
        'status'        => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('bank_transfers.*');

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

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

        return $this;
    }

    public function nextNumber(): string
    {
        $prefix = 'TRF-' . 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);
    }
}
