const FinancialSummary = require('../models/FinancialSummary'); // Adjust the path to your model
const { getSummary } = require('./autoCalculationController');
const {get_Total_Summary}= require('./getTotalSummaryController');
const mongoose = require('mongoose'); // Import mongoose
const Branch=require('../models/Branch');
const BranchInventory=require('../models/BranchInventory')

exports.saveBranchResultsToFinancialSummary = async (branchResults,currentDate) => {
  try {
 
 
 let date=currentDate|| new Date();
 
    // Get the current date and set it to the start of the day (00:00:00)
    const todayStart = new Date(date);
    todayStart.setUTCHours(0, 0, 0, 0);

    const todayEnd = new Date(date);
    todayEnd.setUTCHours(23, 59, 59, 999); // End of the day

    // Iterate through each branch result and save or update it in the FinancialSummary collection
    for (const branch of branchResults) {
      const {
        branchId,
        companyId,
        totalBranchSum, // This will be the stockValue for this branch
        totalSummary
      } = branch;

      const {
        totalSales = 0,      // Set to 0 if totalSales is undefined or null
        totalPurchases = 0,   // Set to 0 if totalPurchases is undefined or null
        totalExpense = 0,     // Set to 0 if totalExpense is undefined or null
        bankDeposit = 0,      // Set to 0 if bankDeposit is undefined or null
        bankWithdraw = 0  ,
        toDaySale=0 ,   // 
        totalStoreWithdrawal=0,
        totalStoreWithdrawalForSelling=0,
        dailyNetProfitUsingSystem=0,
        dailyNetProfitUsingCashier=0,
        orderAdvance=0,
        orderRemaining=0,
        cash=0,
        bank=0,
        credit=0,
        other=0,

      } = totalSummary ?? {}; // Ensure totalSummary is an object to avoid errors
//console.log("sorewithdrwa is:",totalStoreWithdrawal);
      // Check if a record already exists for the branchId, companyId, and today's date
      const existingSummary = await FinancialSummary.findOne({
        branchId,
        companyId,
        createdAt: { $gte: todayStart, $lte: todayEnd } // Check for today’s date
      });

      if (existingSummary) {
        // If the record exists, update it
        existingSummary.stockValue = totalBranchSum;
        existingSummary.totalSales = totalSales;
        existingSummary.storeWithdrawal = totalStoreWithdrawal;
        existingSummary.storeWithdrawalForSelling = totalStoreWithdrawalForSelling;
        existingSummary.totalPurchases = totalPurchases;
        existingSummary.totalExpense = totalExpense;
        existingSummary.bankDeposit = bankDeposit;
        existingSummary.bankWithdraw = bankWithdraw;
        existingSummary.toDaySale = toDaySale;
        existingSummary. dailyNetProfitUsingSystem=  dailyNetProfitUsingSystem;
        existingSummary.dailyNetProfitUsingCashier= dailyNetProfitUsingCashier;
        existingSummary.orderAdvance = orderAdvance;

        existingSummary.orderRemaining = orderRemaining;

        existingSummary.cash = cash;          // New addition
        existingSummary.bank = bank;          // New addition
        existingSummary.credit = credit;      // New addition
        existingSummary.other = other;        // New addition
        // Save the updated entry
        await existingSummary.save();
        console.log(`Financial summary updated for branch ${branchId} on ${todayStart.toDateString()}.`);
      } else {
        // If no record exists, create a new entry
        const financialSummary = new FinancialSummary({
          companyId,
          branchId,
          stockValue: totalBranchSum, // Using totalBranchSum as stockValue
          totalSales,  
          storeWithdrawal: totalStoreWithdrawal,  
          storeWithdrawalForSelling: totalStoreWithdrawalForSelling,               // Use actual value or 0 if undefined
          totalPurchases,             // Use actual value or 0 if undefined
          totalExpense,               // Use actual value or 0 if undefined
          bankDeposit,                // Use actual value or 0 if undefined
          bankWithdraw,               // Use actual value or 0 if undefined
          toDaySale,
          dailyNetProfitUsingSystem,
          dailyNetProfitUsingCashier,
          orderAdvance, // all advance made in today(that day)
          orderRemaining,
          cash,        // New addition
          bank,        // New addition
          credit,      // New addition
          other,  
          createdAt:date  ,   // 
updatedAt:date
        });

        // Save the new entry to the database
        await financialSummary.save();
        console.log(`Financial summary saved for branch ${branchId} on ${todayStart.toDateString()}.`);
      }
    }

    console.log('Branch results successfully saved/updated in FinancialSummary collection.');
  } catch (error) {
    console.error('Error saving or updating branch results in FinancialSummary:', error);
    throw error;
  }
};





exports.getAllBranchSummary = async (req, res) => {
  try {
   
   
    // Extract companyId, branchId, startDate, and endDate from the query parameters sent by the frontend
      const { companyId, startDate, endDate } = req.query;



      const allBranchSummary=[];
      const branches = await Branch.find({  
       companyId: companyId  
    
    });
    for (const branch of branches) {

  const dailySummary=await get_Total_Summary(companyId, branch._id,startDate,endDate );

  
  let branchInventory = 0;
    const inventory = await BranchInventory.find({ branchId:branch._id }).populate('itemId');
  
        // Calculate total sum for the branch
       
        inventory.forEach(item => {
          
          const avgPrice=item.itemId?.avg_price||0;
           branchInventory += item.quantity *avgPrice;
        });
  





  allBranchSummary.push({branchName:branch.name,branchInventory:branchInventory,data:dailySummary})
  }

   // Return the financial summary data as a JSON response
    res.status(200).json(allBranchSummary);
  } catch (error) {
    console.error('Error fetching financial summary:', error);
    res.status(500).json({ message: 'Server error while fetching financial summary.' });
  }
};




// Controller to get financial summary data based on companyId, branchId, startDate, and endDate
exports.getDailySummary = async (req, res) => {
  try {
   
   
    // Extract companyId, branchId, startDate, and endDate from the query parameters sent by the frontend
    const { companyId, branchId, startDate, endDate } = req.query;






  const dailySummary=await get_Total_Summary(companyId, branchId);

  console.log("daily summary is",dailySummary);
    // Return the financial summary data as a JSON response
    res.status(200).json(dailySummary);
  } catch (error) {
    console.error('Error fetching financial summary:', error);
    res.status(500).json({ message: 'Server error while fetching financial summary.' });
  }
};


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

      console.log("Raw company:", req.query.companyId);
      console.log("Raw branch:", req.query.branchId);

      let start, end;

      if (startDate && endDate) {
          start = new Date(startDate);
          end = new Date(endDate);

          // Set to UTC midnight and end of day
          start.setUTCHours(0, 0, 0, 0);
          end.setUTCHours(23, 59, 59, 999);

          console.log("Parsed Start Date (UTC):", start);
          console.log("Parsed End Date (UTC):", end);


      } else {
          return res.status(400).json({ message: "Both startDate and endDate are required." });
      }

      const fSummary = await FinancialSummary.find({
        companyId: new mongoose.Types.ObjectId(companyId), // Convert to ObjectId
        branchId: new mongoose.Types.ObjectId(branchId), // Convert to ObjectId
        createdAt: { $gte: start, $lte: end }
    }).sort({createdAt:-1});

      console.log("f summary", fSummary);
      res.status(200).json(fSummary);
  } catch (error) {
      console.error('Error fetching financial summary:', error);
      res.status(500).json({ message: 'Server error while fetching financial summary.' });
  }
};

async function runDailySalesAggregation(companyId,branchId) {
 
  try {
    const branchResults = await getSummary(companyId,branchId);
    await exports.saveBranchResultsToFinancialSummary(branchResults);
    console.log('Daily sales aggregation completed.');
  } catch (error) {
    console.error('Error during daily sales aggregation:', error);
  }
}
