const User = require("../model/User") exports.createOrder = async (req, res) => { try { const { userId, products, totalAmount } = req.body const user = await User.findById(userId) if (!user) { return res.status(404).json({ message: "User not found" }) } // Check if the user is an admin if (user.isAdmin) { return res .status(403) .json({ message: "Admins cannot create orders" }) } const newOrder = { products: products, totalAmount: totalAmount, purchaseOn: Date.now(), } user.orderedProducts.push(newOrder) await user.save() res.status(201).json({ message: "Order created successfully", order: newOrder, }) } catch (error) { console.error(error) res.status(500).json({ message: "Internal Server Error" }) } } // Retrieve authenticated user's orders exports.getOrders = async (req, res) => { try { const { userId } = req.body const user = await User.findById(userId) if (!user) { return res.status(404).json({ message: "User not found" }) } // Return the user details in the response res.send({ orderedProducts: user.orderedProducts }) } catch (error) { console.error(error) res.status(500).json({ message: "Internal server error" }) } } exports.getAllOrders = async (req, res) => { try { const orders = await User.find({ "orderedProducts.0": { $exists: true } }, "orderedProducts"); res.status(200).json({ success: true, data: orders }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } };