<?php

namespace App\Livewire\Store;

use App\Models\Category;
use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.store')]
#[Title('Semua Produk')]
class Products extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public string $search = '';

    #[Url(as: 'kategori')]
    public string $filterCategory = '';

    public string $filterPrice    = '';
    public string $filterFeatured = '';
    public string $sortBy         = 'terbaru'; // terbaru | termurah | termahal | unggulan

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

    public function render()
    {
        $categories = Category::where('is_active', true)
            ->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        $search = new \App\Services\SearchHelper($this->search);

        $products = Product::with(['category', 'partner'])
            ->where('is_active', true)
            ->when($search->hasTokens(), function ($q) use ($search) {
                $q->where(fn ($q) => $search->applyWhere($q))
                  ->orderByRaw($search->scoreExpression() . ' DESC');
            })
            ->when($this->filterCategory, function ($q) {
                $q->whereHas('category', fn ($q) =>
                    $q->where('slug', $this->filterCategory));
            })
            ->when($this->filterFeatured === 'featured', fn ($q) =>
                $q->where('is_featured', true))
            ->when($this->filterPrice === 'under50k', fn ($q) =>
                $q->where('sell_price', '<', 50000))
            ->when($this->filterPrice === '50k-100k', fn ($q) =>
                $q->whereBetween('sell_price', [50000, 100000]))
            ->when($this->filterPrice === 'above100k', fn ($q) =>
                $q->where('sell_price', '>', 100000))
            ->when($this->sortBy === 'termurah', fn ($q) =>
                $q->orderBy('sell_price'))
            ->when($this->sortBy === 'termahal', fn ($q) =>
                $q->orderByDesc('sell_price'))
            ->when($this->sortBy === 'unggulan', fn ($q) =>
                $q->orderByDesc('is_featured'))
            ->when($this->sortBy === 'terbaru' || ! $this->sortBy,
                fn ($q) => $q->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
                             ->orderBy('sort_order')
                             ->orderByDesc('created_at'))
            ->paginate(16);

        return view('livewire.store.products', compact('products', 'categories'));
    }
}
