<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CartController extends Controller
{
    private function getOrCreateCart(Request $request): Cart
    {
        return Cart::firstOrCreate(['user_id' => $request->user()->id]);
    }

    public function show(Request $request): JsonResponse
    {
        $cart = $this->getOrCreateCart($request);
        $cart->load(['items.product.primaryImage', 'items.variant']);

        return response()->json([
            'success' => true,
            'data'    => [
                'id'          => $cart->id,
                'items'       => $cart->items,
                'total'       => $cart->total,
                'items_count' => $cart->items_count,
            ],
        ]);
    }

    public function addItem(Request $request): JsonResponse
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
            'variant_id' => 'nullable|exists:product_variants,id',
        ]);

        $product = Product::where('is_active', true)->findOrFail($request->product_id);
        
        // اگر variant_id ارسال شده، از موجودی و قیمت آن استفاده کن
        if ($request->variant_id) {
            $variant = $product->variants()->findOrFail($request->variant_id);
            $stock = $variant->stock;
            $price = $variant->final_price;
        } else {
            $stock = $product->stock;
            $price = $product->final_price;
        }

        if ($stock < $request->quantity) {
            return response()->json([
                'success'         => false,
                'message'         => 'موجودی کافی نیست.',
                'available_stock' => $stock,
            ], 422);
        }

        $cart     = $this->getOrCreateCart($request);
        
        // بررسی اگر همین محصول با همین واریانت قبلاً اضافه شده
        $cartItem = $cart->items()
            ->where('product_id', $product->id)
            ->where('variant_id', $request->variant_id)
            ->first();

        if ($cartItem) {
            $newQty = $cartItem->quantity + $request->quantity;
            if ($stock < $newQty) {
                return response()->json([
                    'success'         => false,
                    'message'         => 'موجودی کافی نیست.',
                    'available_stock' => $stock,
                ], 422);
            }
            $cartItem->update(['quantity' => $newQty]);
        } else {
            $cartItem = CartItem::create([
                'cart_id'    => $cart->id,
                'product_id' => $product->id,
                'variant_id' => $request->variant_id,
                'quantity'   => $request->quantity,
                'price'      => $price,
            ]);
        }

        $cart->load(['items.product.primaryImage', 'items.variant']);

        return response()->json([
            'success' => true,
            'message' => 'محصول به سبد خرید اضافه شد.',
            'data'    => [
                'id'          => $cart->id,
                'items'       => $cart->items,
                'total'       => $cart->total,
                'items_count' => $cart->items_count,
            ],
        ]);
    }

    public function updateItem(Request $request, int $itemId): JsonResponse
    {
        $request->validate([
            'quantity' => 'required|integer|min:1',
        ]);

        $cart     = $this->getOrCreateCart($request);
        $cartItem = CartItem::where('cart_id', $cart->id)->findOrFail($itemId);
        
        // استفاده از موجودی واریانت یا محصول
        if ($cartItem->variant_id) {
            $stock = $cartItem->variant->stock;
        } else {
            $stock = $cartItem->product->stock;
        }

        if ($stock < $request->quantity) {
            return response()->json([
                'success'         => false,
                'message'         => 'موجودی کافی نیست.',
                'available_stock' => $stock,
            ], 422);
        }

        $cartItem->update(['quantity' => $request->quantity]);
        $cart->load(['items.product.primaryImage', 'items.variant']);

        return response()->json([
            'success' => true,
            'message' => 'سبد خرید به‌روز شد.',
            'data'    => [
                'id'          => $cart->id,
                'items'       => $cart->items,
                'total'       => $cart->total,
                'items_count' => $cart->items_count,
            ],
        ]);
    }

    public function removeItem(Request $request, int $itemId): JsonResponse
    {
        $cart     = $this->getOrCreateCart($request);
        $cartItem = CartItem::where('cart_id', $cart->id)->findOrFail($itemId);
        $cartItem->delete();

        $cart->load(['items.product.primaryImage', 'items.variant']);

        return response()->json([
            'success' => true,
            'message' => 'محصول از سبد خرید حذف شد.',
            'data'    => [
                'id'          => $cart->id,
                'items'       => $cart->items,
                'total'       => $cart->total,
                'items_count' => $cart->items_count,
            ],
        ]);
    }

    public function clear(Request $request): JsonResponse
    {
        $cart = $this->getOrCreateCart($request);
        $cart->items()->delete();

        return response()->json([
            'success' => true,
            'message' => 'Cart cleared.',
        ]);
    }
}
