<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'purchase_order_id', 'supplier_id', 'receipt_date', 'status',
        'notes', 'posted_by', 'posted_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'            => 'required|max_length[40]',
        'purchase_order_id' => 'required|is_natural_no_zero',
        'supplier_id'       => 'required|is_natural_no_zero',
        'receipt_date'      => 'required|valid_date',
        'status'            => 'permit_empty|in_list[draft,posted,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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