<?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;

class ProductEntry extends Model
{
    use HasFactory;

    protected $table = "tbl_product_entry";

    protected $fillable = [
        'idintake_cart',
        'iduser_created',
        'idsupplier',
        'cost_total',
        'idcompany',
        'status'
    ];

    protected $hidden = [
        'updated_at'
    ];


    # Relaciones
    public function userCreated(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'iduser_created');
    }

    public function supplier(): HasOne
    {
        return $this->hasOne(Supplier::class, 'id', 'idsupplier');
    }

    public function company(): HasOne
    {
        return $this->hasOne(Company::class, 'id', 'idcompany');
    }

    public function details(): HasMany
    {
        return $this->hasMany(ProductEntryDetail::class, 'idproduct_entry', 'id')->active();
    }


    # 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'))
        );
    }

    # Filtros
    public function scopeFilters($query)
    {
        $query->when(
            request('iduser_created'),
            fn($query) => $query->where('iduser_created', request('iduser_created'))
        );

        $query->when(
            request('idsupplier'),
            fn($query) => $query->where('idsupplier', request('idsupplier'))
        );

        $query->company();

        #Filtro de estados
        $query->when(
            request('status'),
            fn($query) => $query->where('status', request('status'))
        )->when(
            !request('status'),
            fn($query) => $query->where('status', 1)
        );
    }
}
