<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'number', 'count_date', 'warehouse_id', 'status', 'notes',
        'completed_at', 'completed_by', 'created_by', 'updated_by',
    ];

    public function scopeForList(?string $search = null, ?string $status = null, ?int $warehouseId = null): self
    {
        $this->select('stock_counts.*, warehouses.name AS warehouse_name, warehouses.code AS warehouse_code')
            ->join('warehouses', 'warehouses.id = stock_counts.warehouse_id', 'left');

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

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

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

        return $this;
    }

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