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

    protected $table = "tbl_shopping_cart";

    protected $fillable = [
        'iduser_created',
        'idcustomer',
        'documenttype',
        'global_discount',
        // 'discounttype',
        'sub_total',
        'net_total',
        'IGV',
        'gross_total',
        'total_discount',
        'total',
        'idcompany',
        'status_ticket',
        'status'
    ];

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

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

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

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

    public function detail(): HasMany
    {
        return $this->hasMany(DetailShoppingCart::class, 'idshopping_cart', 'id')->where('status', 1);
    }

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

    public function scopeShoppingCartCustomer($query, $iduser, $idcustomer)
    {
        return $query->where('iduser_created', $iduser)->where('idcustomer', $idcustomer);
    }

    # Filtros
    public function scopeShoppingCartFilters($query)
    {
        #Filtro de usuario creado
        $query->when(
            request('iduser_created'),
            fn ($query) => $query->where('iduser_created', request('iduser_created'))
        );

        #Filtro de cliente
        $query->when(
            request('idcustomer'),
            fn ($query) => $query->where('idcustomer', request('idcustomer'))
        );

        #Filtro de idcompany
        $query->company();

        #Filtro de ticket emitido
        $query->when(
            request('status_ticket') !== null,
            fn ($query) => $query->where('status_ticket', request('status_ticket'))
        );

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