<?php

namespace App\Models;

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

use Auth;

class SolicitudInsumo extends Model
{
    use HasFactory;

    protected $table = 'solicitud_insumos';
    protected $fillable = ['oti_id', 'user_id', 'observations', 'status', 'approved_user_id'];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($item) 
        {
            if (! $item->user_id && Auth::user()) {
                $item->user_id = Auth::user()->id;
            }
        });
        static::updating(function ($item) 
        {
           if (! $item->user_id && Auth::user()) {
                $item->user_id = Auth::user()->id;
            }
        });
    }

    public function oti() 
    {
        return $this->belongsTo(Oti::class, 'oti_id');
    }

    public function user() 
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function approved_user() 
    {
        return $this->belongsTo(User::class, 'approved_user_id');
    }

    public function detalle() 
    {
        return $this->hasMany(SolicitudInsumoDetalle::class, 'solicitud_insumo_id')->with('insumo');
    }

    public function getData($id = null)
    {
        if (is_null($id)) {
            return $this->with('detalle')->with('user')->with('approved_user')->with('oti')->orderBy('id', 'DESC')->get();
        }
        return $this->with('detalle')->with('user')->with('approved_user')->with('oti')->find($id);
    }
}
