<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Insumo extends Model
{
    use HasFactory;

    protected $table = 'insumos';    
    
    protected static function boot()
    {
        parent::boot();
        static::updated(function ($item) {
            /*
            Generar Orden de Compra - Pasar a Evento
            */
            
            if ($item->quantity < $item->stock_min) {
                $orden = new OrdenCompra;
                $orden->observations = 'Solicitud Autogenerada por alcanzar el stock mínimo';
                
                $insumo_id = isset($item['id']) ? $item['id'] : '';
                $proveedor_id = isset($item['proveedor_id']) ? $item['proveedor_id'] : '';
                $orden->insumo_id = $insumo_id;
                $orden->proveedor_id = $proveedor_id;
                $orden->quantity = $item->stock_min - $item->quantity;
                $orden->save();                
            }
        });
    }

    public function almacenes_insumos() 
    {
        return $this->hasMany(AlmacenInsumo::class, 'insumo_id')->with('insumo');
    }

    public function solicitudes() 
    {
        return $this->hasMany(SolicitudInsumoDetalle::class, 'insumo_id');
    }
}
