// document.addEventListener('DOMContentLoaded', () => {

  
    const transactionsTable = document.getElementById('transactions-table').querySelector('tbody');
    const transactionDetailsModal = document.getElementById('transaction-details-modal');
    const transactionDetailsTable = document.getElementById('transaction-details-table').querySelector('tbody');
    const closeModal = transactionDetailsModal.querySelector('.close');
    const closeBtn = document.getElementsByClassName('close')[0];
//    const companyName = sessionStorage.getItem('companyName');
//    const branchName = sessionStorage.getItem('branchName');
   const companyId = sessionStorage.getItem('companyId');
   const branchId = sessionStorage.getItem('branchId');

    


    const startDateFilter = document.getElementById('start-date-filter');
    const endDateFilter = document.getElementById('end-date-filter');
  
    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];
      startDateFilter.value = today;
      endDateFilter.value = today;
      loadTransactions(); // Trigger filter
    }
  
    // Set date inputs to yesterday
    function setYesterday() {
      const yesterday = new Date(new Date().setDate(new Date().getDate() - 1))
        .toISOString()
        .split('T')[0];
      startDateFilter.value = yesterday;
      endDateFilter.value = yesterday;
      loadTransactions(); // Trigger filter
    }
  // 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];
  
    // Set the start date and end date filters
    startDateFilter.value = formattedMonday;
    endDateFilter.value = formattedToday;
  
    // Trigger the filter function
    loadTransactions(); 
  }
  
    // Event Listeners for buttons
    todayButton.addEventListener('click', setToday);
    yesterdayButton.addEventListener('click', setYesterday);
    weekButton.addEventListener('click', setWeek);





    // Load transactions based on filters
    function loadTransactions() {
        const startDate = document.getElementById('start-date-filter').value;
        const endDate = document.getElementById('end-date-filter').value;
        const type = document.getElementById('transaction-type-filter').value;

        // Fetch transactions based on date range, type, and branchId
        fetch(`/api/transactions?startDate=${startDate}&endDate=${endDate}&transactionType=${type}&companyId=${companyId}&branchId=${branchId}`)
            .then(response => response.json())
            .then(data => {
                transactionsTable.innerHTML = ''; // Clear current table rows

                data.forEach(transaction => {
                    const row = document.createElement('tr');

                    row.innerHTML = `
                        <td>${new Date(transaction.createdAt).toLocaleDateString()}</td>
                        <td>${transaction.transactionType}</td>
                        <td>${transaction.totalItems.toFixed(2)}</td>
                        <td>${transaction.subtotal}</td>
                        <td>Walking</td> 
                        <td>
                            <button onclick="viewDetails('${transaction._id}')">View Details</button>
                            <button onclick="deleteTransaction('${transaction._id}', '${transaction.transactionType}')">Delete</button>
                        </td>
                    `;

                    transactionsTable.appendChild(row);
                });
            })
            .catch(error => console.error('Error loading transactions:', error));
    }

    // Event listener for date and type change
    document.getElementById('start-date-filter').addEventListener('change', loadTransactions);
    document.getElementById('end-date-filter').addEventListener('change', loadTransactions);
    document.getElementById('transaction-type-filter').addEventListener('change', loadTransactions);

    // View transaction details in modal
    window.viewDetails = function (transactionId) {
       
        const startDate = document.getElementById('start-date-filter').value;
        const endDate = document.getElementById('end-date-filter').value;
        const type = document.getElementById('transaction-type-filter').value;


        fetch(`/api/transactions/${transactionId}/tr_details`)

            .then(response => response.json())
            .then(data => {
                transactionDetailsTable.innerHTML = ''; // Clear current details



// Loop through each detail and add them to the table
data.forEach(detail => {




    const row = document.createElement('tr');

    // Add `data-*` attributes for transactionId, itemId, and branchId
row.dataset._id = detail._id;
row.dataset.transactionId = detail.transactionId;
row.dataset.itemId = detail.itemId;
row.dataset.branchId = detail.branchId;
row.dataset.transactionType = detail.transactionType;
    // Create row with non-editable fields
    row.innerHTML = `
        <td>${detail.name}</td>
        <td><input type="number" value="${detail.quantity.toFixed(2)}" class="quantity-field" disabled></td>
        <td><input type="number" value="${detail.price.toFixed(2)}" class="price-field" disabled></td>
        <td class="total-cell">$${detail.total.toFixed(2)}</td>
        <td>
            <button class="action-btn edit-btn">Edit</button>
            <button class="action-btn delete-btn">Delete</button>
        </td>
    `;

    transactionDetailsTable.appendChild(row);

    // Get references to quantity and price fields
    const quantityField = row.querySelector('.quantity-field');
    const priceField = row.querySelector('.price-field');
    const totalCell = row.querySelector('.total-cell');

    // Function to update the total in real-time
    function updateTotal() {
        const quantity = parseFloat(quantityField.value);
        const price = parseFloat(priceField.value);
        const newTotal = (quantity * price).toFixed(2);
        totalCell.textContent = `$${newTotal}`;
    }

    // Add event listeners to quantity and price fields to update the total in real-time
    quantityField.addEventListener('input', updateTotal);
    priceField.addEventListener('input', updateTotal);

    // Add click event listener for the "Edit" button
 
    row.querySelector('.edit-btn').addEventListener('click', async (e) => {
        e.preventDefault();
        
        const quantityField = row.querySelector('.quantity-field');
        const priceField = row.querySelector('.price-field');
    
        // Store previous values in row's dataset when Edit is clicked
        if (quantityField.disabled) {
            row.dataset.previousQuantity = quantityField.value;
            row.dataset.previousPrice = priceField.value;
        }
    
        // Toggle editing mode
        quantityField.disabled = !quantityField.disabled;
        priceField.disabled = !priceField.disabled;
    
        // Change button text between "Edit" and "Save"
        const editBtn = row.querySelector('.edit-btn');
        editBtn.textContent = quantityField.disabled ? "Edit" : "Save";
    
        // If the button text is "Save", it means editing is enabled
        if (editBtn.textContent === "Save") {
            // If the button is now in "Save" mode, exit the function to allow editing
            return;
        }
    
        // If the button text was changed back to "Edit", it means user wants to save changes
        // Retrieve updated values
        const updatedQuantity = parseInt(quantityField.value);
        const updatedPrice = parseFloat(priceField.value);
        const previousQuantity = parseInt(row.dataset.previousQuantity);
        const previousPrice = parseFloat(row.dataset.previousPrice);
        const transactionId = row.dataset.transactionId;
        const itemId = row.dataset.itemId;
        const branchId = row.dataset.branchId;
        const _id = row.dataset._id;
        const transactionType=row.dataset.transactionType;
        // Send a PUT request to the backend with the updated values
        try {
            const response = await fetch(`/api/transaction/update`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    _id,
                    transactionId,
                    itemId,
                    branchId,
                    updatedQuantity,
                    updatedPrice,
                    previousQuantity,
                    previousPrice,
                    transactionType
                })
            });
    
            const result = await response.json();
    
            if (response.ok) {
                alert('Transaction details updated successfully!');
                // Optionally, update any other UI elements if needed
            } else {
                alert('Error updating transaction: ' + result.message);
                // Revert the changes if error occurred
                quantityField.value = previousQuantity;
                priceField.value = previousPrice;
            }
        } catch (error) {
            console.error('Error updating transaction:', error);
            alert('An error occurred while updating the transaction.');
        }
    });
    
    // Add click event listener for the "Delete" button
  
// Event listener for deleting
row.querySelector('.delete-btn').addEventListener('click', (e) => {
    e.preventDefault();

    const _id = row.dataset._id;
    const transactionType=row.dataset.transactionType;
   
    
    // Call the delete function
    deleteOneTransaction(_id, transactionType);
  });

    
});


                

                // data.forEach(detail => {
                //     const row = document.createElement('tr');
                //     row.innerHTML = `
                //         <td>${detail.name}</td>
                //         <td>${detail.quantity}</td>
                //         <td>$${detail.price.toFixed(2)}</td>
                //         <td>$${detail.total.toFixed(2)}</td>
                //         <td>
                //             <button class="action-btn edit-btn">Edit</button>
                //             <button class="action-btn delete-btn">Delete</button>
                //         </td>
                //     `;
                //     transactionDetailsTable.appendChild(row);
                // });

                // Show the modal
                transactionDetailsModal.style.display = 'block';
            })
            .catch(error => console.error('Error loading transaction details:', error));
    };

    // Close the modal
    closeModal.addEventListener('click', () => {
        transactionDetailsModal.style.display = 'none';
    });

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



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


  

    // Close the modal when clicking outside
    window.onclick = function (event) {
        if (event.target === transactionDetailsModal) {
            transactionDetailsModal.style.display = 'none';
        }
    };

    setToday() // set date by default to today and load
   // loadTransactions();

    // Set default date in the date filter to today
    const today = new Date().toISOString().slice(0, 10);
    document.getElementById('start-date-filter').value = today;
    document.getElementById('end-date-filter').value = today;
// });
