<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'company_id', 'contact_id', 'opportunity_id', 'template_id', 'price_list_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]',
        'company_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 $companyId = null): self
    {
        $this->select('quotations.*, companies.name as company_name')
            ->join('companies', 'companies.id = quotations.company_id', 'left');

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

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

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

        return $this;
    }

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