const MonthlyExpense = require('../models/MonthlyExpense');
const mongoose = require('mongoose');
// Create or Update a monthly expense
exports.createOrUpdateMonthlyExpense = async (req, res) => {
    try {
      const { companyId, branchId, rent, salaries, utilities, tax, otherExpenses } = req.body;
  
      // Check if an expense already exists for the given companyId and branchId
      let existingExpense = await MonthlyExpense.findOne({ companyId, branchId });
  
      if (existingExpense) {
        // If the record exists, update the existing expense
        existingExpense.rent = rent || existingExpense.rent;
        existingExpense.salaries = salaries || existingExpense.salaries;
        existingExpense.utilities = utilities || existingExpense.utilities;
        existingExpense.tax = tax || existingExpense.tax;
        existingExpense.otherExpenses = otherExpenses || existingExpense.otherExpenses;
  
        // Save the updated expense
        const updatedExpense = await existingExpense.save();
        return res.status(200).json(updatedExpense);  // Return the updated record
      } else {
        // If no record exists, create a new one
        const newExpense = new MonthlyExpense({
          companyId,
          branchId,
          rent,
          salaries,
          utilities,
          tax,
          otherExpenses
        });
  
        // Save the new expense to the database
        const savedExpense = await newExpense.save();
 //update summary 
 const { runSummarySaving } = require('./autorun.js');
 runSummarySaving();


        return res.status(201).json(savedExpense);  // Return the new record
      }
    } catch (error) {
      console.error('Error creating or updating monthly expense:', error);
      res.status(500).json({ message: 'Server error while creating or updating monthly expense.' });
    }
  };
  

  exports.getMonthlyAllBranchExpenses = async (req, res) => {
    try {
      const { companyId, branchId } = req.query;
  
      // Build query object for filtering
      const query = {};
    
      // Ensure ObjectId type for companyId and branchId, if provided
      if (companyId) query.companyId = new mongoose.Types.ObjectId(companyId);
    
     
      // Fetch monthly expenses based on the query
      const expenses = await MonthlyExpense.find(query);
   
     
      res.status(200).json(expenses);
    } catch (error) {
      console.error('Error fetching monthly expenses:', error.message);
      res.status(500).json({ message: 'Server error while fetching expenses.' });
    }
  };

// Get all monthly expenses or filter by companyId and branchId
exports.getMonthlyExpenses = async (req, res) => {
  try {

    const { companyId, branchId } = req.query;
    const query = {};
      // Ensure ObjectId type for companyId and branchId, if provided
  
    if (companyId) query.companyId = new mongoose.Types.ObjectId(companyId);
   
    if (branchId) query.branchId = new mongoose.Types.ObjectId(branchId);

   
    
    // Fetch monthly expenses based on the query
    const expenses = await MonthlyExpense.findOne(query);
  
   
    res.status(200).json(expenses);
  } catch (error) {
    console.error('Error fetching monthly expenses:', error.message);
    res.status(500).json({ message: 'Server error while fetching expenses.' });
  }
};



// Delete a monthly expense by ID
exports.deleteMonthlyExpense = async (req, res) => {
  try {
    const deletedExpense = await MonthlyExpense.findByIdAndDelete(req.params.id);

    if (!deletedExpense) {
      return res.status(404).json({ message: 'Expense not found.' });
    }

    res.status(200).json({ message: 'Expense deleted successfully.' });
  } catch (error) {
    console.error('Error deleting expense:', error);
    res.status(500).json({ message: 'Server error while deleting expense.' });
  }
};




// Get all monthly expenses or filter by companyId and branchId
exports.get_MonthlyExpenses = async (companyId, branchId) => {
  try {
    // Build query object for filtering
    const query = {};

    // Ensure ObjectId type for companyId and branchId, if provided
    if (companyId) query.companyId = new mongoose.Types.ObjectId(companyId);
    if (branchId) query.branchId = new mongoose.Types.ObjectId(branchId);

    // Fetch monthly expenses based on the query
    const expenses = await MonthlyExpense.findOne(query);

    if (!expenses) {
      console.log('No expenses found.');
      return null;  // Handle this appropriately in the calling function
    }
   // console.log('expenses found is',expenses);
    // Calculate expense per day (assuming 30 days in the month)
    const expensePerDay = expenses.totalExpense / 30;
   // console.log('expen per day',expensePerDay);
    return expensePerDay; // Return the calculated value
  } catch (error) {
    console.error('Error fetching monthly expenses:', error.message);
    throw new Error('Server error while fetching expenses.');
  }
};

  