<?php

namespace App\Models;

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

class ListOfProduct extends Model
{
    use HasFactory;

    protected $table = "tbl_list_of_products";
    protected $primaryKey = "id";

    protected $fillable = [
        'name',
        'validity',
        'idproducts',
        'idcompany',
        'status',
    ];

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

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

    # Filtros
    public function scopeListProductFilters($query)
    {
        #Filtro de Buscador
        $query->when(
            request('search'),
            fn ($query) => $query->where('name', 'LIKE', '%' . request('search') . '%')
        );

        #Filtro de nombre
        $query->when(
            request('name'),
            fn ($query) => $query->where('name', 'LIKE', '%' . request('name') . '%')
        );

        #Filtro de validez
        $query->when(
            request('validity'),
            fn ($query) => $query->where('validity', request('validity'))

        );

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

        );

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