<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'asset_tag', 'name', 'product_id', 'category', 'location', 'serial_number',
        'purchase_date', 'purchase_cost', 'status', 'notes', 'created_by', 'updated_by',
    ];

    public function scopeForList(?string $search = null, ?string $status = null): self
    {
        $this->select('inventory_assets.*, products.name AS product_name, products.sku')
            ->join('products', 'products.id = inventory_assets.product_id', 'left');

        if ($search) {
            $this->groupStart()
                ->like('inventory_assets.asset_tag', $search)
                ->orLike('inventory_assets.name', $search)
                ->orLike('inventory_assets.serial_number', $search)
                ->orLike('inventory_assets.category', $search)
                ->orLike('inventory_assets.location', $search)
                ->orLike('products.name', $search)
                ->orLike('products.sku', $search)
                ->groupEnd();
        }

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

        return $this;
    }

    public function isTagTaken(string $tag, ?int $excludeId = null): bool
    {
        $builder = $this->where('asset_tag', strtoupper(trim($tag)));
        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

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

    public function nextTag(): string
    {
        $prefix = 'AST-';
        $rows   = $this->like('asset_tag', $prefix, 'after')->findAll();

        $max = 0;
        foreach ($rows as $row) {
            if (preg_match('/^AST-(\d+)$/', $row['asset_tag'], $m)) {
                $max = max($max, (int) $m[1]);
            }
        }

        return $prefix . str_pad((string) ($max + 1), 4, '0', STR_PAD_LEFT);
    }
}
