<?php

namespace App\Http\Livewire\Storefront;

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

class ProductList extends Component
{
    use WithPagination;

    public string $search      = '';
    public string $sortBy      = 'latest';
    public ?int   $categoryId  = null;
    public bool   $featuredOnly = false;

    protected $queryString = [
        'search'       => ['except' => ''],
        'sortBy'       => ['except' => 'latest'],
        'categoryId'   => ['except' => null, 'as' => 'category'],
        'featuredOnly' => ['except' => false, 'as' => 'featured'],
    ];

    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    public function updatingSortBy(): void
    {
        $this->resetPage();
    }

    public function updatingCategoryId(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        $query = Product::query()
            ->where('is_visible', true)
            ->with(['variants', 'media'])
            ->when($this->search, fn ($q) =>
                $q->where(function ($sub) {
                    $sub->where('name', 'like', '%' . $this->search . '%')
                        ->orWhere('sku', 'like', '%' . $this->search . '%')
                        ->orWhere('short_description', 'like', '%' . $this->search . '%');
                })
            )
            ->when($this->categoryId, fn ($q) =>
                $q->where('category_id', $this->categoryId)
            )
            ->when($this->featuredOnly, fn ($q) =>
                $q->where('is_featured', true)
            );

        $query = match ($this->sortBy) {
            'price_asc'  => $query->orderBy('price', 'asc'),
            'price_desc' => $query->orderBy('price', 'desc'),
            'name_asc'   => $query->orderBy('name', 'asc'),
            'featured'   => $query->orderBy('is_featured', 'desc')->orderByDesc('created_at'),
            default      => $query->orderByDesc('created_at'), // latest
        };

        $products   = $query->paginate(12);
        $categories = \App\Models\Category::where('is_visible', true)
            ->orderBy('name')
            ->get();

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