<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'product_id', 'warehouse_id', 'serial_number', '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_serials.*, products.name AS product_name, products.sku, warehouses.name AS warehouse_name, warehouses.code AS warehouse_code')
            ->join('products', 'products.id = product_serials.product_id', 'left')
            ->join('warehouses', 'warehouses.id = product_serials.warehouse_id', 'left');

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

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

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

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

        return $this;
    }

    public function isSerialTaken(string $serial, ?int $excludeId = null): bool
    {
        $builder = $this->where('serial_number', trim($serial));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

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