$(document).on('click', '.deleteDocument', function () {
    // Get the data-id attribute
    var documentId = $(this).data('id');
    // Confirm delete action
    if (confirm('Are you sure you want to delete this document?')) {
        // AJAX call to delete the document
        $.ajax({
            url: 'ajax_call.php?ajaxcall=deletePatient', // Replace with your server endpoint
            type: 'POST',
            data: { id: documentId },
            success: function (response) {
                // Handle successful response
                alert('Document deleted successfully!');
                window.location.reload();
                // Optionally, remove the button or update the UI
                // $(this).closest('.document-item').remove();
            },
            error: function (xhr, status, error) {
                // Handle error response
                alert('Error deleting document: ' + error);
            }
        });
    }
});
$(document).ready(function () {
    
    // Prefill acc to drugname and Indication detail listing    -   Start
    
    // fill dose and frequency
    // considering we only have one indication
    var indication = $('#indication').val()[0];
    if(indication!=undefined && indication!='')
    {
        indication = indication.replace("'", "''");
    }
    var drugname = $('#patientDrugName').val().split(" ")[0];
    
    // for multiple indications
    if($('#indication').val() && $('#indication').val().length > 1)
    {
        indication="";
        $('#indication').val().forEach(function(indicationdata) {
            indicationdata = indicationdata.replace("'", "''");
            indication = indication+','+indicationdata;
        });
        indication=indication.substring(1);
        indication=indication.replaceAll(",", "','");
    }
    //get loading dose
    // $('#ldosage').prop('disabled', false).empty().append('<option value="">Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_ldose_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#ldosage').append($('<option>', {
                        value: indication.loadingdose,
                        text: indication.loadingdose
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#ldosage').data('selected', '');
                //if only one entry is present:
                // if($('#ldosage option').length == 1){
                //     $('#ldosage')[0].setAttribute("disabled","true");
                // }
            }
        });
    }
    //get loading frequency
    // $('#lfrequency').prop('disabled', false).empty().append('<option value="">Select Frequency</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_lfrequency_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#lfrequency').append($('<option>', {
                        value: indication.loadingfrequency,
                        text: indication.loadingfrequency
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#lfrequency').data('selected', '');
                //if only one entry is present:
                // if($('#lfrequency option').length == 1){
                //     $('#lfrequency')[0].setAttribute("disabled","true");
                // }
            }
        });
    }
    
    //get loading roa
    // $('#lroa').prop('disabled', false).empty().append('<option value="">Select Route of Administration</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_lroa_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#lroa').append($('<option>', {
                        value: indication.loadingroa,
                        text: indication.loadingroa
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#lroa').data('selected', '');
            }
        });
    }
    
    //get Maintenance dose
    // $('#dose').prop('disabled', false).empty().append('<option value="" disabled>Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mdose_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#dose').append($('<option>', {
                        value: indication.maintenancedose,
                        text: indication.maintenancedose
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#dose').data('selected', '');
            }
        });
    }
    //get Maintenance frequency
    // $('#currentFrequency').prop('disabled', false).empty().append('<option value="" disabled>Select Frequency</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mfrequency_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#currentFrequency').append($('<option>', {
                        value: indication.maintenancefrequency,
                        text: indication.maintenancefrequency
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#currentFrequency').data('selected', '');
            }
        });
    }
    
    //get Maintenance roa
    // $('#roa').prop('disabled', false).empty().append('<option value="" disabled>Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mroa_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#roa').append($('<option>', {
                        value: indication.maintenanceroa,
                        text: indication.maintenanceroa
                    }));
                });
                // Clear the preselected data attribute once status changes.
                // $('#roa').data('selected', '');
            }
        });
    }
    
    // Prefill acc to drugname and Indication details listing   -   END

    $('.accordion').click(function () {
        var $ftitle = $(this).closest('.ftitle');
        var $nextftitle = $ftitle.nextUntil('.ftitle');

        // Hide all li elements between current and next .ftitle
        if ($nextftitle.hasClass('accordion-hide')) {
            $nextftitle.removeClass('accordion-hide');
        } else {
            // Hide all li elements between current and next .ftitle
            $nextftitle.addClass('accordion-hide');
        }
    });
    
    // get indications according to drug name
    $('#patientDrugName').on("change", function () {
    var drugname = $(this).val().split(" ")[0];
    
    // show hide matcode fields (only applicable for Freedom/Dupixent files) 
    if(drugname.includes('Dupi') && $('#prescriberName').find('option:selected').data('physiciantype')!='' && $('#prescriberName').find('option:selected').data('physiciantype')=='Pilot'){
        // make fields mandatory and visible
        $('#mat')[0].setAttribute("required","true");
        $('#consentInsideEF')[0].removeAttribute("hidden");
        $('#EnrollmentMAT')[0].removeAttribute("hidden");
    }
    else{
        //make fields non-mandatory and hide the fields
        $('#mat')[0].removeAttribute("required");
        $('#consentInsideEF')[0].setAttribute("hidden","true");
        $('#EnrollmentMAT')[0].setAttribute("hidden","true");
    }
    
    $('#indication').prop('disabled', false).empty().append('<option value="" disabled>Select Indication</option>');
        if (drugname) {
            $.ajax({
                url: '../pharmacy/ajax_call.php?ajaxcall=fetch_indication_acc_drug',
                type: 'GET',
                data: { drugname: drugname },
                dataType: 'json',
                success: function (data) {
                    $.each(data, function (index, indication) {
                        $('#indication').append($('<option>', {
                            value: indication.name,
                            text: indication.name
                        }));
                    });
                    // Clear the preselected data attribute once status changes.
                    $('#indication').data('selected', '');
                }
            });
        }
    });
    
    //on change indication
    $('#indication').change(function () {
    // fill dose and frequency
    
    // considering we only have one indication
    var indication = $(this).val()[0];
    if(indication!=undefined && indication!='')
    {
        indication = indication.replace("'", "''");
    }
    var drugname = $('#patientDrugName').val().split(" ")[0];
    
    // for multiple indications
    if($(this).val() && $(this).val().length > 1)
    {
        indication="";
        $(this).val().forEach(function(indicationdata) {
            indicationdata = indicationdata.replace("'", "''");
            indication = indication+','+indicationdata;
        });
        indication=indication.substring(1);
        indication=indication.replaceAll(",", "','");
    }
    //get loading dose
    $('#ldosage').prop('disabled', false).empty().append('<option value="">Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_ldose_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#ldosage').append($('<option>', {
                        value: indication.loadingdose,
                        text: indication.loadingdose
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#ldosage').data('selected', '');
                //if only one entry is present:
                // if($('#ldosage option').length == 1){
                //     $('#ldosage')[0].setAttribute("disabled","true");
                // }
            }
        });
    }
    //get loading frequency
    $('#lfrequency').prop('disabled', false).empty().append('<option value="">Select Frequency</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_lfrequency_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#lfrequency').append($('<option>', {
                        value: indication.loadingfrequency,
                        text: indication.loadingfrequency
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#lfrequency').data('selected', '');
                //if only one entry is present:
                // if($('#lfrequency option').length == 1){
                //     $('#lfrequency')[0].setAttribute("disabled","true");
                // }
            }
        });
    }
    
    //get loading roa
    $('#lroa').prop('disabled', false).empty().append('<option value="">Select Route of Administration</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_lroa_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#lroa').append($('<option>', {
                        value: indication.loadingroa,
                        text: indication.loadingroa
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#lroa').data('selected', '');
            }
        });
    }
    
    //get Maintenance dose
    $('#dose').prop('disabled', false).empty().append('<option value="" disabled>Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mdose_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#dose').append($('<option>', {
                        value: indication.maintenancedose,
                        text: indication.maintenancedose
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#dose').data('selected', '');
            }
        });
    }
    //get Maintenance frequency
    $('#currentFrequency').prop('disabled', false).empty().append('<option value="" disabled>Select Frequency</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mfrequency_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#currentFrequency').append($('<option>', {
                        value: indication.maintenancefrequency,
                        text: indication.maintenancefrequency
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#currentFrequency').data('selected', '');
            }
        });
    }
    
    //get Maintenance roa
    $('#roa').prop('disabled', false).empty().append('<option value="" disabled>Select Dose</option>');
    if (indication && drugname) {
        $.ajax({
            url: '../pharmacy/ajax_call.php?ajaxcall=fetch_mroa_acc_drug',
            type: 'GET',
            data: { drugname: drugname,
                    indication: indication
                    },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (index, indication) {
                    $('#roa').append($('<option>', {
                        value: indication.maintenanceroa,
                        text: indication.maintenanceroa
                    }));
                });
                // Clear the preselected data attribute once status changes.
                $('#roa').data('selected', '');
            }
        });
    }
    
    
});
// on change indication end
});
$('#psp').change(function () {
    var psp = $("#psp option:selected").val();
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "ajax_call.php?ajaxcall=4&id=" + psp,
        success: function (data) {
            $('#drug').append(data);
        }
    })
});
$(window).scroll(function () {
    var scrollHeight = $(this).scrollTop();
    var content = $('#shift');
    if (scrollHeight > 20) {
        content.addClass('moveToRight');
    } else {
        content.removeClass('moveToRight');
    }
});

$('#medicationId').change(function () {
    $('#pspId').remove();
    var medication = $("#medicationId option:selected").val();
    $.ajax({
        type: "POST",
        dataType: "html",
        url: "ajax_call.php?ajaxcall=1&id=" + medication,
        success: function (data) {
            $('#pspDiv').append(data);
        }
    });
});
$("#asc").on("click", function () {
    $('.secondaryContact').toggle();
});
$('#tbskin').on("click", function () {
    $('.tbskinshow').toggle();
});
$('#Chest').on("click", function () {
    $('.chestxrayshow').toggle();
});
$('#Other').on("click", function () {
    $('.otherScreenImm').toggle();
});

$('input[name="Dpgsd"]').on("click", function () {
    if ($(this).val() == 0) {
        $('.sampleDosePrescriber').hide();
    } else {
        $('.sampleDosePrescriber').show();
    }
});
$('#sis').on("change", function () {
    $('.ScrnConfirmationDate').hide();
    $('.screeningVaccinationRequired').hide();
    $('.scrnImmFollowUpDate').hide();
    if ($(this).val() == 4) {
        $('.ScrnConfirmationDate').show();
    }
    if ($(this).val() == 1 || $(this).val() == 2) {
        $('.screeningVaccinationRequired').show();
        $('.scrnImmFollowUpDate').show();

    }
});
$('#wcStatus').on("change", function () {
    $('.firstAttemptContact').hide();
    $('.secondAttemptContact').hide();
    $('.thirdAttemptContact').hide();
    $('.welcomeCallCompletionDate').hide();
    $('.welcomeCallCompleteBy').hide();
    if ($(this).val() == 1 || $(this).val() == 7 || $(this).val() == 8 || $(this).val() == 9 || $(this).val() == 10 || $(this).val() == 11 || $(this).val() == 12) {
        //   $('.ScrnConfirmationDate').show();
    }
    if ($(this).val() == 2) {
        $('.firstAttemptContact').show();
    }
    if ($(this).val() == 3) {
        $('.firstAttemptContact').show();
        $('.secondAttemptContact').show();
    }
    if ($(this).val() == 4 || $(this).val() == 6) {
        $('.firstAttemptContact').show();
        $('.secondAttemptContact').show();
        $('.thirdAttemptContact').show();
    }
    if ($(this).val() == 5) {
        $('.welcomeCallCompletionDate').show();
        $('.welcomeCallCompleteBy').show();
        $("#pwkl").prop('required',true);
        $("#indication").prop('required',true);
        $("#oluse").prop('required',true);
    }else{
        $("#pwkl").prop('required',false);
        $("#indication").prop('required',false);
        $("#oluse").prop('required',false);
    }
});

function cloneMedicationFields(count) {
    var newcount = count + 1;
    var clonedFields = `<li class="prmedication rmMed` + count + `" data-id="">
<label class="description" for="pmpw`+ count + `">Previous Medication #` + count + ` Patient was on for their Condition: </label>
<div>
<input id="pmpw`+ count + `" name="pmpw[]" placeholder="Name of Drug" class="form-control" type="text" value="" autocomplete="off">
</div>
</li>

<li class="prmedication rmMed`+ count + `">
<label class="description" for="pmdosage`+ count + `">Previous Medication #` + count + ` Dosage: </label>
<div>
<input id="pmdosage`+ count + `" name="pmdosage[]" class="form-control" type="text" value="" autocomplete="off">
</div>
</li>

<li class="prmedication rmMed`+ count + `">
<label class="description" for="wpsf`+ count + `">Why did Patient switch from previous Medication #` + count + `? </label>
<div>
<input id="wpsf`+ count + `" name="wpsf[]" placeholderforcheck="" class="form-control" type="text" value="" autocomplete="off">
</div>
</li>

<li class="checkboxes prmedication rmMed`+ count + `">
<div>
<fieldset>
<span><input id="pdkse`+ count + `" name="pdkse[]" class="form-checkbox pdkse" type="checkbox" value="1" autocomplete="off">
<label class="choice" for="pdkse`+ count + `">Patient does not know Start/End Date</label>
</span>
</fieldset>
</div>
</li>

<li class="pdkse`+ count + ` col-md-4 prmedication rmMed` + count + `">
<fieldset>
<label class="description" for="pmsd`+ count + `">Previous Medication #` + count + ` Start Date: </label>
<div>
<input type="date" class="form-control" id="pmsd`+ count + `"  name="pmsd[]">
</div>
</fieldset>
</li>

<li class="pdkse`+ count + ` col-md-4 prmedication rmMed` + count + `">
<fieldset>
<label class="pmed`+ count + `">Previous Medication #` + count + ` End Date: </label>
<div>
<input type="date" class="form-control" id="pmed`+ count + `"  name="pmed[]" placeholder="Previous Medication #` + count + ` End Date">
</div>
</fieldset>
</li>

<li class="checkboxes prmedication rmMed`+ count + `">
<div>
<fieldset>
<span><input id="csephp`+ count + `" name="csephp[]" class="form-checkbox" type="checkbox" value="1" autocomplete="off">
<label class="choice" for="csephp`+ count + `">Confirm Start/End Date with Patient's Home Pharmacy</label>
</span>
</fieldset>
</div>
</li>

<li class="checkboxes prmedication rmMed`+ count + `">
<div>
<fieldset>
<span>
<input id="adpm`+ count + `" name="adpm[]" data-id="` + count + `" class="form-checkbox addpreviousMedication" type="checkbox" value="1" autocomplete="off">
<label class="choice" for="adpm`+ count + `">Add Additional Previous Medication #` + newcount + `</label>
</fieldset>
</div>
</li>
<li class="rmMed`+ count + `"><hr></hr></li>
<li class="checkboxes rmMed`+ count + ` hidden lastprmedication` + count + `"></li>`;

    return clonedFields;
}


// Add additional previous medication
// Remove additional previous medication when checkbox is unchecked
$(document).on("change", ".addpreviousMedication", function () {
    var medicationCount = $(this).attr("data-id");
    var isChecked = $(this).is(":checked");
    medicationCount++;
    if (isChecked) {
        if ($('.rmMed' + medicationCount).length > 0) {
            $(".rmMed" + medicationCount).show();
        } else {
            var xmedicationCount = medicationCount - 1;
            var clonedFields = cloneMedicationFields(medicationCount);
            $(clonedFields).insertAfter($(".lastprmedication" + xmedicationCount).prev());
        }
    } else {
        // Remove cloned fields if checkbox is unchecked
        $(".rmMed" + medicationCount).hide();
    }
});

$(document).on("click", '.pdkse', function () {
    var cl = $(this).attr('id');
    $('.' + cl).toggle();
});

function isFieldEmpty(field) {
    return $(field).val().trim() === "";
}
// Function to set input field red if invalid
function setFieldInvalid(field) {
    $(field).addClass('is-invalid');
}
// Function to reset field validation (remove red border)
function resetFieldValidation(field) {
    $(field).removeClass('is-invalid');
}
$("#updateWelcomeCall").on("click", function (e) {
    // Prevent form submission for validation

    let validationPassed = true; // Flag to track if validation passed

    // Reset validation classes before new validation
    resetFieldValidation('#pwkl');
    resetFieldValidation('#indication');
    resetFieldValidation('#oluse');
    if (isFieldEmpty('#pwkl')) {
        setFieldInvalid('#pwkl');
        validationPassed = false;
    }

    if (isFieldEmpty('#indication')) {
        setFieldInvalid('#indication');
        validationPassed = false;
    }

    if (isFieldEmpty('#oluse')) {
        setFieldInvalid('#oluse');
        validationPassed = false;
    }
});

var totalSteps = $(".steps li").length;
var currentPage = 1;
const searchParams = new URLSearchParams(window.location.search);
if (searchParams.get('token')) {
    currentPage = searchParams.get('token'); // price_descending
}

$(".steps li:nth-of-type(" + currentPage + ")").addClass("active");
if (currentPage == 3) {
    $(".steps li:nth-of-type(1)").addClass("active");
    $(".steps li:nth-of-type(2)").addClass("active");
}
if (currentPage == 2) {
    $(".steps li:nth-of-type(1)").addClass("active");
}
if (currentPage == 4) {
    $(".steps li:nth-of-type(1)").addClass("active");
    $(".steps li:nth-of-type(2)").addClass("active");
    $(".steps li:nth-of-type(3)").addClass("active");
}
$(".myContainer .form-container:nth-of-type(" + currentPage + ")").addClass("active");

$(".steps li").on("click", function () {
    var stepVal = $(this).find("span").text();
    $(this).prevAll().addClass("active");
    $(this).addClass("active");
    $(this).nextAll().removeClass("active");
    $(".myContainer .form-container").removeClass("active flipInX");
    $(".myContainer .form-container:nth-of-type(" + stepVal + ")").addClass(
        "active flipInX"
    );
});

$("#pharmacyType").on("change", function (e) {
    var pharmacyType=$(this).val();
    if(pharmacyType=='Rx Connect Specialty Pharmacy'){
        $('#pharmacyPhone').val('647.417.1123');
        $('#pharmacyFax').val('289.801.7194');
        $('#pharmacyName').val('Rx Connect Specialty Pharmacy');
    }
    else if(pharmacyType=='Rx Connect Pharmacy Solutions (Alberta)'){
        $('#pharmacyPhone').val('1.403.417.9123');
        $('#pharmacyFax').val('403.538.6402');
        $('#pharmacyName').val('Rx Connect Pharmacy Solutions (Alberta)');
    }else{
        $('#pharmacyPhone').val('');
        $('#pharmacyFax').val('');
        $('#pharmacyName').val('');
    }
});
$("#resetPhysician").on("click", function (e) {
    e.preventDefault();
    $('.customPhysician').hide();
    $('.physicianId').show();
    if ($('#physicianId').val() == 0) {
        $('#physicianId').val('');
        $('#physicianFirstName').val();
        $('#physicianLastName').val();
        $('#physicianAddress').val();
        $('#physicianPhone').val();
        $('#physicianEmail').val();
        $('#physicianFax').val();
        $('#hospital').val();
        $('#primarySpecialty').val();
        $('#physicianCity').val();
        $('#physicianProvince').val();
        $('#physicianPostalCode').val();
    }
});
$("#submitPhysician").on("click", function (e) {
    e.preventDefault();
    var formData = new FormData();
    var physicianFirstName = $('#physicianFirstName').val();
    var physicianLastName = $('#physicianLastName').val();
    var hospital = $('#hospital').val();
    var primarySpecialty = $('#primarySpecialty').val();
    var physicianAddress = $('#physicianAddress').val();
    var physicianCity = $('#physicianCity').val();
    var physicianProvince = $('#physicianProvince option:selected').val();
    var physicianPostalCode = $('#physicianPostalCode').val();

    var physicianPhone = $('#physicianPhone').val();
    var physicianEmail = $('#physicianEmail').val();
    var physicianFax = $('#physicianFax').val();
    formData.append('physicianFirstName', physicianFirstName);
    formData.append('physicianLastName', physicianLastName);
    formData.append('hospital', hospital);
    formData.append('primarySpecialty', primarySpecialty);
    formData.append('physicianAddress', physicianAddress);
    formData.append('physicianCity', physicianCity);
    formData.append('physicianProvince', physicianProvince);
    formData.append('physicianPostalCode', physicianPostalCode);
    formData.append('physicianPhone', physicianPhone);
    formData.append('physicianEmail', physicianEmail);
    formData.append('physicianFax', physicianFax);
    $.ajax({
        url: 'ajax_call.php?ajaxcall=addPhysician', // Replace with your server endpoint
        type: 'POST',
        data: formData,
        processData: false,  // Required to prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        success: function (response) {
            // Handle successful response
            $('.physicianId').show();
            $('.customPhysician').hide();
            var o = new Option(physicianName, response);
            /// jquerify the DOM object 'o' so we can use the html method
            $(o).html(physicianName);
            $("#physicianId").append(o);
            $('#physicianId').val(response);

            toastr.success('Physician Added Successfully');
            // Optionally, remove the button or update the UI
            // $(this).closest('.document-item').remove();
        },
        error: function (xhr, status, error) {
            // Handle error response
            alert('Error Adding Physician: ' + error);
        }
    });
});
$('#pstatus').change(function () {
    var statusID = $(this).val();

    if (statusID) {
        // Enable substatus dropdown and clear previous options
        $('#substatus').prop('disabled', false).empty().append('<option value="">Select Substatus</option>');

        $.ajax({
            url: 'ajax_call.php?ajaxcall=fetch_patient_substatus', // Backend script to fetch substatus based on statusID
            type: 'GET',
            data: { statusID: statusID },
            dataType: 'json',
            success: function (data) {
                $.each(data, function (key, substatus) {
                    $('#substatus').append($('<option>', {
                        value: substatus.SubstatusID,
                        text: substatus.SubstatusName
                    }));
                });
            }
        });
    } else {
        // Disable substatus dropdown if no status selected
        $('#substatus').prop('disabled', true).empty().append('<option value="">Select Substatus</option>');
    }
});
$('#getActivityInfo').on("click", function (e) {
    $('.popupActivityStatus').show();
});
$('#patientTypeClose').on("click", function (e) {
 $('.popupActivityStatus').hide();
});
$('#getWelcomeActivityInfo').on("click", function (e) {
    $('.popupWelcomeCallActivityStatus').show();
});
$('#welcomeTypeClose').on("click", function (e) {
 $('.popupWelcomeCallActivityStatus').hide();
});
// $('#indication').change(function() {
//     var indication = $(this).val();

//     // Hide all sections initially
//     $('#ad-questionnaire').hide();
//     $('#asthma-questionnaire').hide();
//     $('#pn-questionnaire').hide();

//     // Show the relevant section based on indication
//     if (indication === 'ad') {
//         $('#ad-questionnaire').show();
//     } else if (indication === 'asthma') {
//         $('#asthma-questionnaire').show();
//     } else if (indication === 'pn') {
//         $('#pn-questionnaire').show();
//     }
// });
$('#indication').change(function() {
    var indications = $(this).val(); // Get selected values (array in case of multiple)

    // Hide all sections initially
    $('#ad-questionnaire').hide();
    $('#asthma-questionnaire').hide();
    $('#CRSwNP-questionnaire').hide();

    // Loop through the selected indications and show relevant sections
    if (indications) {
        indications.forEach(function(indication) {
            if (indication === 'AD' || indication === 'PN') {
                $('#ad-questionnaire').show();
            }
            if (indication === 'Asthma') {
                $('#asthma-questionnaire').show();
            }
            if (indication === 'CRSwNP') {
                $('#CRSwNP-questionnaire').show();
            }
        });
    }
});
$("#physicianId").on("change", function () {
    var id = $(this).val();
    if (id == 0 && id != "") {
        $('.customPhysician').show();
        $('.physicianId').hide();
        $('#physicianFirstName').val('');
        $('#physicianLastName').val('');
        $('#physicianAddress').val('');
        $('#physicianPhone').val('');
        $('#physicianEmail').val(''); 
        $('#physicianFax').val('');
        $('#hospital').val('');
        $('#primarySpecialty').val('');
        $('#physicianCity').val('');
        $('#physicianProvince').val('');
        $('#physicianPostalCode').val('');
    } else {
        $.ajax({
            url: 'ajax_call.php?ajaxcall=getPhysician', // Replace with your server endpoint
            type: 'POST',
            data: { physicianId: id },
            dataType: 'json',
            success: function (response) {

                console.log(response.streetAddress);
                // Handle successful response
                $('#physicianAddress').val(response.streetAddress);
                $('#physicianPhone').val(response.phone);
                $('#physicianEmail').val(response.email);

                $('#hospital').val(response.hospital);
                $('#primarySpecialty').val(response.primarySpecialty);
                $('#physicianFax').val(response.fax);
                $('#physicianCity').val(response.city);
                $('#physicianProvince').val(response.province);
                $('#physicianPostalCode').val(response.postalCode);

                // Optionally, remove the button or update the UI
                // $(this).closest('.document-item').remove();
            },
            error: function (xhr, status, error) {
                // Handle error response
                alert('Error Adding Physician: ' + error);
            }
        });
    }
});
$("input[name='dphsp']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.secondaryShow').removeClass('hidden');
    } else {
        $('.secondaryShow').addClass('hidden');
    }
});
$("input[name='dphsp_tertiary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.tertiaryShow').removeClass('hidden');
    } else {
        $('.tertiaryShow').addClass('hidden');
    }
});
$("input[name='dphsp_quaternary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.quaternaryShow').removeClass('hidden');
    } else {
        $('.quaternaryShow').addClass('hidden');
    }
});
$("input[name='sarequired']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.sarequiredshow').removeClass('hidden');
    } else {
        $('.sarequiredshow').addClass('hidden');
    }
});
$("input[name='sarequired_secondary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.sarequired_secondaryshow').removeClass('hidden');
    } else {
        $('.sarequired_secondaryshow').addClass('hidden');
    }
});
$("input[name='sarequired_tertiary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.sarequired_tertiaryShow').removeClass('hidden');
    } else {
        $('.sarequired_tertiaryShow').addClass('hidden');
    }
});
$("input[name='sarequired_quaternary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Y') {
        $('.sarequired_quaternaryShow').removeClass('hidden');
    } else {
        $('.sarequired_quaternaryShow').addClass('hidden');
    }
});
$("input[name='cardholder']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Self') {
        $('.cardholderShow').addClass('hidden');
    } else {
        $('.cardholderShow').removeClass('hidden');
    }
});
$("input[name='cardholder_secondary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Self') {
        $('.cardholder_secondaryShow').addClass('hidden');
    } else {
        $('.cardholder_secondaryShow').removeClass('hidden');
    }
});
$("input[name='cardholder_tertiary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Self') {
        $('.cardholder_tertiaryShow').addClass('hidden');
    } else {
        $('.cardholder_tertiaryShow').removeClass('hidden');
    }
});
$("input[name='cardholder_quaternary']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == 'Self') {
        $('.cardholder_quaternaryShow').addClass('hidden');
    } else {
        $('.cardholder_quaternaryShow').removeClass('hidden');
    }
});
$("input[name='injTraLoc']").on("click", function () {
    //alert($(this).val());
    if ($(this).val() == '1') {
        $('.virtualShow').removeClass('hidden');
        if ($(".clinicShow.hidden")[0]) { } else { $('.clinicShow').addClass('hidden'); }
    } else if ($(this).val() == '2') {
        $('.clinicShow').removeClass('hidden');
        if ($(".virtualShow.hidden")[0]) { } else { $('.virtualShow').addClass('hidden'); }
    } else {
        if ($(".virtualShow.hidden")[0]) { } else { $('.virtualShow').addClass('hidden'); }
        if ($(".clinicShow.hidden")[0]) { } else { $('.clinicShow').addClass('hidden'); }
    }
});

$(".form-container").on("click", ".next", function (e) {
    // e.preventDefault();
    // if($(this).attr('data-id')==1){
    //     $('button[name="savepatientdetials"]').click();
    // }
    $(".steps li")
        .eq($(this).parents(".form-container").index() + 1)
        .addClass("active");
    $(this)
        .parents(".form-container")
        .removeClass("active")
        .next()
        .addClass("active flipInX");
});

$(".form-container").on("click", ".back", function () {
    $(".steps li")
        .eq($(this).parents(".form-container").index() - totalSteps)
        .removeClass("active");
    $(this)
        .parents(".form-container")
        .removeClass("active flipInX")
        .prev()
        .addClass("active flipInY");
});

// document.addEventListener('DOMContentLoaded', function () {
//     const addRowBtn = document.getElementById('addRowBtn');
//     const fileInputsContainer = document.getElementById('fileInputs');
//     const addRowBtn1 = document.getElementById('addRowBtn1');
//     const fileInputsContainer1 = document.getElementById('fileInputs1');
//     const addRowBtn2 = document.getElementById('addRowBtn2');
//     const fileInputsContainer2 = document.getElementById('fileInputs2');
//     addRowBtn.addEventListener('click', function () {
//         const fileRow = document.createElement('div');
//         fileRow.classList.add('row');
//         fileRow.innerHTML = `
//       <div class="col-md-4">
//           <div class="form-group fileRow">
//                 <label for="paymentId">File Name (Title)</label>
//                 <select name="fileTitle[]" class="form-control">
//                 <option disabled selected>Select File Name</option>
//                 <option>SA & PA [special authorization & prior authorization (signed by MD or not)]</option>
//                 <option>LU code</option>
//                 <option>Medical clearance</option>
//                 <option>TB test results</option>
//                 <option>Lab requisitions</option>
//                 <option>EAP requests, approvals, denials, & requests for additional information</option>
//                 <option>Consult/clinical notes</option>
//                 <option>PSP packages</option>
//                 <option>PSP requesting copy of current rx</option>
//                 <option>Compass packages</option>
//                 <option>MD note</option>
//                 <option>Prescription</option>
//                 <option>PIR</option>
//                 <option>PSP note</option>
//                 <option>TDM requisition</option>
//           </select>
//           </div>
//       </div>
//       <div class="col-md-4">
//           <div class="fileRow form-group">
//                 <label for="paymentId">File Attachment</label> 
//                 <input type="file" name="files[]" class="form-control fileInput">
//           </div>
//       </div>`;
//         fileInputsContainer.appendChild(fileRow);
//     });

//     addRowBtn1.addEventListener('click', function () {
//         const fileRow = document.createElement('div');
//         fileRow.classList.add('row');
//         fileRow.innerHTML = `
// <div class="col-md-4">
// <input type="file" name="pmmd[]" multiple class="form-control fileInput">
// </div>
// `;
//         fileInputsContainer1.appendChild(fileRow);
//     });

//     addRowBtn2.addEventListener('click', function () {
//         const fileRow = document.createElement('div');
//         fileRow.classList.add('row');
//         fileRow.innerHTML = `
// <div class="col-md-4">
// <input type="file" name="screeningDocs[]" multiple class="form-control fileInput">
// </div>
// `;
//         fileInputsContainer2.appendChild(fileRow);
//     });
// });

document.addEventListener('DOMContentLoaded', function () {
    const addRowBtn = document.getElementById('addRowBtn');
    const fileInputsContainer = document.getElementById('fileInputs');
    const addRowBtn1 = document.getElementById('addRowBtn1');
    const fileInputsContainer1 = document.getElementById('fileInputs1');
    const addRowBtn2 = document.getElementById('addRowBtn2');
    const fileInputsContainer2 = document.getElementById('fileInputs2');

    function getFileTitleOptions() {
        const titles = window.fileTitles || [];
        let options = '<option disabled selected>Select File Name</option>';
        titles.forEach(function(title) {
            options += `<option>${title}</option>`;
        });
        return options;
    }

    addRowBtn.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <div class="form-group fileRow">
                    <label for="fileTitle">File Name (Title)</label>
                    <select name="fileTitle[]" class="form-control">
                        ${getFileTitleOptions()}
                    </select>
                </div>
            </div>
            <div class="col-md-4">
                <div class="fileRow form-group">
                    <label for="files[]">File Attachment</label>
                    <input type="file" name="files[]" class="form-control fileInput">
                </div>
            </div>`;
        fileInputsContainer.appendChild(fileRow);
    });

    addRowBtn1.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <input type="file" name="pmmd[]" multiple class="form-control fileInput">
            </div>`;
        fileInputsContainer1.appendChild(fileRow);
    });

    addRowBtn2.addEventListener('click', function () {
        const fileRow = document.createElement('div');
        fileRow.classList.add('row');
        fileRow.innerHTML = `
            <div class="col-md-4">
                <input type="file" name="screeningDocs[]" multiple class="form-control fileInput">
            </div>`;
        fileInputsContainer2.appendChild(fileRow);
    });
});