<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'bank_account_id', 'statement_date', 'statement_ending_balance',
        'book_balance', 'status', 'notes', 'completed_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'                   => 'required|max_length[40]',
        'bank_account_id'          => 'required|is_natural_no_zero',
        'statement_date'           => 'required|valid_date',
        'statement_ending_balance' => 'required|decimal',
        'book_balance'             => 'permit_empty|decimal',
        'status'                   => 'permit_empty|in_list[draft,completed,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $bankAccountId = null): self
    {
        $this->select('bank_reconciliations.*, bank_accounts.name as bank_account_name, bank_accounts.code as bank_account_code')
            ->join('bank_accounts', 'bank_accounts.id = bank_reconciliations.bank_account_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('bank_reconciliations.number', $search)
                ->orLike('bank_accounts.name', $search)
                ->orLike('bank_accounts.code', $search)
                ->orLike('bank_reconciliations.notes', $search)
                ->groupEnd();
        }

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

        if ($bankAccountId) {
            $this->where('bank_reconciliations.bank_account_id', $bankAccountId);
        }

        return $this;
    }

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