const PaymentHistory = require('../models/PaymentHistory');

// Create a new payment history
exports.createPaymentHistory = async (req, res) => {
  try {


const {paid,credit,customerId,description}=req.body;
console.log(req.body);
    const newPaymentHistory = new PaymentHistory({paid,credit,customerId,description});
    const savedPaymentHistory = await newPaymentHistory.save();
    res.status(201).json(savedPaymentHistory);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error creating payment history' });
  }
};

// Get all payment history entries
exports.getAllPaymentHistory = async (req, res) => {
  try {
    const paymentHistory = await PaymentHistory.find().populate('customerId'); // Populate customer data
    res.status(200).json(paymentHistory);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error fetching payment history' });
  }
};

// Get a single payment history entry by ID
exports.getPaymentHistoryById = async (req, res) => {
  try {
    const paymentHistory = await PaymentHistory.find({customerId:req.params.id}).populate('customerId').sort({createdAt:-1}); // Populate customer data
    if (!paymentHistory) {
      return res.status(404).json({ message: 'Payment history not found' });
    }
    res.status(200).json(paymentHistory);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error fetching payment history' });
  }
};

// Update a payment history entry
exports.updatePaymentHistory = async (req, res) => {
  try {
    const updatedPaymentHistory = await PaymentHistory.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true } // Return the updated document
    );
    if (!updatedPaymentHistory) {
      return res.status(404).json({ message: 'Payment history not found' });
    }
    res.status(200).json(updatedPaymentHistory);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error updating payment history' });
  }
};

// Delete a payment history entry
exports.deletePaymentHistory = async (req, res) => {
  try {
    const deletedPaymentHistory = await PaymentHistory.findByIdAndDelete(
      req.params.id
    );
    if (!deletedPaymentHistory) {
      return res.status(404).json({ message: 'Payment history not found' });
    }
    res.status(200).json({ message: 'Payment history deleted' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Error deleting payment history' });
  }
};