// Initialize Advanced Select2 on Document Ready
$(document).ready(function() {
    $('#patientSelect').select2({
        placeholder: "-- View All Pending or Select Specific Patient --",
        allowClear: true
    });
});

// Advanced Date Range & Patient Filtering
function applyFilters() {
    const dateFrom = document.getElementById('filterDateFrom').value;
    const dateTo = document.getElementById('filterDateTo').value;
    const patientNo = document.getElementById('patientSelect').value;
    
    let url = `?`;
    if (dateFrom && dateTo) {
        url += `date_from=${dateFrom}&date_to=${dateTo}`;
    }
    if (patientNo) {
        url += (url === '?' ? '' : '&') + `patient_no=${patientNo}`;
    }
    
    window.location.href = url;
}

function clearFilters() {
    window.location.href = `?date_from=ALL`;
}

// UI Interactions
function showToast(message, type = 'success') {
  const container = document.getElementById('toast-container');
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-circle-exclamation';
  toast.innerHTML = `<i class="fa-solid ${iconClass} toast-icon"></i><span class="toast-msg">${message}</span>`;
  container.appendChild(toast);
  setTimeout(() => toast.classList.add('show'), 10);
  setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 3500);
}

function switchTest(itemId) {
  document.querySelectorAll('.test-tab').forEach(tab => tab.classList.remove('active'));
  const activeTab = document.getElementById(`tab-${itemId}`);
  if(activeTab) activeTab.classList.add('active');

  document.querySelectorAll('.test-card').forEach(card => card.classList.remove('active'));
  const activeCard = document.getElementById(`card-${itemId}`);
  if(activeCard) activeCard.classList.add('active');
}

function filterTabs() {
  const searchVal = document.getElementById('tabSearch').value.toLowerCase();
  const tabs = document.querySelectorAll('.test-tab');
  let firstVisibleId = null;

  tabs.forEach(tab => {
    const tName = tab.getAttribute('data-testname');
    let matchesSearch = tName.includes(searchVal);
    
    if (matchesSearch) {
      tab.style.display = 'flex';
      if(!firstVisibleId) firstVisibleId = tab.id.replace('tab-', '');
    } else {
      tab.style.display = 'none';
    }
  });

  const currentActive = document.querySelector('.test-tab.active');
  if(currentActive && currentActive.style.display === 'none' && firstVisibleId) {
      switchTest(firstVisibleId);
  } else if (!currentActive && firstVisibleId) {
      switchTest(firstVisibleId);
  }
}

// Clinical Delta Checking
function evaluateRange(input) {
  const val = parseFloat(input.value);
  const min = parseFloat(input.getAttribute('data-min'));
  const max = parseFloat(input.getAttribute('data-max'));
  const row = input.closest('tr');
  const flagBadge = row.querySelector('.flag-badge');
  const flagInput = row.querySelector('.flag-val');

  input.classList.remove('input-high', 'input-low');
  flagBadge.className = 'flag-badge';
  flagBadge.innerText = '';
  flagInput.value = 'Normal';

  if (isNaN(val)) return;

  if (val < min) {
    input.classList.add('input-low');
    flagBadge.classList.add('flag-low');
    flagBadge.innerText = 'L';
    flagInput.value = 'Low';
  } else if (val > max) {
    input.classList.add('input-high');
    flagBadge.classList.add('flag-high');
    flagBadge.innerText = 'H';
    flagInput.value = 'High';
  }
}

function evaluateQualitative(select, expected) {
  const row = select.closest('tr');
  const flagBadge = row.querySelector('.flag-badge');
  const flagInput = row.querySelector('.flag-val');

  select.classList.remove('input-high', 'input-low');
  flagBadge.className = 'flag-badge';
  flagBadge.innerText = '';
  flagInput.value = 'Normal';

  if(select.value !== '' && select.value !== expected) {
      select.classList.add('input-high');
      flagBadge.classList.add('flag-high');
      flagBadge.innerText = 'Abn';
      flagInput.value = 'Abnormal';
  }
}

function saveAndNext(itemId) {
  const card = document.getElementById(`card-${itemId}`);
  const inputs = card.querySelectorAll('.result-val');
  let isValid = true;

  inputs.forEach(input => input.classList.remove('error'));

  inputs.forEach(input => {
    if(input.value.trim() === '') {
      isValid = false;
      input.classList.add('error');
    }
  });

  if(!isValid) {
    showToast("Please complete all required parameters before saving.", "error");
    return;
  }

  const tab = document.getElementById(`tab-${itemId}`);
  tab.classList.add('completed');
  showToast("Results saved temporarily.", "success");

  const allTabs = Array.from(document.querySelectorAll('.test-tab'));
  let currentIndex = allTabs.findIndex(t => t.id === `tab-${itemId}`);
  
  let nextTabFound = false;
  for(let i = currentIndex + 1; i < allTabs.length; i++) {
     if(allTabs[i].style.display !== 'none' && !allTabs[i].classList.contains('completed')) {
         switchTest(allTabs[i].id.replace('tab-', ''));
         nextTabFound = true;
         break;
     }
  }

  if(!nextTabFound) {
      showToast("All visible tests have been drafted. You may submit.", "success");
  }
}

// API Submission Engine
function submitAllResults() {
  const completedTabs = document.querySelectorAll('.test-tab.completed');
  if(completedTabs.length === 0) {
      showToast("No tests have been completed. Please enter results first.", "error");
      return;
  }

  const payload = {
      patient_no: document.getElementById('patient_no').value,
      tests: []
  };

  document.querySelectorAll('.test-card').forEach(card => {
      const reqId = card.getAttribute('data-reqid');
      const tab = document.getElementById(`tab-${reqId}`);
      
      if(tab && tab.classList.contains('completed')) {
          const remarks = card.querySelector('.test-remarks').value;
          const params = [];
          
          card.querySelectorAll('.param-row').forEach(row => {
              const paramId = row.getAttribute('data-paramid');
              const val = row.querySelector('.result-val').value;
              const ref = row.querySelector('.ref-used-val').value;
              const flag = row.querySelector('.flag-val').value;
              
              params.push({
                  parameter_id: paramId,
                  value: val,
                  reference: ref,
                  flag: flag
              });
          });

          payload.tests.push({
              request_id: reqId,
              remarks: remarks,
              parameters: params
          });
      }
  });

  const btn = document.getElementById('btnSubmitAll');
  btn.disabled = true;
  btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Submitting to Verification...';

  fetch('../../dripend/includes/lab/processLabResult.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
  })
  .then(async res => {
      if(!res.ok) throw new Error('HTTP error ' + res.status);
      return res.json();
  })
  .then(data => {
      if(data.status === 'success') {
          showToast(`${completedTabs.length} test(s) submitted for Pathologist Verification.`, "success");
          setTimeout(() => window.location.reload(), 1500);
      } else {
          showToast(data.message, 'error');
          btn.disabled = false;
          btn.innerHTML = '<i class="fa-solid fa-paper-plane"></i> Submit All Finished Results for Verification';
      }
  })
  .catch(err => {
      showToast('Network error processing results.', 'error');
      btn.disabled = false;
      btn.innerHTML = '<i class="fa-solid fa-paper-plane"></i> Submit All Finished Results for Verification';
      console.error(err);
  });
}