<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'customer_invoice_id', 'credit_date', 'status',
        'subtotal', 'tax_amount', 'total', 'notes', 'posted_at',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'company_id'  => 'required|is_natural_no_zero',
        'credit_date' => 'required|valid_date',
        'status'      => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $companyId = null): self
    {
        $this->select('credit_notes.*, companies.name as company_name, customer_invoices.number as invoice_number')
            ->join('companies', 'companies.id = credit_notes.company_id', 'left')
            ->join('customer_invoices', 'customer_invoices.id = credit_notes.customer_invoice_id', 'left');

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

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

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

        return $this;
    }

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