<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'supplier_quotation_id', 'supplier_id', 'order_date', 'expected_date',
        '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',
        'order_date'  => 'required|valid_date',
        'status'      => 'permit_empty|in_list[draft,pending_approval,approved,rejected,confirmed,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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