// loadPatient.js
//tooltip js

///tooltip js end
// Function to get URL parameters
function getUrlParam(param) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
}
function loadTooltip(){
      var lis = document.querySelectorAll('form#form_46593 li');
  lis.forEach(function(li){
    // prefer .guidelines element, but also look for a hidden <p> directly under li (like your section text)
    var guideline = li.querySelector('.guidelines') || li.querySelector('p');
    if(!guideline) return;

    // Oly proceed if guideline has meaningful text
    if(!guideline.textContent.trim()) return;
    // mark the li so the CSS tooltip appears
    li.classList.add('has-tooltip');
    // ensure the guideline has an id for aria-describedby
    if (!guideline.id) {
      guideline.id = 'guide_' + Math.random().toString(36).slice(2,9);
    }
    // find the best trigger element in this li: label.description, span.description, h3, or the first heading
    var trigger = li.querySelector('label.description, span.description, h3, .description');
    if(!trigger){
      // fallback: make the first input/select/textarea the trigger (so focus shows the tooltip)
      trigger = li.querySelector('input, select, textarea') || li;
    }

    // make trigger keyboard-focusable if not already focusable
    var focusable = ['A','BUTTON','INPUT','SELECT','TEXTAREA'];
    var tag = trigger.tagName ? trigger.tagName.toUpperCase() : '';
    if(!focusable.includes(tag) && !trigger.hasAttribute('tabindex')) {
      trigger.setAttribute('tabindex', '0');
    }

    // connect trigger <-> guideline for screen readers
    trigger.setAttribute('aria-describedby', guideline.id);
    guideline.setAttribute('role', 'tooltip');
    guideline.setAttribute('aria-hidden', 'true');

    // toggle aria-hidden so assistive tech knows when tooltip is shown
    var show = function(){ guideline.setAttribute('aria-hidden','false'); };
    var hide = function(){ guideline.setAttribute('aria-hidden','true'); };

    trigger.addEventListener('focus', show);
    trigger.addEventListener('blur', hide);
    trigger.addEventListener('mouseenter', show);
    trigger.addEventListener('mouseleave', hide);
  });

}
$(document).ready(function() {
  const formId = getUrlParam('id');
  const patientId = getUrlParam('patientId');
  const fileId = getUrlParam('fileId');
  const createdBy = getUrlParam('createdBy');

  // PIR is optional: prefer URL param, fallback to sessionStorage (if previously stored), otherwise empty
  let pir = getUrlParam('pir') || sessionStorage.getItem('pir') || '';

  // Require only the truly necessary params
  if (formId && patientId && fileId && createdBy) {
    // Save PIR to sessionStorage if present so future loads can reuse it
    if (pir) sessionStorage.setItem('pir', pir);

    loadPatientDetails(formId, patientId, fileId, createdBy, pir);
  } else {
    console.error('Missing required URL parameters (id, patientId, fileId, createdBy required).');
  }
  
  loadTooltip();
});

// Function to load patient details using AJAX
function loadPatientDetails(formId, patientId, fileId, createdBy, pir) {
  $.ajax({
    url: 'https://rxconnections.ca/rxcrm/superadmin/getPatientDetails.php',
    type: 'GET',
    data: {
      id: formId,
      patientId: patientId,
      fileId: fileId,
      createdBy: createdBy,
      pir: pir // pass along (may be empty)
    },
    success: function(response) {
      try {
        // handle both JSON string and already-parsed object
        var data = (typeof response === 'string') ? JSON.parse(response) : response;

        if (data && data.success) {
          // Insert Patient ID into element_43 (guarding against missing nested structure)
          if (data.patientDetails && data.patientDetails.patientId) {
            $('#element_12').val(data.patientDetails.patientId);
          }
           if (data.patientDetails && data.patientDetails.exPatientId) {
            $('#element_13').val(data.patientDetails.exPatientId);
          }

          // Prefer the PIR from url/session, but if missing try server-provided value
          var finalPir = pir || (data.patientDetails && data.patientDetails.pir) || (data.patient && data.patient.pir) || '';
          $('#element_77').val(finalPir);

          // Insert DOB into element_44_1, element_44_2, element_44_3 if available and valid
         if (data.patient && data.patient.dob) {
              var dobStr = String(data.patient.dob).trim();
              var birth = null;
            
              // Try common formats:
              //  - YYYY-MM-DD or YYYY/MM/DD or ISO
              //  - DD-MM-YYYY or DD/MM/YYYY
              //  - MM/DD/YYYY
              if (/^\d{4}[-\/]\d{1,2}[-\/]\d{1,2}/.test(dobStr)) {
                // YYYY-MM-DD or YYYY/MM/DD
                var p = dobStr.split(/[-\/]/);
                birth = new Date(parseInt(p[0], 10), parseInt(p[1], 10) - 1, parseInt(p[2], 10));
              } else if (/^\d{1,2}[-\/]\d{1,2}[-\/]\d{4}/.test(dobStr)) {
                // DD-MM-YYYY or MM/DD/YYYY (ambiguous: assume DD-MM-YYYY because original expected YYYY-MM-DD)
                var p = dobStr.split(/[-\/]/);
                // If you expect MM/DD/YYYY instead, swap p[0] and p[1] here.
                birth = new Date(parseInt(p[2], 10), parseInt(p[1], 10) - 1, parseInt(p[0], 10));
              } else {
                // Last resort: let Date try to parse (handles things like "2020-08-01T00:00:00Z")
                var d = new Date(dobStr);
                if (!isNaN(d.getTime())) birth = d;
              }
            
              if (birth && !isNaN(birth.getTime())) {
                var day = birth.getDate();           // 1-31 (number)
                var month = birth.getMonth() + 1;    // 1-12 (number)
                var year = birth.getFullYear();
            
                // Fill the day, month, year inputs (removes leading zeros)
                if ($('#element_15_1').length) $('#element_15_1').val(day);
                if ($('#element_15_2').length) $('#element_15_2').val(month);
                if ($('#element_15_3').length) $('#element_15_3').val(year);
            
                // Calculate age (years), adjusting if birthday hasn't occurred yet this year
                var today = new Date();
                var age = today.getFullYear() - year;
                var todayMonth = today.getMonth() + 1;
                var todayDay = today.getDate();
            
                if (todayMonth < month || (todayMonth === month && todayDay < day)) {
                  age -= 1;
                }
            
                // sanity: don't allow negative ages
                if (age < 0) age = 0;
            
                // set age
                if ($('#element_16').length) $('#element_16').val(age);
              } else {
                // invalid DOB — optional: clear fields or log
                // $('#element_15_2, #element_15_1, #element_15_3, #element_16').val('');
                console.warn('Invalid DOB:', data.patient.dob);
              }
            }
            
           if (data.patient && data.patient.gender) {
                  const gender = String(data.patient.gender).trim().toUpperCase();
                  const genderMap = { M: '1', F: '2', O: '3' };
                  if (genderMap[gender]) $('#element_17').val(genderMap[gender]);
            }

          // Insert Patient Initials into element_45
          if (data.patient && data.patient.patientName) {
            var initials = data.patient.patientName
              .split(' ')
              .map(word => word.charAt(0).toUpperCase())
              .join('');
            $('#element_14').val(initials);
          }

          // Employee name into element_72 if provided by server
          if (data.empName) {
            $('#element_47').val(data.empName);
          }
          //Product Name
           if (data.drugDetails.patientDrugName) {
            $('#element_27').val(data.drugDetails.patientDrugName);
          }
          // indication
           if (data.drugDetails.indication) {
            $('#element_29').val(data.drugDetails.indication);
          }
          //ROA
           if (data.drugDetails.routeOfAdmin) {
            $('#element_33').val(data.drugDetails.routeOfAdmin);
          }
          
       

        } else {
          console.error('Error from server:', (data && data.message) ? data.message : 'Unknown error');
        }
      } catch (e) {
        console.error('Error parsing response:', e, response);
      }
    },
    error: function(xhr, status, error) {
      console.error('AJAX Error:', status, error);
    }
  });
}
