<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'invoice_date', 'due_date', 'status',
        'subtotal', 'tax_amount', 'total', 'amount_paid', 'notes',
        'posted_at', 'paid_at', 'created_by', 'updated_by',
    ];

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

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

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

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

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

        return $this;
    }

    public function scopeOutstanding(?string $search = null, ?int $companyId = null): self
    {
        $this->scopeForList($search, null, $companyId)
            ->whereNotIn('customer_invoices.status', ['draft', 'cancelled', 'paid'])
            ->where('customer_invoices.total > customer_invoices.amount_paid', null, false);

        return $this;
    }

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