const Payment = require('../models/sales');

exports.addsales = async (req, res) => {
  try {
    const { paymentDate, amount, studentId } = req.body;
    const newPayment = await Payment.create({
      paymentDate,
      amount,
      student_FK: studentId,
    });
    res.status(201).json({ msg: 'Payment added successfully', data: newPayment });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to add payment', error: error.message });
  }
};

exports.getsales = async (req, res) => {
  try {
    const getPayments = await Payment.find().populate('student_FK');
    res.status(200).json(getPayments);
  } catch (error) {
    res.status(404).json({ msg: 'Payments not found' });
  }
};

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

exports.updatesales = async (req, res) => {
  try {
    const { paymentDate, amount, studentId } = req.body;
    const updateData = {
      paymentDate,
      amount,
      student_FK: studentId,
    };
    const updatePayment = await Payment.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    ).populate('student_FK');
    if (!updatePayment) return res.status(404).json({ msg: 'Payment not found' });
    res.status(200).json(updatePayment);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to update', error: error.message });
  }
};

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

    if (!deletePayment) return res.status(404).json({ msg: 'Payment not found' });

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