<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DispatchGuide extends Model
{
    use HasFactory;

    protected $table = "tbl_dispatch_guide";

    protected $fillable = [
        'date',
        'n_document',
        'idroute',
        'idproduct',
        'idwarehouse',
        'cantidad',
        'idcompany',
        'status'
    ];

    protected $hidden = [
        'created_at',
        'updated_at'
    ];

    #Relaciones
    
    public function details(): HasMany
    {
        return $this->hasMany(DispatchGuideDetail::class, 'iddispatch_guide', 'id');
    }
    
    public function route(): BelongsTo
    {
        return $this->belongsTo(Route::class, 'idroute', 'id');
    }
    
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'idproduct', 'id');
    }
    
    public function warehouse(): BelongsTo
    {
        return $this->belongsTo(Store::class, 'idwarehouse', 'id');
    }
    
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class, 'idcompany', 'id');
    }
    


    # Query scopes
    public function scopeActiveForID($query, $id)
    {
        return $query->where('id', $id)->where('status', 1);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    public function scopeCompany($query)
    {
        return $query->when(
            request('idcompany'),
            fn($query) => $query->where('idcompany', request('idcompany'))
        );
    }

}
