<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'sales_order_id', 'invoice_date', 'due_date', 'status',
        'subtotal', 'tax_amount', 'total', 'amount_paid', 'payment_notes', 'notes',
        'issued_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,issued,partially_paid,paid,overdue,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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

        return $this;
    }

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