<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\CartItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    public function index()
    {
        $currency = session('currency', 'USD');
        $total = 0;
        $cartItems = [];
        $suggestedProducts = [];

        if (auth()->check()) {
            $cartItems = CartItem::with('product')
                ->where('user_id', auth()->id())
                ->get();
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $item->subtotal = $item->product->getCurrentPrice($currency) * $item->quantity;
                    $total += $item->subtotal;
                }
            }
        } else {
            $cartItems = session()->get('cart', []);
        if (empty($cartItems)) {
            $suggestedProducts = Product::active()->latest()->take(4)->get();
        } else {
            foreach ($cartItems as &$item) {
                $product = Product::find($item['product_id']);
                if ($product) {
                    $item['product'] = $product;
                    $item['subtotal'] = $product->getCurrentPrice($currency) * $item['quantity'];
                    $total += $item['subtotal'];
                    }
                }
            }
        }

        return view('cart.index', compact('cartItems', 'total', 'suggestedProducts', 'currency'));
    }

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

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

    if (! $product->is_active || ! $product->inStock()) {
        return response()->json([
            'success' => false,
            'message' => 'Product is not available',
        ], 400);
    }

    if ($request->quantity > $product->stock_quantity) {
        return response()->json([
            'success' => false,
            'message' => 'Insufficient stock available',
        ], 400);
    }

    if (auth()->check()) {
        $cartItem = CartItem::firstOrNew([
            'user_id' => auth()->id(),
            'product_id' => $product->id,
        ]);
        $cartItem->quantity += $request->quantity;
        if ($cartItem->quantity > $product->stock_quantity) {
            return response()->json([
                'success' => false,
                'message' => 'Cannot add more items than available in stock',
            ], 400);
        }
        $cartItem->save();
    } else {
            $cart = Session::get('cart', []);
            $productId = $product->id;
            if (isset($cart[$productId])) {
                $newQuantity = $cart[$productId]['quantity'] + $request->quantity;
                if ($newQuantity > $product->stock_quantity) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Cannot add more items than available in stock',
                    ], 400);
                }
                $cart[$productId]['quantity'] = $newQuantity;
            } else {
                $cart[$productId] = [
                    'product_id' => $product->id,
                    'quantity' => (int) $request->quantity,
                ];
            }
            Session::put('cart', $cart);
    }

    return response()->json([
        'success' => true,
        'message' => 'Product added to cart!',
    ]);
}

    public function update(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);
        $productId = $request->input('product_id');
        $quantity = $request->input('quantity');
        $currency = session('currency', 'USD');

        if (auth()->check()) {
            $cartItem = CartItem::where('user_id', auth()->id())
                ->where('product_id', $productId)
                ->first();
            if ($cartItem && $quantity > 0) {
                $cartItem->quantity = $quantity;
                $cartItem->save();
            }
        } else {
            $cart = session()->get('cart', []);
            if (isset($cart[$productId]) && $quantity > 0) {
                $cart[$productId]['quantity'] = $quantity;
                session()->put('cart', $cart);
            }
        }

        // Calculate updated subtotal and cart total
        $product = Product::find($productId);
        $subtotal = $product ? $product->getCurrentPrice($currency) * $quantity : 0;

        // Recalculate cart total
        $total = 0;
        if (auth()->check()) {
            $cartItems = CartItem::with('product')
                ->where('user_id', auth()->id())
                ->get();
            foreach ($cartItems as $item) {
                if ($item->product) {
                    $total += $item->product->getCurrentPrice($currency) * $item->quantity;
                }
            }
        } else {
            $cart = session()->get('cart', []);
            foreach ($cart as $item) {
                $product = Product::find($item['product_id']);
                if ($product) {
                    $total += $product->getCurrentPrice($currency) * $item['quantity'];
                }
            }
        }

        if ($request->expectsJson() || $request->ajax()) {
            return response()->json([
                'success' => true,
                'subtotal' => number_format($subtotal, 2),
                'cart_total' => number_format($total, 2),
            ]);
        }

        return redirect()->route('cart.index')->with('success', 'Cart updated successfully.');
    }

    public function remove(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);
        $productId = $request->input('product_id');

        if (auth()->check()) {
            CartItem::where('user_id', auth()->id())
                ->where('product_id', $productId)
                ->delete();
        } else {
            $cart = session()->get('cart', []);
        if (isset($cart[$productId])) {
            unset($cart[$productId]);
            session()->put('cart', $cart);
            }
        }

        return redirect()->route('cart.index')->with('success', 'Product removed from cart.');
    }

    public function clear()
    {
        if (auth()->check()) {
            CartItem::where('user_id', auth()->id())->delete();
        } else {
        Session::forget('cart');
        }

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

    public function count()
    {
        if (auth()->check()) {
            $count = CartItem::where('user_id', auth()->id())->sum('quantity');
        } else {
            $cart = Session::get('cart', []);
            $count = is_array($cart) ? array_sum(array_column($cart, 'quantity')) : 0;
        }
        return response()->json([
            'count' => $count,
        ]);
    }
}
