//document.addEventListener('DOMContentLoaded', () => {
  const companyForm = document.getElementById('company-form');
  const companyList = document.getElementById('company-list');
  const companyIdField = document.getElementById('company-id');
  const companyNameField = document.getElementById('company-name');
  const companyImageField = document.getElementById('company-image'); // New Image field
  const shopTypeField = document.getElementById('shop-type');  // New Shop Type field
  let companies = [];

  // Load Companies and display them in the list
  function loadCompanies() {
    fetch('/api/companies')
      .then(response => response.json())
      .then(data => {
        companies = data;
        companyList.innerHTML = ''; // Clear existing list
        companies.forEach(company => {
          const row = document.createElement('tr');
          row.innerHTML = `
            <td>${company.name}</td>
            <td>${company.shopType}</td>  <!-- Display Shop Type -->
            <td>
              <img src="${company.profile_url}" alt="Company Image" width="50">  <!-- Display Image -->
            </td>
            <td>
              <button class="edit-btn" data-id="${company._id}">Edit</button>
              <button class="delete-btn" data-id="${company._id}">Delete</button>
            </td>
          `;
          companyList.appendChild(row);
        });

        // Add event listeners to edit and delete buttons
        document.querySelectorAll('.edit-btn').forEach(button => {
          button.addEventListener('click', editCompany);
        });
        document.querySelectorAll('.delete-btn').forEach(button => {
          button.addEventListener('click', deleteCompany);
        });
      })
      .catch(error => console.error('Error loading companies:', error));
  }

  // Submit the company form (Create or Update company)
  companyForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(); // Use FormData to handle both text and file data

    formData.append('name', companyNameField.value);
    formData.append('shopType', shopTypeField.value);  // Append shopType
    if (companyImageField.files[0]) {
      formData.append('companyImage', companyImageField.files[0]); // Append image if uploaded
    }

    const companyId = companyIdField.value;
    const method = companyId ? 'PUT' : 'POST';
    const url = companyId ? `/api/companies/${companyId}` : '/api/companies';

    fetch(url, {
      method: method,
      body: formData // Send FormData as body for both text and image
    })
      .then(response => response.json())
      .then(() => {
        companyForm.reset();
        loadCompanies();  // Reload companies after saving
      })
      .catch(error => console.error('Error saving company:', error));
  });

  // Edit company (load data into form)
  function editCompany(event) {
    const companyId = event.target.getAttribute('data-id');
    const company = companies.find(company => company._id === companyId);

    companyIdField.value = company._id;
    companyNameField.value = company.name;
    shopTypeField.value = company.shopType;  // Set shop type in the form
    // Optionally handle image preview if needed
  }

  // Delete company
  function deleteCompany(event) {
    const companyId = event.target.getAttribute('data-id');
    if (confirm('Are you sure you want to delete this company?')) {
      fetch(`/api/companies/${companyId}`, {
        method: 'DELETE'
      })
        .then(() => loadCompanies())  // Reload companies after deletion
        .catch(error => console.error('Error deleting company:', error));
    }
  }

  // Initialize: load companies
  loadCompanies();
//});
