// loadPatient.js

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

// Automatically get patientId and fileId from URL and call loadPatientDetails
$(document).ready(function() {
    const formId = getUrlParam('id');
    const patientId = getUrlParam('patientId');
    const fileId = getUrlParam('fileId');
    const createdBy = getUrlParam('createdBy');

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

// Function to load patient details using AJAX
function loadPatientDetails(formId, patientId, fileId, createdBy) {
    $.ajax({
        url: 'https://rxconnections.ca/rxcrm/superadmin/getPatientDetails.php',
        type: 'GET',
        data: {
            id: formId,         
            patientId: patientId, 
            fileId: fileId,     
            createdBy: createdBy 
        },
        success: function(response) {
            try {
                var data = response;
                if (data.success) {
                    // Insert Patient ID into element_43
                  //  $('#element_1_1').val(data.patientDetails.patientId);
                    $('#element_1_1').val(data.patient.firstName);
                    $('#element_1_2').val(data.patient.lastName);

                    // Insert DOB into element_44_1, element_44_2, element_44_3
                    if (data.patient.dob) {
                        var dobParts = data.patient.dob.split('-'); 
                        $('#element_2_1').val(dobParts[2]); // Day
                        $('#element_2_2').val(dobParts[1]); // Month
                        $('#element_2_3').val(dobParts[0]); // Year
                    }

                    // Insert Patient Initials into element_45
                    // if (data.patient.patientName) {
                    //     var initials = data.patient.patientName
                    //         .split(' ')
                    //         .map(word => word.charAt(0).toUpperCase())
                    //         .join('');
                    //     $('#element_45').val(initials);
                    // }
                    // if (data.empName) {
                    //     var empName = data.empName;
                    //     $('#element_72').val(empName);
                    // }
                    
                } else {
                    console.error('Error:', data.message);
                }
            } catch (e) {
                console.error('Error parsing response:', e);
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', status, error);
        }
    });
}

