<?php

namespace App\Livewire\Store;

use App\Models\Cart as CartModel;
use App\Models\Product;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.store')]
#[Title('Keranjang')]
class Cart extends Component
{
    // ── State ─────────────────────────────────────────────────────────────

    /** Keyed by cart item ID: ['notes' => string] */
    public array $itemNotes = [];

    // ── Lifecycle ─────────────────────────────────────────────────────────

    public function mount(): void
    {
        // Inisialisasi notes dari DB agar input ter-bind dengan benar
        foreach ($this->getCartItems() as $item) {
            $this->itemNotes[$item->id] = $item->notes ?? '';
        }
    }

    // ── Cart helpers ──────────────────────────────────────────────────────

    /**
     * Ambil cart items milik session ini, eager load product + partner.
     */
    private function getCartItems()
    {
        return CartModel::with(['product.partner'])
            ->forSession(session()->getId())
            ->latest()
            ->get();
    }

    /**
     * Ambil atau buat cart item untuk produk tertentu pada session ini.
     */
    private function findOrCreateItem(int $productId): ?CartModel
    {
        return CartModel::forSession(session()->getId())
            ->where('product_id', $productId)
            ->first();
    }

    // ── Actions ───────────────────────────────────────────────────────────

    /**
     * Tambah produk ke keranjang.
     * Dipanggil dari ProductCard dan ProductShow via event.
     */
    public function addToCart(int $productId, int $qty = 1): void
    {
        $product = Product::find($productId);

        if (! $product || ! $product->is_active) {
            $this->dispatch('cart-error', message: 'Produk tidak tersedia.');
            return;
        }

        if ($product->isOutOfStock()) {
            $this->dispatch('cart-error', message: 'Stok produk habis.');
            return;
        }

        $existing = $this->findOrCreateItem($productId);

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

            // Cek batas stok (hanya jika stok dikelola)
            if ($product->isStockManaged() && $newQty > $product->stock) {
                $this->dispatch('cart-error', message: 'Jumlah melebihi stok tersedia (' . $product->stock . ').');
                return;
            }

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

        $this->dispatch('cart-updated');
        $this->dispatch('cart-success', message: $product->name . ' ditambahkan ke keranjang.');
    }

    /**
     * Ubah qty dari halaman keranjang.
     */
    public function updateQty(int $cartId, int $delta): void
    {
        $item = CartModel::with('product')
            ->forSession(session()->getId())
            ->find($cartId);

        if (! $item) return;

        $newQty = max(1, $item->quantity + $delta);

        // Cek batas stok
        if ($delta > 0 && $item->product->isStockManaged() && $newQty > $item->product->stock) {
            $this->dispatch('cart-error', message: 'Stok hanya tersisa ' . $item->product->stock . '.');
            return;
        }

        $item->update(['quantity' => $newQty]);
        $this->dispatch('cart-updated');
    }

    /**
     * Simpan catatan per item (dipanggil saat blur dari textarea).
     */
    public function saveNote(int $cartId): void
    {
        $item = CartModel::forSession(session()->getId())->find($cartId);

        if (! $item) return;

        $item->update(['notes' => $this->itemNotes[$cartId] ?? '']);
    }

    /**
     * Hapus item dari keranjang.
     */
    public function removeItem(int $cartId): void
    {
        CartModel::forSession(session()->getId())
            ->where('id', $cartId)
            ->delete();

        unset($this->itemNotes[$cartId]);
        $this->dispatch('cart-updated');
    }

    /**
     * Kosongkan seluruh keranjang.
     */
    public function clearCart(): void
    {
        CartModel::forSession(session()->getId())->delete();
        $this->itemNotes = [];
        $this->dispatch('cart-updated');
    }

    // ── Render ────────────────────────────────────────────────────────────

    public function render()
    {
        $items    = $this->getCartItems();
        $subtotal = $items->sum('subtotal');

        // Ongkir placeholder — Sprint 2.3 akan isi berdasarkan pilihan area
        $shippingFee = 0;
        $grandTotal  = $subtotal + $shippingFee;

        // Pengelompokan HANYA untuk tampilan — bukan pemisahan checkout.
        // Tetap satu keranjang, satu checkout. Backend yang memecah order per mitra.
        $groupedItems = $items->groupBy(fn ($item) => $item->product->partner_id);
        $partnerCount = $groupedItems->count();

        return view('livewire.store.cart', compact(
            'items', 'subtotal', 'shippingFee', 'grandTotal',
            'groupedItems', 'partnerCount'
        ));
    }
}
