<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'rfq_id', 'supplier_id', 'quotation_date', 'valid_until', 'status',
        'subtotal', 'tax_amount', 'total', 'notes', 'rejection_reason',
        'approved_by', 'approved_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'         => 'required|max_length[40]',
        'supplier_id'    => 'required|is_natural_no_zero',
        'quotation_date' => 'required|valid_date',
        'status'         => 'permit_empty|in_list[draft,pending_approval,approved,rejected,sent,converted,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $supplierId = null): self
    {
        $this->select('supplier_quotations.*, suppliers.name as supplier_name, rfqs.number as rfq_number')
            ->join('suppliers', 'suppliers.id = supplier_quotations.supplier_id', 'left')
            ->join('rfqs', 'rfqs.id = supplier_quotations.rfq_id', 'left');

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

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

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

        return $this;
    }

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