<?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 IntakeCart extends Model
{
    use HasFactory;

    protected $table = "tbl_intake_cart";

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

    protected $hidden = [
        'created_at',
        '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(IntakeCartDetail::class, 'idintake_cart', '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('id'),
            fn($query) => $query->where('id', request('id'))
        );

        $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->when(
            request('status_entry') !== null,
            fn($query) => $query->where('status_entry', request('status_entry'))
        );

        $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)
        );
    }
}
