const salesForm = document.getElementById('sales-form');
const branchSelect = document.getElementById('branch-select');
const salesDateInput = document.getElementById('sales-date');
const totalAmountInput = document.getElementById('total-amount');
const messageDiv = document.getElementById('message');
const todaySalesTbody = document.getElementById('today-sales-tbody');
const allSalesHeader = document.getElementById('all-sales-header');
const allSalesTbody = document.getElementById('all-sales-tbody');
const startDateInput = document.getElementById('start-date');
const endDateInput = document.getElementById('end-date');
const filterSalesBtn = document.getElementById('filter-sales-btn');
const companyId = sessionStorage.getItem('companyId'); // Get company ID from session

// Set the sales date to today by default
const today = new Date().toISOString().split('T')[0];
salesDateInput.value = today;

// Tabs functionality
const tabButtons = document.querySelectorAll('.tab-btn');
const tabContents = document.querySelectorAll('.tab-content');

tabButtons.forEach(button => {
  button.addEventListener('click', () => {
    tabButtons.forEach(btn => btn.classList.remove('active'));
    tabContents.forEach(content => content.classList.remove('active'));
    button.classList.add('active');
    document.getElementById(button.dataset.tab).classList.add('active');
  });
});

// Function to fetch and populate branches based on companyId
function loadBranches() {
  fetch(`/api/branches?companyId=${companyId}`)
    .then(response => response.json())
    .then(data => {
      data.forEach(branch => {
        const option = document.createElement('option');
        option.value = branch._id;
        option.textContent = branch.name;
        branchSelect.appendChild(option);
      });
    })
    .catch(error => console.error('Error loading branches:', error));
}

// Load branches when the page is loaded
loadBranches();

salesDateInput.addEventListener('change', loadTodaySales);

salesDateInput.addEventListener('change',loadTodaySales);

// Handle form submission for saving daily sales
salesForm.addEventListener('submit', function(event) {
event.preventDefault();

const branchId = branchSelect.value;
const salesDate = salesDateInput.value;
const totalAmount = totalAmountInput.value;

if (!branchId || !salesDate || !totalAmount) {
alert('Please fill in all fields.');
return;
}

// Prepare sales data to send
const salesData = {
companyId,
branchId,
salesDate,
totalAmount
};

fetch('/api/sales', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(salesData)
})
.then(response => response.json())
.then(data => {
if (data.success) {
messageDiv.textContent = data.message;
messageDiv.style.display = 'block';
messageDiv.style.color = 'green';
loadTodaySales(); // Reload today's sales after saving
} else {
messageDiv.textContent = data.message;
messageDiv.style.display = 'block';
messageDiv.style.color = 'red';
}
})
.catch(error => {
console.error('Error saving sales:', error);
messageDiv.textContent = 'Error saving sales.';
messageDiv.style.display = 'block';
messageDiv.style.color = 'red';
});
});



// Function to fetch and display today's sales for the current company
function loadTodaySales() {
 
  const day = new Date(salesDateInput.value).toISOString().split('T')[0];
  fetch(`/api/sales/today?companyId=${companyId}&salesDate=${day}`)
    .then(response => response.json())
    .then(data => {
      todaySalesTbody.innerHTML = ''; // Clear previous records
   
      data.forEach(sale => {
        const row = `
          <tr>
            <td>${sale.branchId.name}</td>
            <td>${new Date(sale.salesDate).toLocaleDateString()}</td>
            <td>${sale.totalAmount}</td>
          </tr>
        `;
        todaySalesTbody.innerHTML += row;
        console.log("rr",todaySalesTbody)
      });
    })
    .catch(error => console.error('Error loading today\'s sales:', error));
}
// Function to load sales data grouped by branch
function loadSalesData(startDate, endDate) {
  fetch(`/api/sales/All?companyId=${companyId}&startDate=${startDate}&endDate=${endDate}`)
    .then(response => response.json())
    .then(data => {




      // Validate the response structure
      if (!data || !data.headers || !data.rows) {
        console.error('Invalid data format:', data);
        return;
      }
  
      // Extract headers and rows
      const headers = data.headers; // Includes 'Date' and branch names
      const rows = data.rows;
  
      // Prepare table header
      const headerRowHTML = `<tr>${headers.map(header => `<th>${header}</th>`).join('')}</tr>`;
      document.getElementById('all-sales-header').innerHTML = headerRowHTML;
  
      // Prepare table body
      const bodyHTML = rows.map(row => {
        return `
          <tr>
            ${headers.map(header => `<td>${row[header] || 'No Data'}</td>`).join('')}
          </tr>
        `;
      }).join('');
      document.getElementById('all-sales-tbody').innerHTML = bodyHTML;




      // const branches = data.map(branchGroup => branchGroup.branchName); // Get branch names
      // const maxRows = Math.max(...data.map(branchGroup => branchGroup.sales.length)); // Get the max number of sales rows across all branches

      // // Create headers: "Date" + "Amount [Branch]"
      // allSalesHeader.innerHTML = ''; // Clear previous headers
      // const headerRow = document.createElement('tr');
      // const dateHeader = document.createElement('th');
      // dateHeader.textContent = 'Date';
      // headerRow.appendChild(dateHeader);

      // // Add header columns for each branch
      // branches.forEach(branch => {
      //   const branchHeader = document.createElement('th');
      //   branchHeader.textContent = `Amount [${branch}]`;
      //   headerRow.appendChild(branchHeader);
      // });

      // allSalesHeader.appendChild(headerRow);

      // // Populate sales data in rows
      // allSalesTbody.innerHTML = ''; // Clear previous rows
      // for (let row = 0; row < maxRows; row++) {
      //   const tr = document.createElement('tr');
      //   const dateCell = document.createElement('td');
      //   const salesForDate = data.map(branchGroup => branchGroup.sales[row]);

      //   // Find the date for the row from any existing sale
      //   const validSale = salesForDate.find(sale => sale !== undefined);
      //   if (validSale) {
      //     dateCell.textContent = new Date(validSale.salesDate).toLocaleDateString();
      //   } else {
      //     dateCell.textContent = 'No Data';
      //   }
      //   tr.appendChild(dateCell);

      //   // Fill sales amount for each branch
      //   data.forEach(branchGroup => {
      //     const sale = branchGroup.sales[row]; // Get the sale for this branch in this row
      //     const td = document.createElement('td');
      //     if (sale) {
      //       td.textContent = `$${sale.totalAmount}`;
      //     } else {
      //       td.textContent = 'No Sales'; // If no sale for this branch
      //     }
      //     tr.appendChild(td);
      //   });

        // allSalesTbody.appendChild(tr);
     // }








    })
    .catch(error => console.error('Error loading sales data:', error));
}

// Function to handle sales data filtering
filterSalesBtn.addEventListener('click', function () {
  const startDate = startDateInput.value;
  const endDate = endDateInput.value;

  if (!startDate || !endDate) {
    alert('Please select both start and end dates.');
    return;
  }

  // Fetch and load sales data for the selected date range
  loadSalesData(startDate, endDate);
});

// Load default sales data for the current month on page load
const to_day = new Date();
const defaultStartDate = new Date(to_day.getFullYear(), to_day.getMonth(), 1).toISOString().split('T')[0]; // First day of the month
const defaultEndDate = new Date(to_day.getFullYear(), to_day.getMonth() + 1, 0).toISOString().split('T')[0]; // Last day of the month

startDateInput.value = defaultStartDate;
endDateInput.value = defaultEndDate;
loadSalesData(defaultStartDate, defaultEndDate);

// Load today's sales on page load
loadTodaySales();
