<?php

namespace App\Models;

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

class DetailPriceListSalesman extends Model
{
    use HasFactory;
    protected $table = 'tbl_detail_pricelist_salesman';

    protected $fillable = [
        'idpricelist',
        'idsalesman',
        'idcompany',
        'status',
    ];

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

    public function pricelist(): HasOne
    {
        return $this->hasOne(PriceList::class, 'id', 'idpricelist');
    }

    public function salesman(): HasOne
    {
        return $this->hasOne(Salesman::class, 'id', 'idsalesman');
    }

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

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

    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 scopeSalesmanID($query, $pricelist, $salesman, $id = null)
    {
        return $query->when($id, fn ($query) => $query->where('id', '<>', $id))->where('idpricelist', $pricelist)->where('idsalesman', $salesman)->company();
    }

    # Filtros
    public function scopePriceListSalesmanFilters($query)
    {
        #Filtro de precio de lista
        $query->when(
            request('idpricelist'),
            fn ($query) => $query->where('idpricelist', request('idpricelist'))
        );

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

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

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