<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'transfer_date', 'from_warehouse_id', 'to_warehouse_id',
        'status', 'notes', 'completed_at', 'completed_by', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'number'            => 'required|max_length[40]',
        'transfer_date'     => 'required|valid_date',
        'from_warehouse_id' => 'required|is_natural_no_zero',
        'to_warehouse_id'   => 'required|is_natural_no_zero',
        'status'            => 'permit_empty|in_list[draft,completed,cancelled]',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('stock_transfers.*, fw.name AS from_warehouse_name, tw.name AS to_warehouse_name')
            ->join('warehouses AS fw', 'fw.id = stock_transfers.from_warehouse_id', 'left')
            ->join('warehouses AS tw', 'tw.id = stock_transfers.to_warehouse_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('stock_transfers.number', $search)
                ->orLike('fw.name', $search)
                ->orLike('tw.name', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function findWithWarehouses(int $id): ?array
    {
        return $this->select('stock_transfers.*, fw.name AS from_warehouse_name, tw.name AS to_warehouse_name')
            ->join('warehouses AS fw', 'fw.id = stock_transfers.from_warehouse_id', 'left')
            ->join('warehouses AS tw', 'tw.id = stock_transfers.to_warehouse_id', 'left')
            ->where('stock_transfers.id', $id)
            ->first();
    }

    public function nextNumber(): string
    {
        $prefix = 'ST-' . date('Ym') . '-';
        $last = $this->like('number', $prefix, 'after')
            ->orderBy('number', 'DESC')
            ->first();

        $seq = 1;
        if ($last && preg_match('/(\d+)$/', $last['number'], $m)) {
            $seq = (int) $m[1] + 1;
        }

        return $prefix . str_pad((string) $seq, 4, '0', STR_PAD_LEFT);
    }
}
