// loadPatient.js

// Function to get URL parameters
function getUrlParam(param) {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
}

$(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).');
  }
});

// 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_43').val(data.patientDetails.patientId);
          }

          // 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 dobParts = data.patient.dob.split('-'); // expecting YYYY-MM-DD
            if (dobParts.length === 3) {
              $('#element_44_1').val(dobParts[2]); // Day
              $('#element_44_2').val(dobParts[1]); // Month
              $('#element_44_3').val(dobParts[0]); // Year
            }
          }

          // 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_45').val(initials);
          }

          // Employee name into element_72 if provided by server
          if (data.empName) {
            $('#element_72').val(data.empName);
          }

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