<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'supplier_id', 'bill_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]',
        'supplier_id' => 'required|is_natural_no_zero',
        'bill_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 $supplierId = null): self
    {
        $this->select('supplier_bills.*, suppliers.name as supplier_name')
            ->join('suppliers', 'suppliers.id = supplier_bills.supplier_id', 'left');

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

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

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

        return $this;
    }

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

        return $this;
    }

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