const branchForm = document.getElementById('branch-form');
const branchGroupSelect = document.getElementById('branchgroup-select');
const branchList = document.getElementById('branch-list');
const branchIdField = document.getElementById('branch-id');
const branchNameField = document.getElementById('branch-name');
const branchTypeSelect = document.getElementById('branch-type');
const storeBranchSelect = document.getElementById('storebranch-select');

let branches = [];
let branchGroups = [];
let storeBranches = [];

const companyId = sessionStorage.getItem('companyId');

// Load branch groups
function loadBranchGroups() {
  fetch(`/api/branch-groups/company/${companyId}`)
    .then(response => response.json())
    .then(data => {
      branchGroups = data;
      branchGroupSelect.innerHTML = '<option value="">-- null--</option>';
      branchGroups.forEach(group => {
        const option = document.createElement('option');
        option.value = group._id;
        option.textContent = group.groupName;
        branchGroupSelect.appendChild(option);
      });
    })
    .catch(error => console.error('Error loading branch groups:', error));
}

// Load branches for storeBranch selection and branch list
function loadBranches() {
  fetch(`/api/branches?companyId=${companyId}`)
    .then(response => response.json())
    .then(data => {
      branches = data;
      branchList.innerHTML = '';
  
      storeBranchSelect.innerHTML = '<option value="">-- null--</option>';
      
      branches.forEach(branch => {
        const branchGroupName = branch.groupId ? branch.groupId.groupName : 'No Group';
        
        // Populate branch list table
        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${branch.name}</td>
          <td>${branchGroupName}</td>
          <td>${branch.type}</td>
          <td>${branch.storeBranch ? branch.storeBranch.name : 'N/A'}</td>
          <td>
            <button class="edit-btn" data-id="${branch._id}">Edit</button>
            <button class="delete-btn" data-id="${branch._id}">Delete</button>
          </td>`;
        branchList.appendChild(row);

        // Populate storeBranch dropdown for selection
        const option = document.createElement('option');
        option.value = branch._id;
        option.textContent = branch.name;
        storeBranchSelect.appendChild(option);
      });

      // Add event listeners for edit and delete
      document.querySelectorAll('.edit-btn').forEach(button => button.addEventListener('click', editBranch));
      document.querySelectorAll('.delete-btn').forEach(button => button.addEventListener('click', deleteBranch));
    })
    .catch(error => console.error('Error loading branches:', error));
}

// Form submission for creating/updating a branch
branchForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const branchData = {
    companyId: companyId,
    groupId: branchGroupSelect.value ,
    name: branchNameField.value,
    type: branchTypeSelect.value,
    storeBranch: storeBranchSelect.value 
  };



  const branchId = branchIdField.value;
  const method = branchId ? 'PUT' : 'POST';
  const url = branchId ? `/api/branches/${branchId}` : '/api/branches';

  fetch(url, {
    method: method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(branchData),
  })
    .then(response => response.json())
    .then(() => {
      branchForm.reset();
      branchIdField.value = '';
      alert("Branch saved successfully");
      loadBranches();
    })
    .catch(error => console.error('Error saving branch:', error));
});

function editBranch(event) {
  const branchId = event.target.getAttribute('data-id');
  const branch = branches.find(branch => branch._id === branchId);

  // Populate form fields with the branch's existing data
  branchIdField.value = branch._id;
  branchNameField.value = branch.name;
  branchTypeSelect.value = branch.type;
  storeBranchSelect.value = branch.storeBranch ? branch.storeBranch._id : '';
  branchGroupSelect.value = branch.groupId ? branch.groupId._id : '';

  // Optionally, switch to the form tab if you're using tabbed content
  openTab(event, 'branch-form-tab');
}

// Delete branch function
function deleteBranch(event) {
  const branchId = event.target.getAttribute('data-id');
  if (confirm('Are you sure you want to delete this branch?')) {
    fetch(`/api/branches/${branchId}`, { method: 'DELETE' })
      .then(() => loadBranches())
      .catch(error => console.error('Error deleting branch:', error));
  }
}

// Tab switching function
function openTab(event, tabId) {
  const tabContents = document.querySelectorAll('.tab-content');
  tabContents.forEach(tab => (tab.style.display = 'none'));

  const tabButtons = document.querySelectorAll('.tab-button');
  tabButtons.forEach(button => button.classList.remove('active'));

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

// Initial Load
loadBranchGroups();
loadBranches();
