document.addEventListener('DOMContentLoaded', () => {
  const customerForm = document.getElementById('customer-form');
  const customerTable = document.getElementById('customer-list1').getElementsByTagName('tbody')[0];
  const companyId = sessionStorage.getItem('companyId');
 let customers;
  const openTab = (event, tabName) => {
    const tabContents = document.getElementsByClassName('tab-content');
    for (let i = 0; i < tabContents.length; i++) {
      tabContents[i].style.display = 'none';
    }

    const tabButtons = document.getElementsByClassName('tab-btn');
    for (let i = 0; i < tabButtons.length; i++) {
      tabButtons[i].classList.remove('active');
    }

    document.getElementById(tabName).style.display = 'block';
    event.currentTarget.classList.add('active');
  };

  document.getElementById('tab-btn-add-customer').addEventListener('click', (e) => {
    openTab(e, 'customer-form-tab');
  });

  document.getElementById('tab-btn-customer-list').addEventListener('click', (e) => {
    openTab(e, 'customer-list-tab');
  });

  const fetchCustomers = async () => {
    try {
      const response = await fetch(`/api/customers/List?companyId=${companyId}`);
       customers = await response.json();

      customerTable.innerHTML = ''; // Clear table body

      customers.forEach(customer => {
        const row = customerTable.insertRow();
        const nameCell = row.insertCell();
        const typeCell = row.insertCell();
        const phoneCell = row.insertCell();
        const statusCell = row.insertCell();
        const actionsCell = row.insertCell();

        nameCell.textContent = customer.name;
        typeCell.textContent = customer.customerType;
        phoneCell.textContent = customer.phone;
        statusCell.textContent = customer.status;
        actionsCell.innerHTML = ` <div class="row">
          <button onclick="editCustomer('${customer._id}')">Edit</button>
          <button style="background-color:#f63434;" onclick="deleteCustomer('${customer._id}')">Delete</button></div>
        `;
      });
    } catch (err) {
      console.error('Error fetching customers:', err);
    }
  };







  window.editCustomer =async (customerId) => {
  
    const customer = customers.find(c => c._id === customerId); 
    console.log("customer is",customer);
    if (!customer) {
        console.error("Customer not found for editing:", customerId);
        alert("Customer not found.");
        return;
    }

    document.getElementById('name').value = customer.name;
    document.getElementById('type').value = customer.customerType;
    document.getElementById('phone').value = customer.phone;
    document.getElementById('status').value = customer.status;

    const submitButton = document.querySelector('#customer-form button[type="submit"]');
    submitButton.textContent = 'Update Customer';
    submitButton.dataset.editingId = customerId;

    const addTabButton = document.getElementById('tab-btn-add-customer');
    addTabButton.click();
};

customerForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = document.getElementById('name').value;
    const type = document.getElementById('type').value;
    const phone = document.getElementById('phone').value;
    const status = document.getElementById('status').value;

    const submitButton = e.target.querySelector('button[type="submit"]');
    const editingId = submitButton.dataset.editingId;

    try {
        let response;
        if (editingId) { // If editing an existing customer
            response = await fetch(`/api/customers/${editingId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, customerType: type, phone, status, companyId })
            });
            delete submitButton.dataset.editingId; // Clean up the data attribute
            submitButton.textContent = 'Add Customer'; // Reset button text
        } else { // If creating a new customer
            response = await fetch('/api/customers', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name, customerType: type, phone, status, companyId })
            });
        }

        if (response.ok) {
            alert(editingId ? "Customer updated successfully!" : "Customer created successfully!");
            customerForm.reset();
                      
            fetchCustomers();
        } else {
            const errorData = await response.json();
            alert(errorData.message || (editingId ? "Failed to update customer." : "Failed to create customer."));
        }
    } catch (error) {
        console.error('Error:', error);
        alert("An error occurred. Please check the console.");
    }
});








  fetchCustomers(); // Initial fetch
});