<?php

namespace App\Livewire\Products;

use Daylight\Core\Models\Variant;
use Daylight\Core\Modules\Cart\Contracts\CartInterface;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;

class AddToCart extends Component
{
    public ?Variant $variant = null;

    public bool $disabled = false;

    public int $quantity = 1;

    public function updatedQuantity()
    {
        $this->dispatch('quantity-changed', $this->quantity);
    }

    public function increment()
    {
        //        $this->quantity = min($this->variant->stock, $this->quantity + 1);
        $this->quantity = $this->quantity + 1;

        $this->dispatch('quantity-changed', $this->quantity);
    }

    public function decrement()
    {
        $this->quantity = max(1, $this->quantity - 1);

        $this->dispatch('quantity-changed', $this->quantity);
    }

    #[On('current-variant-changed')]
    public function currentVariantChanged(Variant $variant)
    {
        $this->variant = $variant;
    }

    public function addToCart(CartInterface $cart)
    {
        $cart->add($this->variant, $this->quantity);

        $this->dispatch('add-to-cart', $this->variant->getDataLayerInformation($this->quantity));

        $this->dispatch('cart-updated');
        $this->dispatch('show-cart-summary');
    }

    public function render(): View
    {
        return view('livewire.products.add-to-cart');
    }
}
