<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'voucher_date', 'amount', 'account_id', 'pay_from_type',
        'pay_from_id', 'cost_center_id', 'payee', 'reference', 'notes', 'status',
        'journal_entry_id', 'posted_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'        => 'required|max_length[40]',
        'voucher_date'  => 'required|valid_date',
        'amount'        => 'required|decimal',
        'account_id'    => 'required|is_natural_no_zero',
        'pay_from_type' => 'required|in_list[bank,cash]',
        'pay_from_id'   => 'required|is_natural_no_zero',
        'status'        => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('payment_vouchers.*, chart_of_accounts.code as account_code, chart_of_accounts.name as account_name, cost_centers.code as cost_center_code, cost_centers.name as cost_center_name')
            ->join('chart_of_accounts', 'chart_of_accounts.id = payment_vouchers.account_id', 'left')
            ->join('cost_centers', 'cost_centers.id = payment_vouchers.cost_center_id', 'left');

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

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

        return $this;
    }

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