<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'purchase_request_id', 'rfq_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]',
        'rfq_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): self
    {
        $this->select('rfqs.*, purchase_requests.number as purchase_request_number')
            ->join('purchase_requests', 'purchase_requests.id = rfqs.purchase_request_id', 'left');

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

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

        return $this;
    }

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