<?php

namespace App\Livewire\Merchant;

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

#[Layout('layouts.merchant')]
#[Title('المنتجات - تاجر بلس')]
class ProductsPage extends Component
{
    public string $search = '';
    public string $fulfillmentFilter = '';
    public ?int $expandedProductId = null;
    public array $quantities = [];

    public function addToCart(int $variantId, int $productId): 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 toggleProduct(int $productId): void
    {
        $this->expandedProductId = $this->expandedProductId === $productId ? null : $productId;
    }

    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))
            ->withCount('variants')
            ->with(['pricingTiers', 'variants' => fn ($q) => $q->where('is_active', true)])
            ->orderBy('name')
            ->get();

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