const Sales = require('../models/sales')

exports.addsales = async (req, res) => {
    try {
        const { salesDate, quantitySold, totalAmount, paymentStatus } = req.body
        const newsales = await Sales.create({
            salesDate,
            quantitySold,
            totalAmount,
            paymentStatus,
            product_FK:req.params.id
        })
        res.status(201).json({ msg: "Sales Added Successfully" })

    } catch (error) {
        res.status(500).json({ msg: "Failed to add sales" ,error: error.message })
    }
}

exports.getsales = async (req, res) => {
    try {
       const getsales= await Sales.find().populate('product_FK')
        res.status(200).json(getsales)
    } catch (error) {
        res.status(404).json({ msg: "Sales not found" })
    }

}

exports.getsalesbyid = async (req, res) => {
    try {
        const getsalesbyid= await Sales.findById(req.params.id).populate('product_FK')
         if (!getsalesbyid) {
            return res.status(404).json({
                msg: "Sale not found"
            });
        }
        res.status(200).json(getsalesbyid)
    } catch (error){
        res.status(404).json({ msg: "Failed to fetch" })
    }
}

exports.updatesales = async (req, res) => {
    try {
       const updatesales= await Sales.findByIdAndUpdate(
            req.params.id,
            req.body,
            { new: true }
        )
   if(!updatesales)return res.status(404).json({ msg: "Sale not found" });
        res.status(200).json(updatesales)
    } catch (error) {
        res.status(500).json({ msg: "Failed  to Update",error: error.message })
    }
}

exports.deletesales = async (req, res) => {
    try {
        const deletesales=await Sales.findByIdAndDelete(req.params.id)

        if (!deletesales) return res.status(404).json({ msg: "Sale not found" });

        res.status(200).json({ msg: "Successful" })
    } catch (error) {
        res.status(500).json({ msg: "Failed to delete",error: error.message })

    }

}