


import permissionUtils from "./common.js";
import { TRANSACTIONS_DETAIL } from "./frontEndPermission.js";

  const transactionsTable = document.getElementById('transactions-table').querySelector('tbody');
  const searchInput = document.getElementById('item-name-filter'); // For real-time search by item name
  const transactionTypeFilter = document.getElementById('transaction-type-filter');
  const startDateSelect= document.getElementById('start-date');
  const endDateSelect = document.getElementById('end-date');

  let transactionData = {};
   
  let activeTransactionId='';
let prv_total=0;
let new_total=0;
let new_subtotal=0;
let prv_subtotal=0;
let updatedPaymentDetail= {};
 const updateDetailBtn = document.getElementById('update-detail-btn');

 // Add click event listener
  updateDetailBtn.addEventListener('click', updateDetail);

//   const companyName=sessionStorage.getItem('companyName');
// const branchName=sessionStorage.getItem('branchName');
const companyId=sessionStorage.getItem('companyId');
const branchId=sessionStorage.getItem('branchId');

transactionTypeFilter.value="selling"; // intially set to selling by default

  let allTransactionDetails = []; // Store all transaction details locally



  // Add event listeners to handle changes
startDateSelect.addEventListener('change', loadTransactionDetails);
endDateSelect.addEventListener('change', loadTransactionDetails);
transactionTypeFilter.addEventListener('change', loadTransactionDetails);



const todayButton = document.getElementById('today-btn');
const yesterdayButton = document.getElementById('yesterday-btn');
const weekButton = document.getElementById('week-btn');





// Set date inputs to today
function setToday() {
  const today = new Date().toISOString().split('T')[0];
  startDateSelect.value = today;
  endDateSelect.value = today;
  loadTransactionDetails(); // Trigger filter
}

// Set date inputs to yesterday
function setYesterday() {
  const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
    .toISOString()
    .split('T')[0];
  startDateSelect.value = yesterday;
  endDateSelect.value = yesterday;
  loadTransactionDetails();
}
// starting from monday

function setWeek() {
 
const today = new Date();
const currentDayOfWeek = today.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday

// Find the most recent Monday: subtract (currentDayOfWeek - 1) days, handle Sunday as 0
const offsetToMonday = currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1;
const monday = new Date(today);
monday.setDate(today.getDate() - offsetToMonday);

// Format the dates as 'YYYY-MM-DD'
const formattedMonday = monday.toISOString().split('T')[0];
const formattedToday = today.toISOString().split('T')[0];


startDateSelect.value =  formattedMonday;
endDateSelect.value =formattedToday;
// Trigger the filter function

loadTransactionDetails();
}

// Event Listeners for buttons
todayButton.addEventListener('click', setToday);
yesterdayButton.addEventListener('click', setYesterday);
weekButton.addEventListener('click', setWeek);











  // Load all transaction details once
       
        function loadTransactionDetails() {  
          const dateFrom=startDateSelect.value;
          const dateTo= endDateSelect.value;
         const transactionType=transactionTypeFilter.value;

          const url = `api/transactions/tr_details?branchId=${branchId}&startDate=${dateFrom}&endDate=${dateTo}&transactionType=${transactionType}`;
   
          // Fetch the data from the backend with the provided date range
      

    fetch(url)
      .then(response => response.json())
      .then(data => {
        allTransactionDetails = data; // Store all details locally
      
        displayTransactionDetails(allTransactionDetails); // Display all initially
      })
      .catch(error => console.error('Error loading transaction details:', error));
  }

 






  // Display transactions based on provided data
  function displayTransactionDetails(details) {
   
    // handleTransactionTypeChange(transactionTypeFilter.value)
let  totalProfit=0;
let totalSales=0;

    transactionsTable.innerHTML = ''; // Clear table before populating
    details.forEach(detail => {

      //let veiw_delete_button=false; //
      let veiw_edit_button=false;
      totalProfit += (detail.profit)*(detail.quantity);
    //  totalItems += detail.quantity;
      totalSales += (detail.price * detail.quantity); //
  
      const row = document.createElement('tr');
      let rowContent = `
    <td>${new Date(detail.createdAt).toISOString().split('T')[0]}</td>
    <td>${detail.name}</td>
    <td>${detail.quantity}</td>
    <td>${detail.price.toFixed(0)}</td>
    <td>${detail.total.toFixed(0)}</td>
    <td class="profit-column">${(detail.profit * detail.quantity).toFixed(0)}</td>
    <td class="row">
`;

if (permissionUtils.hasPermission(userPermissions, TRANSACTIONS_DETAIL.VIEW_EDIT_TRANSACTIONS_BUTTON)) {
    veiw_edit_button=true;
  rowContent += `<button class="edit-btn">Edit</button>`;
  
}

if (permissionUtils.hasPermission(userPermissions, TRANSACTIONS_DETAIL.VIEW_DELETE_TRANSACTIONS_BUTTON)) {
    rowContent += `<button class="delete-btn" onclick="deleteDetail('${detail._id}', '${detail.transactionType}')">Delete</button>`;
//veiw_delete_button=true;
  }

rowContent += `</td>`;

row.innerHTML = rowContent;

      // esssss   shall be view  <button class="edit-btn hidden"
      transactionsTable.appendChild(row);

    
    
      if(veiw_edit_button){
      row.querySelector('.edit-btn').addEventListener('click', () => {
           
            openEditModal(detail.transactionType,detail._id, detail.quantity, detail.price,detail.name,detail.itemId,detail.transactionId);
          });
      
        }



    }     );

    totalProfit = totalProfit.toFixed(2); 
    totalSales = totalSales.toFixed(2); // total sales or total purchase . they are the same because price hold both purchasing ande selling price

// // Display in HTML
document.getElementById('total-sales').textContent = `$${totalSales}`;
document.getElementById('total-purchases').textContent =`$${totalSales}`;
document.getElementById('total-profit').textContent = `$${totalProfit}`;
updateSummaryVisibility();

  }



  // Real-time search by item name
  searchInput.addEventListener('input', () => {
    const searchValue = searchInput.value.toLowerCase();
   
    // Filter locally based on item name
    const filteredDetails = allTransactionDetails.filter(detail =>
      detail.name.toLowerCase().includes(searchValue)
    );
   
    displayTransactionDetails(filteredDetails); // Display filtered results
  });

 

    // Filter transactions locally
    const filteredDetails = allTransactionDetails.filter(detail => {
      let isMatch = true;
      if (filters.dateFrom && new Date(detail.date) < new Date(filters.dateFrom)) {
        isMatch = false;
      }
      if (filters.dateTo && new Date(detail.date) > new Date(filters.dateTo)) {
        isMatch = false;
      }
      if (filters.branch && detail.branch !== filters.branch) {
        isMatch = false;
      }
      return isMatch;
    });

  //   displayTransactionDetails(filteredDetails);
  // });


  function updateSummaryVisibility() {
    const transactionType = document.getElementById('transaction-type-filter').value;
  
    if (transactionType === 'selling') {
      // Show Total Sales and Total Profit, hide Total Purchases
      hideProfitColumn(false)
      showHideSummaryBoxes(true, false, true);
      updateNaming("selling")
    } else if (transactionType === 'purchasing') {
      // Show Total Purchases, hide Total Sales and Total Profit
      showHideSummaryBoxes(false, true, false);
      hideProfitColumn(true)
      updateNaming("purchasing")
    }
      else if (transactionType === 'using') {
        // Show Total Purchases, hide Total Sales and Total Profit
        showHideSummaryBoxes(true, false, false);
        hideProfitColumn(true)
        updateNaming("using")

    } 
    else if (transactionType === 'producing') {
      // Show Total Purchases, hide Total Sales and Total Profit
      showHideSummaryBoxes(false, true, false);
      hideProfitColumn(true)
      updateNaming("producing")
  }
    
    
    else {
      // Hide all if no valid selection
      showHideSummaryBoxes(false, false, false);
    }
  }


// Function to update Total Sales and Total Purchases dynamically
function updateNaming(type) {
  // Update Total Sales text and value
  const totalSalesSpan = document.querySelector('.total-sales'); // Span for Total Sales
  const totalPurchasesSpan = document.querySelector('.total-purchases'); // Span for Total Purchases
  if(type==='selling')
  {
  totalSalesSpan.textContent = `Total Sold`; // Add dynamic text if needed
     }
  else if(type==='purchasing')
  {
    totalPurchasesSpan.textContent = `Total Purchased`; // Add dynamic text if needed


  }
  else if(type==='producing')
    {
      totalPurchasesSpan.textContent = `Total Produced`; // Add dynamic text if needed
  
  
    }
  else if(type==='using')
    {
      totalSalesSpan.textContent = `Total Used`; // Add dynamic text if needed
  }
}






  function hideProfitColumn(hideOrNot){

    const table = document.getElementById('transactions-table'); // Replace with your table's ID or class selector
   
  if (hideOrNot) {
   table.querySelectorAll('th:nth-child(6), td:nth-child(6)').forEach((cell) => {
      cell.style.display = 'none';
    });
  }

  else{
    table.querySelectorAll('th:nth-child(6), td:nth-child(6)').forEach((cell) => {
      cell.style.display = 'yes';
    });

  }
}

//console.log("permissions are",user.permission)

  function showHideSummaryBoxes(salesVisible, purchasesVisible, profitVisible) {
    const totalSalesBox = document.getElementById('total-sales-box');
    const totalPurchasesBox = document.getElementById('total-purchases-box');
    const totalProfitBox = document.getElementById('total-profit-box');
    
    // Toggle visibility for sales
    if (salesVisible) {

      if (permissionUtils.hasPermission(userPermissions,TRANSACTIONS_DETAIL. VIEW_TRANSACTIONS_TOTAL)) {
   
      totalSalesBox.style.display = 'block';
      }
   
    } else {
      totalSalesBox.style.display = 'none';
    }
  
    // Toggle visibility for purchases
    if (purchasesVisible) {
      totalPurchasesBox.style.display = 'block';
    } else {
      totalPurchasesBox.style.display = 'none';
    }
  
    // Toggle visibility for profit
    if (profitVisible) {

     if (permissionUtils.hasPermission(userPermissions,TRANSACTIONS_DETAIL.VIEW_TRANSACTIONS_PROFIT)) {
       console.log("you have permissin to vewi this")
        totalProfitBox.style.display = 'block';
     
     }

    //  else
   //   {
       // console.log("you are not allowed")
       // totalProfitBox.style.display = 'none';
    //  }





    } else {
      totalProfitBox.style.display = 'none';
    }
  }
  
  






// Function to open the edit modal with pre-filled data
// function editDetail(detailId) {
// activeTransactionId='';
//   fetch(`/api/transactionDetails/${detailId}`)
//     .then(response => response.json())
//     .then(detail => {
//       // Open the modal and pre-fill data fields
//       const editModal = document.getElementById('edit-modal');
//       document.getElementById('edit-item-name').value = detail.name;
//       document.getElementById('edit-quantity').value = detail.quantity;
//       document.getElementById('edit-price').value = detail.price;
//       document.getElementById('edit-total').value = detail.total;
    
     
//       document.getElementById('edit-detail-id').value = detail._id; // Store the detailId for updating
//       activeTransactionId=detail.transactionId;
//       prv_total= detail.total;
//       // Show the modal
//       editModal.style.display = 'block';
//     })
//     .catch(error => console.error('Error fetching transaction detail for editing:', error));
// }






function calculateNewSubTotal() {

      const diff=new_total-prv_total;

     new_subtotal= prv_subtotal+diff;

  document.getElementById("editCash").value = new_subtotal

  document.getElementById("editBank").value =  0;
  document.getElementById("editCredit").value = 0;
  document.getElementById("editOther").value =  0;
  document.getElementById("editDescription").value = "";
 
}


// Handle edit form submission
document.getElementById("editPaymentForm").addEventListener("submit", function (e) {
  e.preventDefault();




});





// Function to update detail
function getTransactionSubTotal() {


  fetch(`/api/transaction/one?transactionId=${activeTransactionId}`)
    .then(response => response.json())
    .then(data => {

      prv_subtotal=data.subtotal;
      new_subtotal=data.subtotal;// at intial it holds this.

  document.getElementById("editCash").value =  data.paymentId.cash;// get this as default
  document.getElementById("editBank").value =  data.paymentId.bank;
  document.getElementById("editCredit").value = data.paymentId.credit;
  document.getElementById("editOther").value =  data.paymentId.other;
  document.getElementById("editDescription").value =  data.paymentId.description;
 
    }).catch(error => console.error('Error fetching transaction detail for editing:', error));


  }


  function updateDetail(){


  const detailId = document.getElementById('edit-detail-id').value; // Get the stored detailId


  updatedPaymentDetail = {
    cash: parseFloat(document.getElementById("editCash").value) || 0,
    bank: parseFloat(document.getElementById("editBank").value) || 0,
    credit: parseFloat(document.getElementById("editCredit").value) || 0,
    other: parseFloat(document.getElementById("editOther").value) || 0,
    description: document.getElementById("editDescription").value.trim() || "",
  };




// Construct the updated detail object
const updatedDetail = {
  updatedQuantity: parseFloat(document.getElementById('edit-quantity').value) || 0, // Ensure numeric fallback
  updatedPrice: parseFloat(document.getElementById('edit-price').value) || 0, // Ensure numeric fallback
  total: parseFloat(document.getElementById('edit-total').value) || 0, // Ensure numeric fallback
  previousQuantity: transactionData.previousQuantity || 0, // Ensure fallback
  itemId: transactionData.itemId || '', // Ensure fallback
  transactionId: transactionData.transactionId || '', // Ensure fallback
  transactionType: transactionData.transactionType || '', // Ensure fallback
  branchId,
  _id: detailId || '', // Ensure fallback
  updatedPaymentDetail 
};


  fetch(`/api/transaction/update`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updatedDetail)
  })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('Transaction detail updated successfully');
        document.getElementById('edit-modal').style.display = 'none'; // Close the modal
        loadTransactionDetails(); // Reload transaction details
      } else {
        alert('Failed to update transaction detail');
      }
    })
    .catch(error => console.error('Error updating transaction detail:', error));
}


//document.querySelector('.close').addEventListener('click', closeEditModal);
// Select all elements with the 'close' class and add click listener
document.querySelectorAll('.close').forEach(button => {
  button.addEventListener('click', closeEditModal);
});

// Function to close the edit modal
function closeEditModal() {
 
  document.getElementById('edit-modal').style.display = 'none';
}
// Assign the function to the window object to make it global
window.deleteDetail = function(detailId,transactionType) {


  if (confirm('Are you sure you want to delete this transaction?')) {
    fetch(`/api/transactions/one/${detailId}?transactionType=${transactionType}`, { method: 'DELETE' })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Transaction deleted successfully');
                loadTransactionDetails() ;// Reload transactions
            } else {
                alert('Failed to delete transaction');
            }
        })
        .catch(error => console.error('Error deleting transaction:', error));
}


}









// Calculate total automatically when quantity or price changes

document.getElementById('edit-quantity').addEventListener('input', calculateTotal);

document.getElementById('edit-price').addEventListener('input', calculateTotal);



function calculateTotal() {
const quantity = parseFloat(document.getElementById('edit-quantity').value) || 0;
const price = parseFloat(document.getElementById('edit-price').value) || 0;
document.getElementById('edit-total').value = (quantity * price).toFixed(2);
new_total=(quantity * price).toFixed(2);

calculateNewSubTotal();
}


const cashField = document.getElementById("editCash");
const bankField = document.getElementById("editBank");
const creditField = document.getElementById("editCredit");
const otherField = document.getElementById("editOther");

// To store previous valid values
const previousValues = {
  bank: parseFloat(bankField.value) || 0,
  credit: parseFloat(creditField.value) || 0,
  other: parseFloat(otherField.value) || 0,
};

// Function to recalculate the cash field dynamically
function recalculateCash() {
  const bank = parseFloat(bankField.value) || 0;
  const credit = parseFloat(creditField.value) || 0;
  const other = parseFloat(otherField.value) || 0;

  // Calculate the current total
  const currentTotal = bank + credit + other;

  if (currentTotal > new_subtotal) {
    // If total exceeds 100, reject the change and revert to previous value
    alert(`Total cannot exceed ${new_subtotal}. Reverting to previous value.`);
    bankField.value = previousValues.bank;
    creditField.value = previousValues.credit;
    otherField.value = previousValues.other;
  } else {
    // Update the previous values
    previousValues.bank = bank;
    previousValues.credit = credit;
    previousValues.other = other;
  console.log("new toatal",new_subtotal);
    // Calculate remaining cash
    const cash = new_subtotal- currentTotal;
    cashField.value = cash;
  }
}

// Attach event listeners to all fields except cash
[bankField, creditField, otherField].forEach((field) => {
  field.addEventListener("input", recalculateCash);
});



// Get the close button element
const closePaymentModal = document.getElementById("closePaymentModal");
closePaymentModal.addEventListener("click", closeEditPaymentModal);
// Function to close the modal
function closeEditPaymentModal() {
  const modal = document.getElementById("editPaymentModal");
  modal.style.display = "none";
}






function openEditModal(type,detailId, quantity, price,name,item_Id,transaction_id) {

  transactionData.itemId=item_Id; // preparing for later use
  transactionData.previousQuantity=quantity;
  transactionData.transactionId=transaction_id;
  transactionData.transactionType=type;


  // Populate the modal fields with the transaction detail data
  document.getElementById('edit-item-name').value =name;
  document.getElementById('edit-detail-id').value = detailId;
  document.getElementById('edit-quantity').value = quantity;
  document.getElementById('edit-price').value = price;

  activeTransactionId= transaction_id;
  prv_total=(quantity * price).toFixed(2);


  getTransactionSubTotal();
  // Calculate total and display
  document.getElementById('edit-total').value = (quantity * price).toFixed(2);


  // Display the modal
  const modal = document.getElementById('edit-modal');
  modal.style.display = 'block';
}



// Optionally, close the modal when clicking outside of it
window.onclick = function(event) {
  const modal = document.getElementById('edit-modal');
  if (event.target == modal) {
    modal.style.display = 'none';
  }
};

transactionTypeFilter.addEventListener('change', () => {
  loadTransactionDetails();

  // Hide profit section and total profit if transaction type is 'purchasing'
  const profitColumns = document.querySelectorAll('.profit-column'); // Select profit columns
  const totalProfitSection = document.getElementById('total-profit'); // Total profit element

  if (transactionTypeFilter.value === 'purchasing') {
    profitColumns.forEach(column => column.style.display = 'none'); // Hide profit columns
    totalProfitSection.parentElement.style.display = 'none'; // Hide total profit section
  } else {
    profitColumns.forEach(column => column.style.display = 'table-cell'); // Show profit columns
    totalProfitSection.parentElement.style.display = 'block'; // Show total profit section
  }
});




//

const showModalBtn = document.getElementById('show-modal');
const modal = document.getElementById('common-modal');
 const closeBtn = document.getElementById('close-btn');

// Show the modal when the button is clicked
showModalBtn.addEventListener('click', function () {
 
  modal.style.display = 'flex'; // Change display from none to flex to show modal
});


closeBtn.addEventListener('click', function () {
 
  modal.style.display = 'none'; // Change display from none to flex to show modal
});
//
// Hide modal when clicking outside the modal content
window.addEventListener('click', function (e) {
  if (e.target === modal) {
    modal.style.display = 'none'; // Hide modal by setting display to none
  }
});



showHideSummaryBoxes(true,false,true)// intially set for selling visibility


 function  initializeTransactionList()
  {

    loadTransactionDetails();
  }
  initializeTransactionList();
// });

// Function to open a specific tab
window.openTab=function (event, tabId) {
  const tabContents = document.querySelectorAll(".tab-content");
  const tabLinks = document.querySelectorAll(".tab-link");

  // Hide all tabs and remove active class
  tabContents.forEach((tab) => tab.classList.remove("active"));
  tabLinks.forEach((link) => link.classList.remove("active"));

  // Show the selected tab and mark button active
  document.getElementById(tabId).classList.add("active");
  event.currentTarget.classList.add("active");
}


