<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'quotation_id', 'company_id', 'contact_id',
        'order_date', 'required_date', 'status', 'subtotal', 'tax_amount', 'total',
        'notes', 'tracking_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',
        'order_date' => 'required|valid_date',
        'status'     => 'permit_empty|in_list[draft,pending_approval,approved,rejected,confirmed,in_progress,fulfilled,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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