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

exports.getproduct = async (req, res) => {
  try {
    const students = await Student.find();
    if (!students) {
      return res.status(404).json({ message: 'Students not found' });
    }
    res.json(students);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getproductbyid = async (req, res) => {
  try {
    const studentById = await Student.findById(req.params.id);
    if (!studentById) {
      return res.status(404).json({ message: 'Student not found' });
    }
    res.json(studentById);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.addproduct = async (req, res) => {
  try {
    const { studentId, fullName, classGrade, parentName, parentPhone } = req.body;
    const newStudent = await Student.create({
      studentId,
      fullName,
      classGrade,
      parentName,
      parentPhone,
    });

    res.status(201).json(newStudent);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.updateproduct = async (req, res) => {
  try {
    const updateStudent = await Student.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );
    if (!updateStudent) return res.status(404).json({ msg: 'Student not found' });

    res.json({ msg: 'Student updated successfully', data: updateStudent });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.deleteproduct = async (req, res) => {
  try {
    const deleteStudent = await Student.findByIdAndDelete(req.params.id);
    if (!deleteStudent) {
      return res.status(404).json({ message: 'Student not found' });
    }
    res.json({ message: 'Student deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getstats = async (req, res) => {
  try {
    const studentCount = await Student.countDocuments();
    const payments = await Payment.find();
    const paymentCount = payments.length;
    const totalPaid = payments.reduce(
      (sum, payment) => sum + parseFloat(payment.amount || 0),
      0
    );

    res.json({ studentCount, paymentCount, totalPaid });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
