// 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');
    var pir='';
    if(getUrlParam('pir')){
        pir=getUrlParam('pir');
    }
    if (formId && patientId && fileId && createdBy) {
          loadPatientDetails(formId, patientId, fileId, createdBy,pir);
    } else {
        console.error('Missing required URL parameters');
    }
});

// Function to load patient details using AJAX
function loadPatientDetails(formId, patientId, fileId, createdBy,pir) {
    $.ajax({
        url: 'https://rxconnections.ca/rxcrm/superadmin/getpatientdetailsforAE.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_23').val(data.patientDetails.patientId);
                    $('#element_10').val(data.patientDetails.patientDrugName);

                    // Insert DOB into element_44_1, element_44_2, element_44_3
                    console.log(pir);
                    $('#element_25').val(pir); // Day 
              
                    if (data.patient.dob) {
                        var dobParts = data.patient.dob.split('-'); 
                        if(formId=="38356"){
                        
                        $('#element_4_1').val(dobParts[2]); // Day
                        $('#element_4_2').val(dobParts[1]); // Month
                        $('#element_4_3').val(dobParts[0]); // Year
                        }
                        else{
                        $('#element_4_2').val(dobParts[2]); // Day
                        $('#element_4_1').val(dobParts[1]); // Month
                        $('#element_4_3').val(dobParts[0]); // Year
                        }
                    }
                        var gender='';
                     if (data.patient.gender) {
                         gender=data.patient.gender;
                        if(gender=='M'){gender='Male';}
                        if(gender=='F'){gender='Female';}
                        if(gender=='O'){gender='Other';}
                        $('#element_5').val(gender); // 
                    }

                    // Insert Patient Initials into element_45
                    if (data.patient.patientName) {
                        var initials = data.patient.patientName
                            .split(' ')
                            .map(word => word.charAt(0).toUpperCase())
                            .join('');
                        $('#element_3').val(initials);
                    }
                    if (data.empName) {
                        var empName = data.empName;
                        $('#element_22').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);
        }
    });
}

// $(document).ready(function() {
//     $('.loader-container').fadeOut(1000);
//     let timer;
//     const inactivityLimit = 1200000;
//     let isActive = false;
//     const events = ['mousemove', 'keydown', 'click', 'scroll']
//     const logoutFunction = () => {
//         //  Logout functionality
//         console.log('user logged out')
//         window.location.href = 'https://rxconnections.ca/rxcrm/logout.php';
//     }
//     const manageSession = () => {
//         clearTimeout(timer)
//         if (isActive) {
//             keepSessionAlive()
//             startTimer()
//             return
//         }
//         logoutFunction()
//     }
//     const keepSessionAlive = () => {
//         fetch('https://rxconnections.ca/rxcrm/keep_session_alive.php');
//     }
//     const startTimer = () => {
//         isActive = false
//         timer = setTimeout(() => {
//             manageSession()
//         }, inactivityLimit)
//     }
//     events.forEach(event => {
//         document.addEventListener(event, () => {
//             isActive = true
//         })
//     })
//     startTimer()
// });
