<?php

namespace App\Http\Controllers\Api;

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

class CartController extends Controller
{
    /**
     * Get current customer's cart with items.
     */
    public function index(Request $request)
    {
        $customer = $request->user();
        $cart = Cart::with(['items.product.images', 'items.productWeight.weightUnit', 'coupon'])
            ->firstOrCreate(
                ['customer_id' => $customer->id],
                ['session_id' => null]
            );

        // Calculate totals
        $subtotal = $cart->items->sum(function ($item) {
            return $item->productWeight->price * $item->quantity;
        });

        return response()->json([
            'data' => $cart,
            'subtotal' => round($subtotal, 3),
            'items_count' => $cart->items->sum('quantity'),
        ]);
    }

    /**
     * Add product + weight to cart.
     */
    public function addItem(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'product_weight_id' => 'required|exists:product_weights,id',
            'quantity' => 'required|integer|min:1|max:99',
            'notes' => 'nullable|string|max:500',
        ]);

        $customer = $request->user();

        // Verify weight belongs to product
        $weight = ProductWeight::where('id', $request->product_weight_id)
            ->where('product_id', $request->product_id)
            ->firstOrFail();

        // Check stock
        if ($weight->stock < $request->quantity) {
            return response()->json([
                'message' => 'الكمية المطلوبة غير متوفرة في المخزون',
            ], 422);
        }

        $cart = Cart::firstOrCreate(
            ['customer_id' => $customer->id],
            ['session_id' => null]
        );

        // Check if item already in cart
        $existingItem = $cart->items()
            ->where('product_id', $request->product_id)
            ->where('product_weight_id', $request->product_weight_id)
            ->first();

        if ($existingItem) {
            $newQty = $existingItem->quantity + $request->quantity;
            if ($weight->stock < $newQty) {
                return response()->json([
                    'message' => 'الكمية المطلوبة تتجاوز المخزون المتوفر',
                ], 422);
            }
            $existingItem->update(['quantity' => $newQty]);
            $item = $existingItem->fresh(['product.images', 'productWeight.weightUnit']);
        } else {
            $item = $cart->items()->create([
                'product_id' => $request->product_id,
                'product_weight_id' => $request->product_weight_id,
                'quantity' => $request->quantity,
                'notes' => $request->notes,
            ]);
            $item->load(['product.images', 'productWeight.weightUnit']);
        }

        return response()->json([
            'message' => 'تمت الإضافة إلى السلة',
            'data' => $item,
        ], 201);
    }

    /**
     * Update cart item quantity.
     */
    public function updateItem(Request $request, CartItem $cartItem)
    {
        $request->validate([
            'quantity' => 'required|integer|min:1|max:99',
        ]);

        // Verify ownership
        $cart = Cart::where('customer_id', $request->user()->id)->firstOrFail();
        if ($cartItem->cart_id !== $cart->id) {
            return response()->json(['message' => 'غير مصرح'], 403);
        }

        // Check stock
        if ($cartItem->productWeight->stock < $request->quantity) {
            return response()->json([
                'message' => 'الكمية المطلوبة غير متوفرة في المخزون',
            ], 422);
        }

        $cartItem->update(['quantity' => $request->quantity]);
        $cartItem->load(['product.images', 'productWeight.weightUnit']);

        return response()->json([
            'message' => 'تم تحديث الكمية',
            'data' => $cartItem,
        ]);
    }

    /**
     * Remove item from cart.
     */
    public function removeItem(Request $request, CartItem $cartItem)
    {
        $cart = Cart::where('customer_id', $request->user()->id)->firstOrFail();
        if ($cartItem->cart_id !== $cart->id) {
            return response()->json(['message' => 'غير مصرح'], 403);
        }

        $cartItem->delete();

        return response()->json([
            'message' => 'تم حذف المنتج من السلة',
        ]);
    }

    /**
     * Clear entire cart.
     */
    public function clear(Request $request)
    {
        $cart = Cart::where('customer_id', $request->user()->id)->first();

        if ($cart) {
            $cart->items()->delete();
            $cart->update(['coupon_id' => null]);
        }

        return response()->json([
            'message' => 'تم تفريغ السلة',
        ]);
    }
}
