<?php

namespace App\Livewire;

use App\Models\Category;
use App\Models\Product;
use Livewire\Component;
use Livewire\WithPagination;

class ProductSection extends Component
{
    use WithPagination;

    public string $search = '';

    public ?int $selectedCategoryId = null;

    public int $perPage = 8;

    protected $queryString = [
        'search' => ['except' => ''],
        'selectedCategoryId' => ['except' => null],
    ];

    public function updatedSearch()
    {
        $this->resetPage();
    }

    public function filterByCategory(?int $categoryId)
    {
        $this->selectedCategoryId = $categoryId;
        $this->resetPage();
    }

    public function render()
    {
        $categories = Category::active()
            ->orderBy('sort_order')
            ->get();

        $products = Product::active()
            ->when($this->search, function ($q) {
                $q->where(function ($q) {
                    $q->where('name', 'like', '%' . $this->search . '%')
                        ->orWhere('description', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->selectedCategoryId, function ($q) {
                $q->where('category_id', $this->selectedCategoryId);
            })
            ->orderBy('sort_order')
            ->paginate($this->perPage);

        return view('livewire.product-section', [
            'products' => $products,
            'categories' => $categories,
        ]);
    }
}