<?php

namespace App\Livewire\Store;

use App\Models\Banner;
use App\Models\Category;
use App\Models\Partner;
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('Beranda')]
class Home extends Component
{
    use WithPagination;

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

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

    public string $filterPrice = '';   // all | under50k | 50k-100k | above100k
    public string $filterFeatured = ''; // '' | featured

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

    public function setCategory(string $slug): void
    {
        $this->filterCategory = $this->filterCategory === $slug ? '' : $slug;
        $this->resetPage();
    }

    public function render()
    {
        // ── Banner aktif, urut sort_order ────────────────────────────────
        $banners = Banner::active()->get();

        // ── Kategori aktif ────────────────────────────────────────────────
        $categories = Category::where('is_active', true)
            ->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get();

        // ── Produk dengan filter & search ────────────────────────────────
        $search = new \App\Services\SearchHelper($this->search);

        $productsQuery = 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))
            ->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
            ->orderBy('sort_order')
            ->orderByDesc('created_at');

        // Mode search/filter: tampilkan semua di satu grid dengan pagination
        // Mode default (beranda): tampilkan section terpisah (terbaru + unggulan)
        $isFiltering = $this->search || $this->filterCategory || $this->filterPrice || $this->filterFeatured;

        $products        = null;
        $newestProducts  = collect();
        $featuredProducts = collect();

        if ($isFiltering) {
            $products = $productsQuery->paginate(12);
        } else {
            $newestProducts   = (clone $productsQuery)->take(8)->get();
            $featuredProducts = Product::with(['category', 'partner'])
                ->where('is_active', true)
                ->where('is_featured', true)
                ->orderByRaw('CASE WHEN sort_order = 0 THEN 1 ELSE 0 END')
                ->orderBy('sort_order')
                ->take(8)
                ->get();
        }

        // ── Mitra aktif ───────────────────────────────────────────────────
        $partners = Partner::where('is_active', true)
            ->withCount(['products' => fn ($q) => $q->where('is_active', true)])
            ->orderBy('name')
            ->take(6)
            ->get();

        return view('livewire.store.home', compact(
            'banners', 'categories', 'partners',
            'products', 'newestProducts', 'featuredProducts', 'isFiltering'
        ));
    }
}
