<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'product_id', 'warehouse_id', 'batch_number', 'quantity',
        'manufactured_date', 'expiry_date', 'status', 'notes', 'created_by', 'updated_by',
    ];

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

        if ($search) {
            $this->groupStart()
                ->like('product_batches.batch_number', $search)
                ->orLike('products.name', $search)
                ->orLike('products.sku', $search)
                ->groupEnd();
        }

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

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

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

        return $this;
    }

    public function isBatchTaken(int $productId, string $batchNumber, ?int $excludeId = null): bool
    {
        $builder = $this->where('product_id', $productId)
            ->where('batch_number', trim($batchNumber));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }
}
