const Cart = require('../model/Cart'); exports.addToCart = async (req, res) => { const { userId } = req.body; const { productId, quantity } = req.body; try { let cart = await Cart.findOne({ userId }); if (!cart) { cart = new Cart({ userId, items: [{ productId, quantity }], }); } else { const existingItem = cart.items.find(item => item.productId.toString() === productId); if (existingItem) { existingItem.quantity += quantity; } else { cart.items.push({ productId, quantity }); } } await cart.save(); res.json({ message: 'Item added to cart successfully' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }; exports.updateQuantity = async (req, res) => { const { userId, productId, quantity } = req.body; try { let cart = await Cart.findOne({ userId }); if (!cart) { return res.status(404).json({ error: 'Cart not found for the user' }); } const existingItem = cart.items.find(item => item.productId.toString() === productId); if (!existingItem) { return res.status(404).json({ error: 'Product not found in the cart' }); } existingItem.quantity = quantity; await cart.save(); res.json({ message: 'Quantity updated successfully' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }; exports.removeFromCart = async (req, res) => { const { userId, productId } = req.body; try { let cart = await Cart.findOne({ userId }); if (!cart) { return res.status(404).json({ error: 'Cart not found for the user' }); } cart.items = cart.items.filter(item => item.productId.toString() !== productId); await cart.save(); res.json({ message: 'Product removed from cart successfully' }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }; exports.getCartDetails = async (req, res) => { const { userId } = req.body; try { const cart = await Cart.findOne({ userId }).populate('items.productId', 'name price'); if (!cart) { return res.status(404).json({ error: 'Cart not found for the user' }); } // Calculate subtotal for each item const itemsWithSubtotal = cart.items.map(item => ({ ...item.toObject(), subtotal: item.quantity * item.productId.price, })); // Calculate total price for all items const totalPrice = itemsWithSubtotal.reduce((total, item) => total + item.subtotal, 0); res.json({ items: itemsWithSubtotal, totalPrice, }); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } };