<?php

namespace App\Http\Controllers\API;

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

class CartController extends Controller
{
    public function index(Request $request)
    {
        $carts = Cart::with(['product', 'restaurant'])
            ->where('user_id', $request->user()->id)
            ->get()
            ->map(function ($cart) {
                return [
                    'id' => $cart->id,
                    'restaurant_id' => $cart->restaurant_id,
                    'restaurant_name' => $cart->restaurant->name ?? 'Unknown',
                    'product_name' => $cart->product->name ?? 'Unknown',
                    'price' => $cart->unit_price,
                    'quantity' => $cart->quantity,
                    'variation' => !empty($cart->variations) ? collect($cart->variations)->pluck('name')->join(', ') : null,
                    'addons' => !empty($cart->addons) ? collect($cart->addons)->pluck('name')->toArray() : [],
                    'special_notes' => $cart->special_notes,
                ];
            });

        $total = $carts->sum(fn($item) => $item['price'] * $item['quantity']);

        return response()->json([
            'data' => $carts,
            'total' => $total,
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
            'variation_id' => 'nullable|integer|exists:product_variations,id',
            'addon_ids' => 'nullable|array',
            'addon_ids.*' => 'integer|exists:product_addons,id',
        ]);

        $product = Product::with('variations')->findOrFail($request->product_id);

        if (!$product->is_available) {
            return response()->json(['message' => 'Product not available'], 404);
        }

        // If product has variations, base price is 0 (price comes from variation)
        if ($product->variations && $product->variations->count() > 0) {
            $basePrice = 0;
        } else {
            // Use discount as offer price if available, otherwise regular price
            $basePrice = $product->discount > 0 ? $product->discount : $product->price;
        }
        $selectedVariation = null;
        $selectedAddons = collect([]);

        if ($request->filled('variation_id')) {
            $selectedVariation = ProductVariation::where('id', $request->variation_id)
                ->where('product_id', $product->id)
                ->first(['id', 'name', 'value', 'price', 'discount']);
            
            // If discount field has value, use it as selling price instead of regular price
            if ($selectedVariation && $selectedVariation->discount > 0) {
                $selectedVariation->price = $selectedVariation->discount;
            }
        }

        if ($request->filled('addon_ids')) {
            $selectedAddons = ProductAddon::whereIn('id', $request->addon_ids)
                ->where('product_id', $product->id)
                ->get(['id', 'name', 'price']);
        }

        $variationPrice = $selectedVariation ? ($selectedVariation->price ?? 0) : 0;
        $addonsPrice = $selectedAddons->sum('price');
        $unitPrice = $basePrice + $variationPrice + $addonsPrice;
        $totalPrice = $unitPrice * $request->quantity;

        $cart = Cart::create([
            'user_id' => $request->user()->id,
            'restaurant_id' => $product->restaurant_id,
            'product_id' => $product->id,
            'quantity' => $request->quantity,
            'unit_price' => $unitPrice,
            'variations' => $selectedVariation ? [$selectedVariation->toArray()] : [],
            'addons' => $selectedAddons->toArray(),
            'special_notes' => $request->special_notes,
            'total_price' => $totalPrice,
        ]);

        return response()->json($cart->load('product'), 201);
    }

    public function update(Request $request, $id)
    {
        $cart = Cart::where('user_id', $request->user()->id)->findOrFail($id);

        $cart->update([
            'quantity' => $request->quantity,
            'total_price' => $cart->unit_price * $request->quantity,
        ]);

        return response()->json($cart);
    }

    public function destroy(Request $request, $id)
    {
        $cart = Cart::where('user_id', $request->user()->id)->findOrFail($id);

        $cart->delete();

        return response()->json(['message' => 'Item removed from cart']);
    }

    public function clear(Request $request)
    {
        Cart::where('user_id', $request->user()->id)->delete();

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