<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'customer_invoice_id', 'receipt_date',
        'amount', 'method', 'status', 'notes', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'       => 'required|max_length[40]',
        'company_id'   => 'required|is_natural_no_zero',
        'receipt_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 $companyId = null): self
    {
        $this->select('customer_receipts.*, companies.name as company_name, customer_invoices.number as invoice_number')
            ->join('companies', 'companies.id = customer_receipts.company_id', 'left')
            ->join('customer_invoices', 'customer_invoices.id = customer_receipts.customer_invoice_id', 'left');

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

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

        if ($companyId) {
            $this->where('customer_receipts.company_id', $companyId);
        }

        return $this;
    }

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