const Sales = require('../models/DailySales');

// Create or update daily sales
exports.createOrUpdateSales = async (req, res) => {
  try {
    const {companyId, branchId, salesDate, totalAmount } = req.body;


 
    // Normalize the salesDate by setting time to 00:00:00
    const normalizedSalesDate = new Date(salesDate);
    normalizedSalesDate.setUTCHours(0, 0, 0, 0);

    // Check if a record already exists for the given branchId and salesDate
    const existingRecord = await Sales.findOne({ branchId, salesDate: normalizedSalesDate });

    if (existingRecord) {
      // If the record exists, update it
      existingRecord.totalAmount = totalAmount;
      existingRecord.updatedAt = Date.now();
      await existingRecord.save();
      
      return res.status(200).json({ success: true, message: 'Sales record updated successfully!', sales: existingRecord });
    }

    // If no record exists, create a new one
    const newSales = new Sales({
        companyId,
      branchId,
      salesDate: normalizedSalesDate,  // Save the normalized date
      totalAmount,
    });

    await newSales.save();
    //update summary 
     const { runSummarySaving } = require('./autorun.js');
    runSummarySaving();

    res.status(201).json({ success: true, message: 'Sales record Saved successfully!', sales: newSales });

  } catch (error) {
    console.error('Error creating/updating sales record:', error);

    // Handle duplicate key error (E11000) for uniqueness violation
    if (error.code === 11000) {
      res.status(400).json({ message: 'Sales record already exists for this date and branch.' });
    } else {
      res.status(500).json({ message: 'Failed to create or update sales record', error });
    }
  }
};


// Controller to get today's sales for a company
exports.getTodaySales = async (req, res) => {
    try {
      const { companyId, salesDate } = req.query;
  
// Normalize the salesDate by setting time to 00:00:00
const normalizedSalesDate = new Date(salesDate);
normalizedSalesDate.setUTCHours(0, 0, 0, 0);

      // Fetch today's sales for the specified company
      const todaySales = await Sales.find({companyId,salesDate: normalizedSalesDate  }).populate('branchId', 'name');
 
      res.status(200).json(todaySales);
    } catch (error) {
      console.error('Error fetching today\'s sales:', error);
      res.status(500).json({ message: 'Error fetching today\'s sales' });
    }
  };









// Controller to get all sales within a date range for a company, grouped by branch
exports.getAllSales = async (req, res) => {
  try {
    const { companyId, startDate, endDate } = req.query;

    // Normalize the startDate and endDate by setting time to 00:00:00
    const normalizedStartDate = new Date(startDate);
    normalizedStartDate.setUTCHours(0, 0, 0, 0);

    const normalizedEndDate = new Date(endDate);
    normalizedEndDate.setUTCHours(23, 59, 59, 999); // Include the entire day

    // Fetch sales for the specified company within the date range
    // const sales = await Sales.find({
    //   companyId,
    //   salesDate: {
    //     $gte: normalizedStartDate,
    //     $lte: normalizedEndDate
    //   }
    // }).populate('branchId', 'name').sort({createdAt:-1});

    // // Group sales by branchId


    // console.log("sales are",sales);


    // const salesByBranch = sales.reduce((acc, sale) => {

    //   const branchId = sale.branchId?._id ?? 'Deleted Branch';


    //   if (!acc[branchId]) {
    //     acc[branchId] = {
    //       branchId: sale.branchId?._id ?? 'DEleted Branch',
    //       branchName: sale.branchId?.name ?? 'Unknown',
    //       sales: []
    //     };
    //   }
    //   acc[branchId].sales.push(sale);
    //   return acc;
    // }, {});

    // // Convert the result into an array of grouped sales
    // const groupedSales = Object.values(salesByBranch);

    // console.log("data",groupedSales);

    const sales = await Sales.find({
      companyId,
      salesDate: {
        $gte: new Date(startDate),
        $lte: new Date(endDate)
      }
    })
      .populate('branchId', 'name')
      .sort({ salesDate: -1 });

    // Organize data into rows (dates) and columns (branches)
    const groupedData = {};
    const branchNames = new Set();

    // Group data by date and branch
    sales.forEach(entry => {
      const date = entry.salesDate.toISOString().split('T')[0];
      const branchName = entry.branchId?.name || 'Unknown Branch';

      branchNames.add(branchName); // Collect all branch names

      if (!groupedData[date]) {
        groupedData[date] = {};
      }
      groupedData[date][branchName] = entry.totalAmount;
    });

    // Create table structure
    const response = {
      headers: ['Date', ...Array.from(branchNames)],
      rows: []
    };

    // Loop through dates and format data for each branch
    for (const date in groupedData) {
      const row = { Date: date };

      response.headers.slice(1).forEach(branch => {
        row[branch] = groupedData[date][branch] || 'No Data';
      });

      response.rows.push(row);
    }

    res.json(response);







  //  res.status(200).json(groupedSales);
  } catch (error) {
    console.error('Error fetching sales:', error);
    res.status(500).json({ message: 'Error fetching sales' });
  }
};


// Function to get today's sales for a company
exports.get_TodaySales = async (companyId, branchId,start,end) => {
  try {
    // Normalize the salesDate by setting the time to 00:00:00
    const startDate= new Date(start);
    const endDate= new Date(end);
    startDate.setUTCHours(0, 0, 0, 0);
    endDate.setUTCHours(23, 59, 59, 59);

    // Fetch today's sales for the specified company
    const todaySalesFind = await Sales.find({
      companyId: (companyId), // Important: Convert to ObjectId
      branchId: (branchId), // Important: Convert to ObjectId
      salesDate: {
          $gte: new Date(startDate),
          $lte: new Date(endDate)
      }
  });
  let totalSalesValueFind = 0;
  todaySalesFind.forEach(sale=>{
      totalSalesValueFind+=sale.totalAmount
  })
  console.log("Total Sales Amount find:", totalSalesValueFind);
    
    //.populate('branchId', 'name'); // Populating branchId with branch name



    if (totalSalesValueFind)
       {
       return totalSalesValueFind; // or return todaySales, based on what you need
    } else {
     // console.log('No sales found for today.');
      return 0; // Return null or handle as appropriate
    }


  } catch (error) {
    console.error('Error fetching today\'s sales:', error);
    throw error; // Rethrow the error for the caller to handle
  }
};

// module.exports = { get_TodaySales };