// Define variables
const hamburger = document.querySelector('.hamburger');
const sidebar = document.querySelector('.sidebar');
const navbar = document.querySelector('.navbar');
const container_main = document.querySelector('.container_main');
const footer = document.querySelector('.footer');
// Add event listener to hamburger icon
hamburger.addEventListener('click', () => {
  sidebar.classList.toggle('active');
  navbar.classList.toggle('active');   
  container_main.classList.toggle('active'); 
  footer.classList.toggle('active');
});

// jQuery document ready function to initialize Bootstrap Selectpicker
$(document).ready(function(){
  $('#clientUid').selectpicker();
});

// Add event listener to body for change event
document.body.addEventListener('change', function(event) {
  if (event.target.matches('.category')) {
    var categoryId = event.target.value;
    var url = 'fetch_products.php?category=' + categoryId;

    // Use AJAX to fetch products
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var productDropdown = event.target.parentNode.nextElementSibling.querySelector('.product');
        if (productDropdown) {
          productDropdown.innerHTML = xhr.responseText;
        }
      }
    };
    xhr.open('GET', url, true);
    xhr.send();
  }

  if (event.target.matches('.product')) {
    var productId = event.target.value;
    var url = 'fetch_variation.php?product=' + productId;

    // Use AJAX to fetch variations
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var variationDropdown = event.target.parentNode.nextElementSibling.querySelector('.variation');
        if (variationDropdown) {
          variationDropdown.innerHTML = xhr.responseText;
        }
      }
    };
    xhr.open('GET', url, true);
    xhr.send();
  }
});

// jQuery document ready function for change event on variation select
$(document).ready(function() {
  $(document).on('change', '.variation', function() {
    var variation = $(this).val();
    var parentContainer = $(this).closest('.box_button');
    var productElement = parentContainer.find('.product_id');
    var priceElement = parentContainer.find('.price');
    var stockElement = parentContainer.find('.Instock');

    // Use AJAX to fetch variation details
    $.ajax({
      url: 'fetch_variation_details.php',
      method: 'POST',
      data: { variation: variation },
      dataType: 'json',
      success: function(response) {
        console.log("Response:", response); // Log the entire response object
        console.log("Product ID:", response.product_id); // Log the product ID

        // Check if the product_id input field exists
        if (productElement.length > 0) {
          // Set the value of the product_id input field
          productElement.val(response.product_id);
        } else {
          console.error("Product ID input field not found.");
        }

        // Set other values if needed
        priceElement.val(response.price);
        stockElement.val(response.quantity);
      },
      error: function(xhr, status, error) {
        console.error("AJAX Error:", error);
        alert('An error occurred while processing your request.');
      }
    });
  });
});

// Function to update total amount
function updateTotalAmount() {
  console.log("Updating total amount");
  var totalAmount = 0;

  // Calculate for dynamically added fields
  $('.box_button').each(function () {
    var priceInput = parseFloat($(this).find('.price').val().replace(/[^\d.]/g, '')) || 0;
    var quantityInput = parseFloat($(this).find('.quantity').val()) || 0;
    totalAmount += priceInput * quantityInput;
  });

  console.log("Total amount: " + totalAmount.toFixed(2));
  $('#totalAmount').val("Rs " + totalAmount.toFixed(2)); // Prepend "Rs" to total amount
}

// Call the function inside the document ready block
$(document).ready(function() {
  console.log("Document ready");
  updateTotalAmount(); // Calculate total amount initially

  // Attach change event listeners to input fields
  $(document).on('change', '.box_button input', function() {
    console.log("Input changed");
    updateTotalAmount(); // Call the function whenever any input changes
  });
});

// Event listener for "Add More" button
document.getElementById("addMore").addEventListener("click", function() {
  console.log("Add more clicked");
  var originalBox = document.getElementById("boxButton");
  var cloneBox = originalBox.cloneNode(true); // Clone the box_button div

  // Clear the values of input fields in the cloned div
  var inputs = cloneBox.querySelectorAll("input");
  inputs.forEach(function(input) {
    input.value = ""; // Clear the input value
  });

  // Update the cloned price field to avoid confusion
  var priceElement = cloneBox.querySelector('.price');
  if (priceElement) {
    priceElement.value = ""; // Clear the price value
  }

  // Create a Remove button
  var removeButton = document.createElement("button");
  removeButton.type = "button";
  removeButton.textContent = "Remove";
  removeButton.className = "removeButton btn btn-danger centered-button";
  removeButton.style.display = "block";
  removeButton.style.margin = "0 auto";
  removeButton.style.textAlign = "center"; // Center the button text

  removeButton.addEventListener("click", function() {
    cloneBox.parentNode.removeChild(cloneBox); // Remove the cloned div
    updateTotalAmount(); // Update total amount after removing
  });

  // Append the Remove button to the cloned div
  cloneBox.appendChild(removeButton);

  // Append the cloned div to the clonedContainer
  document.getElementById("clonedContainer").appendChild(cloneBox);
  updateTotalAmount(); // Update total amount after adding
});





// FETCH DATA OF _ARRIVAL_STORE_


document.addEventListener('DOMContentLoaded', function() { 
document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.category_one')) {
        var categoryId = event.target.value;
        var url = 'fetch_raw_product.php?category=' + categoryId;
    
        // Use AJAX to fetch products
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var nextElementSibling = event.target.parentNode.nextElementSibling;
                if (nextElementSibling && nextElementSibling.querySelector) {
                    // Instead of parsing JSON, just set innerHTML
                    nextElementSibling.querySelector('.product_one').innerHTML = xhr.responseText;
                }
            }
        };
        xhr.open('GET', url, true);
        xhr.send();
    }
});

var productSelect = document.getElementById('product_one');
var variationSelect = document.getElementById('variation_one');

// Add event listener to product select
  document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.product_one')) {
        var productId = event.target.value;
        var url = 'fetch_raw_variations.php?product=' + productId;
    
        // Use AJAX to fetch variations
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var nextElementSibling = event.target.parentNode.nextElementSibling;
                if (nextElementSibling && nextElementSibling.querySelector) {
                    nextElementSibling.querySelector('.variation_one').innerHTML = xhr.responseText;
                }
            }
        };
        xhr.open('GET', url, true);
        xhr.send();
    }
});

document.body.addEventListener('change', function(event) {
    if (event.target && event.target.matches('.variation_one')) {
        var variation = event.target.value;

        // Find the product_id and price_one elements by their IDs
        var productIdElement = document.getElementById('product_id');
        var priceElement = document.getElementById('price_one');

        $.ajax({
            url: 'fetch_raw_price.php',
            method: 'POST',
            data: { variation: variation },
            dataType: 'json',
            success: function(response) {
                console.log(response);

                if (response.success) {
                    var price = response.price;
                    var productId = response.product_id;

                    // Update price input field
                  if (priceElement) {
                        priceElement.value = 'Rs ' + price + '/';
                    } else {
                        console.error('Price element not found');
                    }
                    
                    // Update product ID input field
                    if (productIdElement) {
                        productIdElement.value = response.product_id;
                    } else {
                        console.error('Product ID element not found');
                    }
                } else {
                    console.error("Error:", response.error);
                    alert('An error occurred while fetching price.');
                }
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert('An error occurred while fetching price.');
            }
        });
    }
});
});


function moveToOrderCancel(orderid) {
    if (confirm('Are you sure you want to cancel this order?')) {
        // Send AJAX request to PHP script
        $.ajax({
            type: 'POST',
            url: 'order_cancel.php',
            data: { order_id: orderid }, // Corrected key name to match PHP
            success: function(response) {
                alert(response);
                // Reload the page or update the UI as needed
                location.reload(); // Reload the page after successful move
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                alert('An error occurred while moving the order to cancel.');
            }
        });
    }
}

document.querySelector(".or").onclick = function() {
            myFunction();
        };

        function myFunction() {
            var elements = document.querySelectorAll(".pd_id");
            elements.forEach(function(element) {
                element.classList.toggle("show");
            });
        }
        
        
$(document).ready(function() {
    var monthVisitInput = $('#month-visit');
    
    // Check if the element is found
    if (monthVisitInput.length > 0) {
        monthVisitInput.change(function() {
            var selectedMonth = $(this).val();

            $.ajax({
                url: 'fetch_monthly_data.php',
                method: 'POST',
                data: { selectedMonth: selectedMonth },
                dataType: 'json',
                success: function(response) {
                    console.log("Monthly Data Response:", response); // Log the response to console
                    
                    // Clear existing table data
                    $('.table tbody').empty();

                    // Loop through the fetched data and append rows to the table
                    $.each(response, function(index, item) {
                        var newRow = '<tr>' +
                            '<td>' + item.category + '</td>' +
                            '<td>' + item.product + '</td>' +
                            '<td>' + item.variation + '</td>' +
                            '<td>' + item.price + '</td>' +
                            '<td>' + item.quantity + '</td>' +
                            '<td>' + item.total_amount + '</td>' +
                            '</tr>';
                        $('.table tbody').append(newRow);
                    });

                    // Calculate and display total sales
                    var totalSales = response.reduce(function(total, item) {
                        return total + parseFloat(item.total_amount);
                    }, 0);
                    $('.table tbody').append('<tr><td colspan="5" style="text-align: right;"><strong>Total Sales:</strong></td><td>Rs ' + totalSales.toFixed(2) + '</td></tr>');

                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                    alert('An error occurred while fetching data for the selected month.');
                }
            });
        });
    } else {
        console.error('Element with ID "month-visit" not found.');
    }
});
