<?php

namespace App\Livewire;

use App\Models\Opcion;
use App\Models\Producto;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

class Filter extends Component
{
    use WithPagination;

    public $familia_id;
    public $categoria_id;
    public $subcategoria_id;

    public $opciones;
    public $selected_caracteristicas = [];
    public $orderBy = 1;
    public $search;

    public function mount(){

        $this->opciones = Opcion::verificarFamilia($this->familia_id)
        ->verificarCategoria($this->categoria_id)
        ->verificarSubcategoria($this->subcategoria_id)
        ->get()->toArray();
    }

    public function render()
    {
        $productos = Producto::when($this->familia_id, function($query){
            $query->whereHas('subcategoria.categoria', function($query){
                $query->where('familia_id', $this->familia_id);
            });
        })->when($this->categoria_id, function($query){
            $query->whereHas('subcategoria', function($query){
                $query->where('categoria_id', $this->categoria_id);
            });
        })->when($this->subcategoria_id, function($query){
            $query->where('subcategoria_id', $this->subcategoria_id);
        })->when($this->orderBy == 1,function($query){
            $query->orderBy('created_at','desc');
        })->when($this->orderBy == 2,function($query){
            $query->orderBy('precio','desc');
        })->when($this->orderBy == 3,function($query){
            $query->orderBy('precio','asc');
        })->when($this->selected_caracteristicas, function($query){
            $query->whereHas('variantes.caracteristicas', function($query){
                $query->whereIn('caracteristicas.id', $this->selected_caracteristicas);
            });
        })->when($this->search, function($query){
            $query->where('nombre', 'like', '%'.$this->search.'%'); 
        })->paginate(12);
        return view('livewire.filter',compact('productos'));
    }

    #[On('search')]
    public function search($search){
        $this->search = $search; 
    }
}
