const router = require('express').Router();
const Invoice = require('../models/Invoice');
const { auth } = require('../middleware/auth');

router.get('/', auth, async (req, res) => {
  try {
    const inv = await Invoice.find().sort({ createdAt: -1 }).populate('customer_id', 'name email').populate('trip_id', 'trip_code');
    res.json(inv);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/stats', auth, async (req, res) => {
  try {
    const total = await Invoice.countDocuments();
    const paid = await Invoice.countDocuments({ status: 'paid' });
    const overdue = await Invoice.countDocuments({ status: 'overdue' });
    const agg = await Invoice.aggregate([{
      $group: { _id: null, total_amount: { $sum: '$total_amount' }, paid_amount: { $sum: { $cond: [{ $eq: ['$status', 'paid'] }, '$total_amount', 0] } } }
    }]);
    res.json({ total, paid, overdue, ...(agg[0] || { total_amount: 0, paid_amount: 0 }) });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.get('/:id', auth, async (req, res) => {
  try {
    const inv = await Invoice.findById(req.params.id).populate('customer_id').populate('trip_id');
    if (!inv) return res.status(404).json({ message: 'Invoice not found' });
    res.json(inv);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.post('/', auth, async (req, res) => {
  try {
    const inv = await Invoice.create(req.body);
    res.status(201).json(inv);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.put('/:id', auth, async (req, res) => {
  try {
    const inv = await Invoice.findByIdAndUpdate(req.params.id, req.body, { new: true });
    res.json(inv);
  } catch (err) { res.status(500).json({ message: err.message }); }
});

router.delete('/:id', auth, async (req, res) => {
  try {
    await Invoice.findByIdAndDelete(req.params.id);
    res.json({ message: 'Deleted successfully' });
  } catch (err) { res.status(500).json({ message: err.message }); }
});

module.exports = router;
