<?php

namespace App\Livewire;

use App\Models\Product;
use App\Services\CartService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.merchant')]
#[Title('تاجر بلس - كاتالوج المنتجات')]
class CatalogPage extends Component
{
    #[Url]
    public string $search = '';

    #[Url]
    public string $fulfillmentFilter = '';

    public array $quantities = [];

    public function addToCart(int $variantId): void
    {
        $qty = $this->quantities[$variantId] ?? 1;
        if ($qty < 1) $qty = 1;

        app(CartService::class)->addItem($variantId, $qty);

        $this->dispatch('cart-updated');
        session()->flash('success', 'تمت الإضافة إلى السلة بنجاح');
    }

    public function render()
    {
        $products = Product::query()
            ->where('is_active', true)
            ->when($this->search, fn ($q) => $q->where('name', 'like', "%{$this->search}%"))
            ->when($this->fulfillmentFilter, fn ($q) => $q->where('fulfillment_type', $this->fulfillmentFilter))
            ->with([
                'pricingTiers',
                'variants' => fn ($q) => $q->where('is_active', true)->orderByDesc('id'),
            ])
            ->withCount('variants')
            ->get()
            ->sortByDesc(fn ($product) => $product->pricingTiers->max('unit_price') ?? 0)
            ->values();

        return view('livewire.catalog-page', compact('products'));
    }
}
