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

exports.getTransactionReport = async (req, res) => {
  try {
    const { startDate, endDate, branchId, transactionType, companyId } = req.query;

    // Build query filters
    const query = {};
    if (startDate && endDate) {
      query.date = { $gte: new Date(startDate), $lte: new Date(endDate) };
    }
    if (branchId) {
      query.branch = branchId;
    }
    if (companyId) {
      query.companyId = companyId;  // Filter by company
    }
    if (transactionType) {
      query.transactionType = transactionType;
    }

    // Fetch transactions based on filters
    const transactions = await Transaction.find(query)
      .populate('items')
      .populate('company')
      .populate('branch');

    // Aggregate totals
    const totalSales = transactions
      .filter(txn => txn.transactionType === 'selling')
      .reduce((acc, txn) => acc + txn.total, 0);

    const totalPurchases = transactions
      .filter(txn => txn.transactionType === 'purchasing')
      .reduce((acc, txn) => acc + txn.total, 0);

    const totalProfit = transactions
      .filter(txn => txn.transactionType === 'selling')
      .reduce((acc, txn) => acc + txn.items.reduce((profit, item) => profit + item.profit, 0), 0);

    // Return the report data
    res.json({
      totalSales,
      totalPurchases,
      totalProfit,
      transactions
    });
  } catch (error) {
    console.error('Error generating report:', error);
    res.status(500).json({ message: 'Server error' });
  }
};
