<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'cheque_number', 'direction', 'party_name', 'bank_account_id',
        'cash_account_id', 'cheque_date', 'amount', 'status', 'cleared_at',
        'journal_entry_id', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'        => 'required|max_length[40]',
        'cheque_number' => 'required|max_length[60]',
        'direction'     => 'required|in_list[issued,received]',
        'party_name'    => 'required|max_length[200]',
        'cheque_date'   => 'required|valid_date',
        'amount'        => 'required|decimal',
        'status'        => 'permit_empty|in_list[registered,issued,cleared,bounced,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?string $direction = null): self
    {
        $this->select('cheques.*, bank_accounts.name as bank_account_name, bank_accounts.code as bank_account_code, cash_accounts.name as cash_account_name, cash_accounts.code as cash_account_code')
            ->join('bank_accounts', 'bank_accounts.id = cheques.bank_account_id', 'left')
            ->join('cash_accounts', 'cash_accounts.id = cheques.cash_account_id', 'left');

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

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

        if ($direction) {
            $this->where('cheques.direction', $direction);
        }

        return $this;
    }

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