<?php

namespace App\Http\Controllers\Store;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CartController extends Controller
{
    /**
     * Tambah produk ke keranjang via POST JSON.
     * Dipanggil dari Alpine.js di product-card.blade.php.
     */
    public function add(Request $request): JsonResponse
    {
        $productId = (int) $request->input('product_id', 0);
        $qty       = max(1, (int) $request->input('qty', 1));

        $product = Product::find($productId);

        if (! $product || ! $product->is_active) {
            return response()->json(['ok' => false, 'message' => 'Produk tidak tersedia.'], 422);
        }

        if ($product->isOutOfStock()) {
            return response()->json(['ok' => false, 'message' => 'Stok produk habis.'], 422);
        }

        $sessionId = session()->getId();

        $existing = Cart::forSession($sessionId)
            ->where('product_id', $productId)
            ->first();

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

            if ($product->isStockManaged() && $newQty > $product->stock) {
                return response()->json([
                    'ok'      => false,
                    'message' => 'Stok hanya tersisa ' . $product->stock . '.',
                ], 422);
            }

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

        $totalQty = Cart::forSession($sessionId)->sum('quantity');

        return response()->json([
            'ok'       => true,
            'message'  => $product->name . ' ditambahkan ke keranjang.',
            'cart_qty' => $totalQty,
        ]);
    }

    /**
     * Ambil jumlah item di keranjang (untuk badge).
     */
    public function count(): JsonResponse
    {
        $qty = Cart::forSession(session()->getId())->sum('quantity');

        return response()->json(['cart_qty' => $qty]);
    }
}
