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 branchDefaultAction= document.getElementById('branch-default-action');

const storeBranchSelect = document.getElementById('storebranch-select');
const considerStockToggle = document.getElementById('considerStock');
const considerSystemSaleToggle = document.getElementById('considerSystemSale');
const considerSystemWithdrawalToggle = document.getElementById('considerSystemWithdrawal');
const considerSystemWithdrawalForSellingToggle = document.getElementById('considerSystemWithdrawalForSelling');

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');
   // Create the table row with editable fields
   let tempgroupId='';
row.innerHTML = `
<td contenteditable="true" data-field="name">${branch.name}</td>
<td>
  <select data-field="groupId">
    <option value="">Select Group</option>
    ${branchGroups.map(group => `
   ${ tempgroupId=branch.groupId?branch.groupId._id:''}
      <option value="${group._id}" ${tempgroupId === group._id ? 'selected' : ''}>${group.groupName}</option>
    `).join('')}
  </select>
</td>
<td>
  <select data-field="type" >
    <option value="store" ${branch.type === 'store' ? 'selected' : ''}>Store</option>
    <option value="shop" ${branch.type === 'shop' ? 'selected' : ''}>Shop</option>
  </select>
</td>


<td>
 <select data-field="defaultAction">
   <option value="selling" ${branch.defaultAction == 'selling' ? 'selected' : ''}>Selling</option>
  <option value="using" ${branch.defaultAction == 'using' ? 'selected' : ''}>Using</option>
  <option value="purchasing" ${branch.defaultAction == 'purchasing' ? 'selected' : ''}>Purchasing</option>
  <option value="transfer" ${branch.defaultAction == 'transfer' ? 'selected' : ''}>Transfer</option>
  <option value="producing" ${branch.defaultAction == 'producing' ? 'selected' : ''}>Producing</option>
 </select>
  </td>




<td>
  <label class="switch">
    <input type="checkbox" data-field="considerStock" ${branch.considerStock ? 'checked' : ''}>
    <span class="slider round"></span>
  </label>
</td>
<td>
  <label class="switch">
    <input type="checkbox" data-field="considerSystemSale" ${branch.considerSystemSale ? 'checked' : ''}>
    <span class="slider round"></span>
  </label>
</td>
<td>
  <label class="switch">
    <input type="checkbox" data-field="considerSystemWithdrawal" ${branch.considerSystemWithdrawal ? 'checked' : ''}>
    <span class="slider round"></span>
  </label>
</td>
<td>
  <label class="switch">
    <input type="checkbox" data-field="considerSystemWithdrawalForSelling" ${branch.considerSystemWithdrawalForSelling ? 'checked' : ''}>
    <span class="slider round"></span>
  </label>
</td>
<td>
  <button class="save-btn" data-id="${branch._id}" style="display: none;">Save</button>
  <button class="delete-btn" data-id="${branch._id}">Delete</button>
</td>
`;

branchList.appendChild(row);

// Show "Save" button when any field is edited
const saveButton = row.querySelector('.save-btn');

// Add event listeners to make "Save" button appear when changes are detected
row.querySelectorAll('[data-field]').forEach(field => {
if (field.getAttribute('contenteditable') === 'true') {
  field.addEventListener('input', () => {
    saveButton.style.display = 'inline-block';
  });
} else {
  field.addEventListener('change', () => {
    saveButton.style.display = 'inline-block';
  });
}
});



        // Populate storeBranch dropdown for selection
        if (branch.type === 'store') {
          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 || null,
    name: branchNameField.value,
    type: branchTypeSelect.value,
    defaultAction:branchDefaultAction.value,
    storeBranchId: storeBranchSelect.value || null,
    considerStock: considerStockToggle.checked,
    considerSystemSale: considerSystemSaleToggle.checked,
    considerSystemWithdrawal: considerSystemWithdrawalToggle.checked,
    considerSystemWithdrawalForSelling: considerSystemWithdrawalForSellingToggle.checked
  };



  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;
  branchDefaultAction.value=  branch.defaultAction;
  storeBranchSelect.value = branch.storeBranchId ? branch.storeBranchId._id : '';
  branchGroupSelect.value = branch.groupId ? branch.groupId._id : '';

  // Set toggle switches based on existing data
  considerStockToggle.checked = branch.considerStock;
  considerSystemSaleToggle.checked = branch.considerSystemSale;
  considerSystemWithdrawalToggle.checked = branch.considerSystemWithdrawal;
  considerSystemWithdrawalForSellingToggle.checked = branch.considerSystemWithdrawalForSelling;

  // 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');
}



document.addEventListener('click', (e) => {
  if (e.target.classList.contains('save-btn')) {
    const branchId = e.target.getAttribute('data-id');
    const row = e.target.closest('tr');

  // Capture edited values
const updatedData = {
  name: row.querySelector('[data-field="name"]').textContent,
  groupId: row.querySelector('[data-field="groupId"]').value||null, // Capture selected groupId value
  type: row.querySelector('[data-field="type"]').value,
  defaultAction: row.querySelector('[data-field="defaultAction"]').value,
  considerStock: row.querySelector('[data-field="considerStock"]').checked,
  considerSystemSale: row.querySelector('[data-field="considerSystemSale"]').checked,
  considerSystemWithdrawal: row.querySelector('[data-field="considerSystemWithdrawal"]').checked,
  considerSystemWithdrawalForSelling: row.querySelector('[data-field="considerSystemWithdrawalForSelling"]').checked
};

console.log("values are:",updatedData);
    // Send updated data to backend
    fetch(`/api/branches/${branchId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updatedData)
    })
    .then(response => response.json())
    .then(data => {
      alert('Branch updated successfully');
      e.target.style.display = 'none'; // Hide the Save button after saving
    })
    .catch(error => console.error('Error updating branch:', error));
  }

  if (e.target.classList.contains('delete-btn')) {
    const branchId = e.target.getAttribute('data-id');
    if (confirm('Are you sure you want to delete this branch?')) {
      fetch(`/api/branches/${branchId}`, {
        method: 'DELETE'
      })
      .then(() => {
        alert('Branch deleted successfully');
        loadBranches(); // Reload the branches list
      })
      .catch(error => console.error('Error deleting branch:', error));
    }
  }
});



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