<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'adjustment_date', 'product_id', 'warehouse_id',
        'quantity_before', 'quantity_after', 'delta', 'mode', 'reason', 'notes', 'created_by',
    ];

    public function scopeForList(?string $search = null, ?int $warehouseId = null, ?int $productId = null): self
    {
        $this->select('stock_adjustments.*, products.name AS product_name, products.sku, warehouses.name AS warehouse_name, warehouses.code AS warehouse_code')
            ->join('products', 'products.id = stock_adjustments.product_id')
            ->join('warehouses', 'warehouses.id = stock_adjustments.warehouse_id');

        if ($search) {
            $this->groupStart()
                ->like('stock_adjustments.number', $search)
                ->orLike('products.name', $search)
                ->orLike('products.sku', $search)
                ->orLike('warehouses.name', $search)
                ->orLike('warehouses.code', $search)
                ->orLike('stock_adjustments.reason', $search)
                ->groupEnd();
        }

        if ($warehouseId) {
            $this->where('stock_adjustments.warehouse_id', $warehouseId);
        }

        if ($productId) {
            $this->where('stock_adjustments.product_id', $productId);
        }

        return $this;
    }

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