<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'supplier_id', 'supplier_bill_id', 'payment_date',
        'amount', 'method', 'status', 'notes', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'       => 'required|max_length[40]',
        'supplier_id'  => 'required|is_natural_no_zero',
        'payment_date' => 'required|valid_date',
        'amount'       => 'required|decimal',
        'status'       => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $supplierId = null): self
    {
        $this->select('ap_payments.*, suppliers.name as supplier_name, supplier_bills.number as bill_number')
            ->join('suppliers', 'suppliers.id = ap_payments.supplier_id', 'left')
            ->join('supplier_bills', 'supplier_bills.id = ap_payments.supplier_bill_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('ap_payments.number', $search)
                ->orLike('suppliers.name', $search)
                ->orLike('ap_payments.notes', $search)
                ->orLike('supplier_bills.number', $search)
                ->groupEnd();
        }

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

        if ($supplierId) {
            $this->where('ap_payments.supplier_id', $supplierId);
        }

        return $this;
    }

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