const Branch = require('../models/Branch');
const FinancialSummary = require('../models/FinancialSummary');
const mongoose = require('mongoose');
const { getSummary } = require('./autoCalculationController');
const { saveBranchResultsToFinancialSummary } = require('./financialSummaryController');



exports.runSummary = async (req, res) => {
const { companyId, groupId, startDate, endDate,branchId } = req.query;
console.log("comeing her....")
await runDailySalesAggregation(companyId,branchId,startDate,endDate);

res.status(200).json({message:"successfully completed"});
}

exports.getMergedSummary = async (req, res) => {
  const { companyId, groupId, startDate, endDate } = req.query;

let branches;
let allBranchData = [];

  try {
  
    console.log("object id is ",groupId);
// Convert companyId and groupId to ObjectId if they are not already
const companyObjectId = new mongoose.Types.ObjectId(companyId);
const groupObjectId = new mongoose.Types.ObjectId(groupId);



// Query with ObjectId types for companyId and groupId
const branches = await Branch.find({ 
  companyId: companyId, 
groupId: groupId 
});
     console.log("###",branches)
    // Loop over each branch and fetch financial summaries
    for (const branch of branches) {
      const query = {
        companyId: branch.companyId,
        branchId: branch._id
      };

      // Apply date filtering if startDate and endDate are provided
      if (startDate && endDate) {
        query.createdAt = {
          $gte: new Date(new Date(startDate).setUTCHours(0, 0, 0, 0)),  // Start of the day (UTC)
          $lte: new Date(new Date(endDate).setUTCHours(23, 59, 59, 999))  // End of the day (UTC)
        };
      }

      // Fetch financial summary data from the database based on the filters
      const financialSummary = await FinancialSummary.find(query)
      .populate('branchId')
      .sort({createdAt:-1});
    
      //  console.log("finance:",financialSummary)
      // Merge the financial summaries into the allBranchData array
      allBranchData.push(...financialSummary);
    }
  // console.log("all data:",allBranchData);
    // Merge data by `createdAt` and sum up the fields
    const mergedResults = mergeBranchData(allBranchData);

    // Return the merged results to the client
 //console.log("merged Data:",mergedResults);

   res.status(200).json(mergedResults);


  } catch (error) {
    console.error('Error fetching data:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

// Function to merge data by `createdAt` and sum fields
function mergeBranchData(data) {
  const mergedData = {};

  // Iterate over each record and group them by the `createdAt` date
// console.log("main data is",data);

  data.forEach(item => {
    // Extract the date part from `createdAt` (ignore time)
    const date = new Date(item.createdAt).toISOString().split('T')[0];

    const condition1=item.branchId.considerStock; //avaliable stock values
    const condition2=item.branchId.considerSystemSale;//?? not clear reason fro this, better to remove this
    const condition3=item.branchId.considerSystemWithdrawal;// for using
    const condition4=item.branchId.considerSystemWithdrawalForSelling;// for selling or ordering

   // console.log("condotions",condition1,condition2,condition3);
    // If the date already exists, sum up the fields

    if (mergedData[date])
       {
    mergedData[date].stockValue += condition1 ? item.stockValue : 0;

    mergedData[date].totalSales += condition2 ? item.totalSales : 0;

    mergedData[date].totalStoreWithdrawal += condition3 ? item.storeWithdrawal : 0;
    mergedData[date].totalStoreWithdrawalForSelling += condition4 ? item.storeWithdrawalForSelling : 0;
        
      mergedData[date].toDaySale += item.toDaySale;
      mergedData[date].totalPurchases += item.totalPurchases;
      mergedData[date].totalExpense += item.totalExpense;
      mergedData[date].bankDeposit += item.bankDeposit;
      mergedData[date].bankWithdraw += item.bankWithdraw;

  
      mergedData[date].dailyNetProfitUsingSystem += item.dailyNetProfitUsingSystem;
      mergedData[date].dailyNetProfitUsingCashier += item.dailyNetProfitUsingCashier;
      mergedData[date].orderAdvance +=item.orderAdvance;
      mergedData[date].orderRemaining +=item.orderRemaining;
    } else {
      // Initialize the fields if the date doesn't exist
 
      mergedData[date] = {

        stockValue:condition1? item.stockValue:0,
        totalSales: condition2 ? item.totalSales : 0, 
        totalStoreWithdrawal:  condition3 ?item.storeWithdrawal:0,
        totalStoreWithdrawalForSelling:  condition4 ?item.storeWithdrawalForSelling:0,
        toDaySale: item.toDaySale,
        totalPurchases: item.totalPurchases,
        totalExpense: item.totalExpense,
        bankDeposit: item.bankDeposit,
        bankWithdraw: item.bankWithdraw,

        dailyNetProfitUsingSystem: item.dailyNetProfitUsingSystem,
        dailyNetProfitUsingCashier: item.dailyNetProfitUsingCashier,
        orderAdvance:item.orderAdvance,
        orderRemaining:item.orderRemaining
      };
    }
   // add order sales to todaySale
    mergedData[date].totalSales= mergedData[date].totalSales+ 
                                 mergedData[date].orderAdvance+
                                 mergedData[date].orderRemaining

// then make empty for preventing redudent addition because already added to the totalsales
mergedData[date].orderAdvance=0;
mergedData[date].orderRemaining=0;
 
 // combine stock all stock deducted

 mergedData[date].totalStoreWithdrawal= mergedData[date].totalStoreWithdrawal+ mergedData[date].totalStoreWithdrawalForSelling;
 mergedData[date].totalStoreWithdrawalForSelling=0;

                               

});

  // Convert the merged data back into an array for easier manipulation
  return Object.keys(mergedData).map(date => ({
    createdAt: date,
    ...mergedData[date]
  }));
}


async function runDailySalesAggregation(companyId, branchId, startDate, endDate) {
  try {
    // Create a date object for the start date
    let currentDate = new Date(startDate);

   console.log("working starting from ",currentDate)
    while (currentDate <= new Date(endDate)) {
      const date = currentDate.toISOString().split('T')[0]; // Get date in YYYY-MM-DD format
      console.log("working inside loop for date",currentDate)
      // Call the getSummary function and save results
      const branchResults = await getSummary(companyId, branchId, date);
      await saveBranchResultsToFinancialSummary(branchResults,date);

      // Increment the date by one day
      currentDate.setDate(currentDate.getDate() + 1);

      console.log(`Daily sales aggregation completed for ${date}.`);
    }
  } catch (error) {
    console.error('Error during daily sales aggregation:', error);
  }
}

