<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'supplier_id', 'vendor_bill_id', 'payment_date',
        'amount', 'method', 'status', 'notes', 'processed_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,pending,processed,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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