<?php

namespace App\Livewire\Store;

use App\Models\Cart as CartModel;
use App\Models\Product;
use Livewire\Component;

/**
 * Komponen kecil untuk tombol "Tambah ke Keranjang".
 * Dipakai di: product-card.blade.php, product-show.blade.php
 *
 * Mengirim event 'cart-updated' yang didengar oleh CartBadge.
 */
class AddToCart extends Component
{
    public int    $productId;
    public int    $qty      = 1;
    public bool   $added    = false;
    public string $message  = '';
    public bool   $fullWidth = false; // true di product-show, false di product-card

    public function mount(int $productId, bool $fullWidth = false): void
    {
        $this->productId  = $productId;
        $this->fullWidth  = $fullWidth;
    }

    public function add(): void
    {
        $product = Product::find($this->productId);

        if (! $product || ! $product->is_active) {
            $this->message = 'Produk tidak tersedia.';
            return;
        }

        if ($product->isOutOfStock()) {
            $this->message = 'Stok habis.';
            return;
        }

        $existing = CartModel::forSession(session()->getId())
            ->where('product_id', $this->productId)
            ->first();

        if ($existing) {
            $newQty = $existing->quantity + $this->qty;

            if ($product->isStockManaged() && $newQty > $product->stock) {
                $this->message = 'Stok hanya tersisa ' . $product->stock . '.';
                return;
            }

            $existing->update(['quantity' => $newQty]);
        } else {
            CartModel::create([
                'session_id' => session()->getId(),
                'product_id' => $this->productId,
                'quantity'   => $this->qty,
                'notes'      => '',
            ]);
        }

        $this->added   = true;
        $this->message = '';

        $this->dispatch('cart-updated');

        // Reset visual feedback setelah 1.5 detik
        $this->js("setTimeout(() => \$wire.added = false, 1500)");
    }

    public function render()
    {
        return view('livewire.store.partials.add-to-cart');
    }
}
