<?php

namespace App\Models;

use CodeIgniter\Model;

class WorkOrderEquipmentModel extends Model
{
    protected $table         = 'work_order_equipment';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'work_order_id', 'inventory_asset_id', 'notes', 'assigned_at', 'assigned_by', 'returned_at',
    ];

    /**
     * @return list<array>
     */
    public function getForWorkOrder(int $workOrderId, bool $activeOnly = false): array
    {
        $builder = $this->select('work_order_equipment.*, inventory_assets.asset_tag, inventory_assets.name AS asset_name, inventory_assets.serial_number, inventory_assets.category, inventory_assets.status AS asset_status')
            ->join('inventory_assets', 'inventory_assets.id = work_order_equipment.inventory_asset_id', 'left')
            ->where('work_order_equipment.work_order_id', $workOrderId);

        if ($activeOnly) {
            $builder->where('work_order_equipment.returned_at', null);
        }

        return $builder->orderBy('inventory_assets.name', 'ASC')->findAll();
    }

    public function isAssigned(int $workOrderId, int $assetId): bool
    {
        return $this->where('work_order_id', $workOrderId)
            ->where('inventory_asset_id', $assetId)
            ->where('returned_at', null)
            ->countAllResults() > 0;
    }
}
