<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'supplier_id', 'purchase_order_id', 'goods_receipt_id', 'return_date', 'status',
        'subtotal', 'tax_amount', 'total', 'reason', 'notes',
        'approved_by', 'approved_at', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'      => 'required|max_length[40]',
        'supplier_id' => 'required|is_natural_no_zero',
        'return_date' => 'required|valid_date',
        'status'      => 'permit_empty|in_list[draft,submitted,approved,completed,cancelled]',
    ];

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

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

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

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

        return $this;
    }

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