<?php

namespace App\Models;

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

class DetailPriceListProduct extends Model
{
    use HasFactory;
    protected $table = 'tbl_detail_pricelist_products';

    protected $fillable = [
        'price',
        'cost',
        'stock',
        'subtotal',
        'discount',
        'idpricelist',
        'idproduct',
        'idcompany',
        'status',
    ];

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

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

    public function product(): HasOne
    {
        return $this->hasOne(Product::class, 'id', 'idproduct');
    }

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

    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 scopeProductsID($query, $list, $product, $id = null)
    {
        return $query->when($id, fn ($query) => $query->where('id', '<>', $id))->where('idproduct', $product)->where('idpricelist', $list)->company();
    }

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

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

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