$(document).ready(function () {
    $('.dailysummaryreport').click();
    debugger;
    if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
        $('#dailySummaryTab').show();           
        $('#showdoc').show();
        $('#branch_div').show();
            LoadBranch();
    }
    else {
        //$('#dailySummaryTab').show();
    }
    var val = "0";
    appointment_list_cur_month(val);
   
});
function LoadBranch() {
    document.getElementById("pkg_branch_id").innerHTML = null;
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    $('#pkg_branch_id').append(default_opt + SubDepartment);
                    if ($('#hiddenRole_id').val() == 1) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
$('#pkg_branch_id').change(function () {
    var val = "#SelDoctorapp";
    doctor_list(val);
})

$('#SelDoctorapp').change(function () {
    var val = "0";
    appointment_list_cur_month(val);
});

$('#pres_report').click(function () {
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) {
        }
        else {
            $('#showdocmed').show();
            var val = "#SelDoctormed";
            doctor_list(val);
        }
    var val = "0";
    medicine_list_cur_month(val);
});

$('#SelDoctormed').change(function () {
    var val = "0";
    medicine_list_cur_month(val);
});

$('#lab_report').click(function () {
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) {
    }
    else {
        $('#showdoclab').show();
        var val = "#SelDoctorlab";
        doctor_list(val);
    }
    var val = "0";
    lab_list_cur_month(val);
});

$('#SelDoctorlab').change(function () {
    var val = "0";
    lab_list_cur_month(val);
});
$('#rev_report').click(function () {
    debugger;
    if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
        $('#showdocrev').show();
        var val = "#SelDoctorrev";
        doctor_list(val);
    }
    var val = "0";
    revenue_list_cur_month(val);
});

$('#SelDoctorrev').change(function () {
    var val = "0";
    revenue_list_cur_month(val);
});

$('#dailySummaryTab').click(function () {
    Daily_SummaryList();
    var val = "#selSummaryDoctor";
    doctor_list(val);

    debugger;
    var DoctorData = {
        Indicator_id: "SL"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/mobile_speciality_details',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var b = data1.list;
                    var SelRole = '';
                    $('#selSummarySpeciality').empty();
                    var default_opt = '<option value="">--Select--</option>';
                    $.each(b, function (i, emp) {
                        SelRole = SelRole + '<option value="' + emp.medway_speciality_id + '">' + emp.speciality_name + '</option>';
                    });
                    $('#selSummarySpeciality').html(default_opt + SelRole);
                }
                else {
                    console.log(data);
                }
            }
        }
    });

});

function doctor_list(val) {
    var DoctorData = {
        Dml_Indicator: "DL",
        user_role: $('#hiddenRole_id').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Prescription_Settings/casesheet_configurations',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            var data = data2.data;
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = data;
                console.log(data1);
                var b = data1.Table;
                var tr = '';
                var SelRole = '';
                $(val).empty();
                var default_opt = '<option value="">--Select Doctor--</option>';
                $.each(b, function (i, emp) {
                    SelRole = SelRole + '<option value="' + emp.doctor_id + '">' + emp.doctor_name + '</option>';
                });
                $(val).html(default_opt + SelRole);
            }
        }
    });
}
//appoiment  report selections filter

$('#phyapp,#vidapp,#smsapp,#bookapp,#visitapp,#failapp,#webapp,#mobapp,#chatapp').click(function () {
    app_selected_options();
});


function app_selected_options() {
    $('#appsellist').empty();
    debugger;
    if ($.trim($('#fromdatetodate').val()).length > 0) {
        var date = $('#fromdatetodate').val().split('-');
        var from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        var to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        var date_merge = from_date + " to " + to_date;
        $('#appsellist').append('<li class="label label-primary"> <span class="head-li-filter">visited Date : ' + date_merge + ' </span> <i class="fa fa-times"  onclick = app_sel_del(' + '1' + ')></i> </li>');
    }
    if ($.trim($('#fromdatetodatenextapp').val()).length > 0) {
        debugger;
        var next_date, next_from_date, next_to_date, next_date_merge;
        next_date = $('#fromdatetodatenextapp').val().split('-');
        next_from_date = next_date[0];
        next_from_date = next_from_date.split("/").reverse().join("-");
        next_to_date = next_date[1];
        next_to_date = next_to_date.split("/").reverse().join("-");
        next_date_merge = next_from_date + " to " + next_to_date;
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Next visit Date : ' + next_date_merge + '</span> <i class="fa fa-times" onclick = app_sel_del(' + '2' + ')></i> </li>');
    }
    if ($('#phyapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Physical</span> <i class="fa fa-times" onclick = app_sel_del(' + '3' + ')></i> </li>');
    }
    if ($('#vidapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Video</span> <i class="fa fa-times" onclick = app_sel_del(' + '4' + ')></i> </li>');
    }
    if ($('#smsapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">SMS</span> <i class="fa fa-times" onclick = app_sel_del(' + '5' + ')></i> </li>');
    }
    if ($('#bookapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Booked</span> <i class="fa fa-times" onclick = app_sel_del(' + '6' + ')></i> </li>');
    }
    if ($('#visitapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Visited</span> <i class="fa fa-times" onclick = app_sel_del(' + '7' + ')></i> </li>');
    }
    if ($('#failapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Failed to visit</span> <i class="fa fa-times" onclick = app_sel_del(' + '8' + ')></i> </li>');
    }
    if ($('#webapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Web</span> <i class="fa fa-times" onclick = app_sel_del(' + '9' + ')></i> </li>');
    }
    if ($('#mobapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">Mobile</span> <i class="fa fa-times" onclick = app_sel_del(' + '10' + ')></i> </li>');
    }
    if ($('#chatapp').prop("checked") == true) {
        $('#appsellist').append('<li class="label label-primary"><span class="head-li-filter">ChatBot</span> <i class="fa fa-times" onclick = app_sel_del(' + '11' + ')></i> </li>');
    }
}


function app_sel_del(val) {
    if (val == "1") $('#fromdatetodate').val('');
    if (val == "2") $('#fromdatetodatenextapp').val('');
    if (val == "3") $('#phyapp').prop("checked", false);
    if (val == "4") $('#vidapp').prop("checked", false);
    if (val == "5") $('#smsapp').prop("checked", false);
    if (val == "6") $('#bookapp').prop("checked", false);
    if (val == "7") $('#visitapp').prop("checked", false);
    if (val == "8") $('#failapp').prop("checked", false);
    if (val == "9") $('#webapp').prop("checked", false);
    if (val == "10") $('#mobapp').prop("checked", false);
    if (val == "11") $('#chatapp').prop("checked", false);
    app_selected_options();
}

$('#btnreportfilter').click(function () {
    debugger;
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {       
    }
    else {
        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
            if ($.trim($('#SelDoctorapp').val()).length == "") {
                $('#PSelHospitalapp').show();
                $('#PSelHospitalapp').fadeOut(8000);
                $('#PSelHospitalapp').html('Please Select Doctor');
                $('#SelDoctorapp').focus();
                $('#SelDoctorapp').val('');
                return false;
            }
        }
    }

    if ($.trim($('#fromdatetodate').val()).length == "") {
        $('#Pfromdatetodate').show();
        $('#Pfromdatetodate').fadeOut(8000);
        $('#Pfromdatetodate').html('Please Select Date');
        $('#fromdatetodate').focus();
        $('#fromdatetodate').val('');
        return false;
    }
    if ($('#fromdatetodate').val().length > 0) {
        $('#app_table_list').addClass('us-db-loader-appoinments');
        var val = "1";
        appointment_list_cur_month(val);
    }
});

//appoiment  report selections filter ended



//medicine report selected options code


$('#med_name_report').change(function () {
    med_sel_options();
});

function med_sel_options() {
    $('#medsellist').empty();
    var medicine_name, date, from_date, to_date, med_date;
    if ($.trim($('#fromdatetodatepres').val()).length > 0) {
        date = $('#fromdatetodatepres').val().split('-');
        from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        med_date = from_date + " to " + to_date;
        $('#medsellist').append('<li> <span class="head-li-filter">Prescribed date: ' + med_date + '</span> <i class="fa fa-times" onclick = med_sel_del(' + '1' + ')></i> </li>');
    }
    if ($.trim($('#med_name_report').val()).length > 0) {
        medicine_name = $('#med_name_report').val();
        $('#medsellist').append('<li> <span class="head-li-filter"> ' + medicine_name + ' </span> <i class="fa fa-times" onclick = med_sel_del(' + '2' + ')></i> </li>');
    }
}

function med_sel_del(val) {
    if (val == "1") $('#fromdatetodatepres').val('');
    if (val == "2") $('#med_name_report').val('');
    med_sel_options();
}


$('#btnmedreportfilter').click(function () {
    debugger;
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {

    }
    else {
        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
            if ($.trim($('#SelDoctormed').val()).length == "" || $.trim($('#SelDoctormed').val()) == 0) {
                $('#PSelHospitalmed').show();
                $('#PSelHospitalmed').fadeOut(8000);
                $('#PSelHospitalmed').html('Please Select Doctor');
                $('#SelDoctormed').focus();
                $('#SelDoctormed').val('');
                return false;
            }
        }
    }
    if ($.trim($('#fromdatetodatepres').val()).length == "") {
        $('#Pfromdatetodatepres').show();
        $('#Pfromdatetodatepres').fadeOut(8000);
        $('#Pfromdatetodatepres').html('Please Select Date');
        $('#fromdatetodatepres').focus();
        $('#fromdatetodatepres').val('');
        return false;
    }
    if ($.trim($('#fromdatetodatepres').val()).length > 0) {
        $('#med_table_list').addClass('us-db-loader-appoinments');
        var val = "1";
        medicine_list_cur_month(val);
    }
});

//medicine report selected options code ended


//lab options selected code started

$('#lab_name_report').change(function () {
    lab_sel_options();
});


function lab_sel_options() {
    $('#labsellist').empty();
    var lab_name, date, from_date, to_date, lab_date, date1, sug_from_date, Sug_to_date, lab_sug_date;
    if ($.trim($('#fromdatetodatelab').val()).length > 0) {
        date = $('#fromdatetodatelab').val().split('-');
        from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        lab_date = from_date + " to " + to_date;
        $('#labsellist').append('<li> <span class="head-li-filter">Lab Dates : ' + lab_date + ' </span> <i class="fa fa-times"  onclick = lab_sel_del(' + '1' + ')></i> </li>');
    }
    if ($.trim($('#fromdatetodatelabsugg').val()).length > 0) {
        date1 = $('#fromdatetodatelabsugg').val().split('-');
        sug_from_date = date1[0];
        sug_from_date = sug_from_date.split("/").reverse().join("-");
        Sug_to_date = date1[1];
        Sug_to_date = Sug_to_date.split("/").reverse().join("-");
        lab_sug_date = sug_from_date + " to " + Sug_to_date;
        $('#labsellist').append('<li> <span class="head-li-filter">Lab Suggestion Date : ' + lab_sug_date + ' </span> <i class="fa fa-times"  onclick = lab_sel_del(' + '2' + ')></i> </li>');
    }
    if ($.trim($('#lab_name_report').val()).length > 0) {
        lab_name = $('#lab_name_report').val();
        $('#labsellist').append('<li> <span class="head-li-filter">' + lab_name + ' </span> <i class="fa fa-times"  onclick = lab_sel_del(' + '3' + ')></i> </li>');
    }
}

function lab_sel_del(val) {
    if (val == "1") $('#fromdatetodatelab').val('');
    if (val == "2") $('#fromdatetodatelabsugg').val('');
    if (val == "3") $('#lab_name_report').val('');
    lab_sel_options();
}

$('#btnlabreportfilter').click(function () {
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {

    }
    else {
        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
            if ($.trim($('#SelDoctorlab').val()).length == "" || $.trim($('#SelDoctorlab').val()) == 0) {
                $('#PSelHospitallab').show();
                $('#PSelHospitallab').fadeOut(8000);
                $('#PSelHospitallab').html('Please Select Doctor');
                $('#SelDoctorlab').focus();
                $('#SelDoctorlab').val('');
                return false;
            }
        }
    }
    if (($.trim($('#fromdatetodatelab').val()).length > 0 || $.trim($('#fromdatetodatelabsugg').val()).length > 0 || $.trim($('#lab_name_report').val()).length > 0))
    {
        $('#lab_table_list').addClass('us-db-loader-appoinments');
        var val = "1";
        lab_list_cur_month(val);
    }
    else 
    {
        toastr.warning("Select Any one of the Filter");
    }
    
});

//lab options selected code end

//report selected options code start

$('#rev_pending,#rev_partial,#rev_paid,#rev_chat,#rev_lab,#rev_consul,#rev_app,#rev_prepaid,#rev_postpaid,#rev_cash,#rev_card,#rev_gatway').change(function () {
    rev_sel_options();
});

$('#pat_rev_report').change(function () {
    rev_sel_options();
});

function rev_sel_options() {
    $('#revsellist').empty();
    if ($.trim($('#fromdatetodaterevenue').val()).length > 0) {
        var date = $('#fromdatetodaterevenue').val().split('-');
        var from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        var to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        var rev_date = from_date + " to " + to_date;
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Invoice Date : ' + rev_date + ' </span> <i class="fa fa-times"  onclick = rev_sel_del(' + '1' + ')></i> </li>');
    }
    if ($('#rev_pending').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Pending Payment</span> <i class="fa fa-times" onclick = rev_sel_del(' + '2' + ')></i> </li>');
    }
    if ($('#rev_partial').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Partial Payment</span> <i class="fa fa-times" onclick = rev_sel_del(' + '3' + ')></i> </li>');
    }
    if ($('#rev_paid').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Payment Completed</span> <i class="fa fa-times" onclick = rev_sel_del(' + '4' + ')></i> </li>');
    }
    if ($('#rev_chat').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Chat</span> <i class="fa fa-times" onclick = rev_sel_del(' + '5' + ')></i> </li>');
    }
    if ($('#rev_lab').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Lab</span> <i class="fa fa-times" onclick = rev_sel_del(' + '6' + ')></i> </li>');
    }
    if ($('#rev_consul').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Consultation</span> <i class="fa fa-times" onclick = rev_sel_del(' + '7' + ')></i> </li>');
    }
    if ($('#rev_app').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Appointment</span> <i class="fa fa-times" onclick = rev_sel_del(' + '8' + ')></i> </li>');
    }
    if ($('#rev_prepaid').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Prepaid</span> <i class="fa fa-times" onclick = rev_sel_del(' + '9' + ')></i> </li>');
    }
    if ($('#rev_postpaid').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Postpaid</span> <i class="fa fa-times" onclick = rev_sel_del(' + '10' + ')></i> </li>');
    }
    if ($('#rev_cash').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Cash</span> <i class="fa fa-times" onclick = rev_sel_del(' + '11' + ')></i> </li>');
    }
    if ($('#rev_card').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Card</span> <i class="fa fa-times" onclick = rev_sel_del(' + '12' + ')></i> </li>');
    }
    if ($('#rev_gatway').prop("checked") == true) {
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter">Payment Gateway</span> <i class="fa fa-times" onclick = rev_sel_del(' + '13' + ')></i> </li>');
    }
    if ($.trim($('#pat_rev_report').val()).length > 0) {
        name = $('#pat_rev_report').val();
        $('#revsellist').append('<li class="label label-primary"> <span class="head-li-filter"> ' + name + ' </span> <i class="fa fa-times" onclick = rev_sel_del(' + '14' + ')></i> </li>');
    }
}


function rev_sel_del(val) {
    if (val == "1") $('#fromdatetodaterevenue').val('');
    if (val == "2") $('#rev_pending').prop("checked", false);
    if (val == "3") $('#rev_partial').prop("checked", false);
    if (val == "4") $('#rev_paid').prop("checked", false);
    if (val == "5") $('#rev_chat').prop("checked", false);
    if (val == "6") $('#rev_lab').prop("checked", false);
    if (val == "7") $('#rev_consul').prop("checked", false);
    if (val == "8") $('#rev_app').prop("checked", false);
    if (val == "9") $('#rev_prepaid').prop("checked", false);
    if (val == "10") $('#rev_postpaid').prop("checked", false);
    if (val == "11") $('#rev_cash').prop("checked", false);
    if (val == "12") $('#rev_card').prop("checked", false);
    if (val == "13") $('#rev_gatway').prop("checked", false);
    if (val == "14") $('#pat_rev_report').val('');
    rev_sel_options();
}


$('#btnrevreportfilter').click(function () {
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {

    }
    else {
        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
            if ($.trim($('#SelDoctorrev').val()).length == "" || $.trim($('#SelDoctorrev').val()) == 0) {
                $('#PSelHospitalrev').show();
                $('#PSelHospitalrev').fadeOut(8000);
                $('#PSelHospitalrev').html('Please Select Doctor');
                $('#SelDoctorrev').focus();
                $('#SelDoctorrev').val('');
                return false;
            }
        }
    }

    if ($.trim($('#fromdatetodaterevenue').val()).length == "") {
        $('#Pfromdatetodaterevenue').show();
        $('#Pfromdatetodaterevenue').fadeOut(8000);
        $('#Pfromdatetodaterevenue').html('Please Select Date');
        $('#fromdatetodaterevenue').focus();
        $('#fromdatetodaterevenue').val('');
        return false;
    }
    if ($('#fromdatetodaterevenue').val().length > 0) {
        $('#rev_table_list').addClass('us-db-loader-appoinments');
        var val = "1";
        revenue_list_cur_month(val);
    }
});

//report selected options code end


//appointment report code started

function appointment_list_cur_month(val) {
    var doc_id = '';
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) {
        doc_id = $('#HiddenDoctorID').val();
    }
    else { doc_id = $('#SelDoctorapp').val(); }

    if (val == 0) {
        var appointment_data = {
            indicator_id: 'AL',
            doctor_id: doc_id
        }
    }
    else {
        var date = $('#fromdatetodate').val().split('-');
        var from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        var to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        var physical = '', sms = '', video = '', bookslot = '', visited = '', noshow = '', web = '', chat = '', mobile = '', where_condition = '';
        if ($('#phyapp').prop("checked") == true) {
            physical = 1;
        }
        if ($('#vidapp').prop("checked") == true) {
            video = 2;
        }
        if ($('#smsapp').prop("checked") == true) {
            sms = 3;
        }

        if ($('#bookapp').prop("checked") == true) {
            bookslot = 1;
        }
        if ($('#visitapp').prop("checked") == true) {
            visited = 4;
        }
        if ($('#failapp').prop("checked") == true) {
            noshow = 1;
        }

        if ($('#webapp').prop("checked") == true) {
            web = $('#HiddenDoctorID').val();
        }
        if ($('#mobapp').prop("checked") == true) {
            mobile = '%PCH%';
        }
        if ($('#chatapp').prop("checked") == true) {
            chat = 'CHATBOT';
        }

        if (physical != '' && video != '' && sms != '') {
            where_condition = where_condition + ' and (das.appointment_type = ' +physical + ' or das.appointment_type = ' + video + ' or das.appointment_type = ' + sms + ')';
        }
        else if (physical != '' && video != '') {
            where_condition = where_condition + ' and (das.appointment_type = ' + physical + ' or das.appointment_type = ' + video + ')';
        }
        else if (physical != '' && sms != '') {
            where_condition = where_condition + ' and (das.appointment_type = ' + physical + ' or das.appointment_type = ' + sms + ')';
        }
        else if (video != '' && sms != '') {
            where_condition = where_condition + ' and (das.appointment_type = ' + video + ' or das.appointment_type = ' + sms + ')';
        }
        else if (physical != '') {
            where_condition = where_condition + ' and das.appointment_type = ' + physical;
        }
        else if (video != '') {
            where_condition = where_condition + ' and das.appointment_type = ' + video;
        }
        else if (sms != '') {
            where_condition = where_condition + ' and das.appointment_type = ' + sms;
        }



        if (bookslot != '' && visited != '' && noshow != '') {
            where_condition = where_condition + " and ((das.doctor_appointment_slot_status = " + bookslot + " and (das.check_status !=  '6 ' or das.check_status is NULL)) or (das.doctor_appointment_slot_status = " + visited + " or das.doctor_appointment_slot_status = '7 ' ) or (das.doctor_appointment_slot_status = " + noshow + " and das.check_status = '6 ' ))";
        }
        else if (bookslot != '' && visited != '') {
            where_condition = where_condition + " and ((das.doctor_appointment_slot_status = " + bookslot + " and (das.check_status !=  '6 ' or das.check_status is NULL)) or (das.doctor_appointment_slot_status = " + visited + " or das.doctor_appointment_slot_status = '7 ' ))";
        }
        else if (bookslot != '' && noshow != '') {
            where_condition = where_condition + " and ((das.doctor_appointment_slot_status = " + bookslot + " and (das.check_status !=  '6 ' or das.check_status is NULL)) or (das.doctor_appointment_slot_status = " + noshow + " and das.check_status = '6 ' ))";
        }
        else if (visited != '' && noshow != '') {
            where_condition = where_condition + " and ((das.doctor_appointment_slot_status = " + visited + " or das.doctor_appointment_slot_status = '7 ' ) or (das.doctor_appointment_slot_status = " + noshow + "and das.check_status = '6 ' ))";
        }
        else if (bookslot != '') {
            where_condition = where_condition + " and (das.doctor_appointment_slot_status = " + bookslot + " and (das.check_status !=  '6 ' or das.check_status is NULL))";
        }
        else if (visited != '') {
            where_condition = where_condition + " and (das.doctor_appointment_slot_status = " + visited + " or das.doctor_appointment_slot_status = '7 ' )";
        }
        else if (noshow != '') {
            where_condition = where_condition + " and (das.doctor_appointment_slot_status = " + noshow + " and das.check_status = '6 ' )";
        }



        if (web != '' && mobile != '' && chat != '') {
            where_condition = where_condition + " and (das.created_by = '" + web + "' or das.created_by like '" + mobile + "' or das.created_by = '" + chat + "')";
        }
        else if (web != '' && mobile != '') {
            where_condition = where_condition + " and (das.created_by = '" + web + "' or das.created_by like '" + mobile + "')";
        }
        else if (web != '' && chat != '') {
            where_condition = where_condition + " and (das.created_by = '" + web + "' or das.created_by = '" + chat + "')";
        }
        else if (mobile != '' && chat != '') {
            where_condition = where_condition + " and (das.created_by like '" + mobile + "' or das.created_by ='" + chat + "')";
        }
        else if (web != '') {
            where_condition = where_condition + " and das.created_by = '" + web + "'";
        }
        else if (mobile != '') {
            where_condition = where_condition + " and das.created_by like '" + mobile + "'";
        }
        else if (chat != '') {
            where_condition = where_condition + " and das.created_by ='" + chat + "'";
        }

        if ($.trim($('#fromdatetodatenextapp').val()).length > 0) {
            var next_date = $('#fromdatetodatenextapp').val().split('-');
            var next_from_date = next_date[0];
            next_from_date = next_from_date.split("/").reverse().join("-");
            var next_to_date = next_date[1];
            next_to_date = next_to_date.split("/").reverse().join("-");
            where_condition = where_condition + " and CONVERT(date,(vr.next_appointment_date)) between '" + next_from_date + "' and  '" + next_to_date + "' ";
        }

        where_condition = " and CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' " + where_condition;
        console.log(where_condition);
        var appointment_data = {
            doctor_id: doc_id,
            indicator_id: 'AFL',
            from_date: from_date,
            to_date: to_date,
            where_condition: where_condition
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_appointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            
            table_appointment(data);
        },
    });
}

function table_appointment(data) {
    debugger;
    if (jQuery.isEmptyObject((data)) || data.length == "0") {
        tr = $('<table class="table-responsive table table-condensed body-borderless table_borderless" id="appointmentlist" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Details</th><th>Appointment Date</th><th>Next Visit Date</th><th>Appointment Mode</th><th>Appointment Type</th><th>Status</th></tr></thead><tbody>");
        tr.append("</tbody>");
    }
    else if (data.length > 0) {
        debugger;
        var data2 = JSON.parse(data);
        var data1 = data2.data;
        $('#app_table_list').empty();
        var j = 0;
        //var data1 = JSON.parse(data);
        var b = data1.Table;
        tr = $('<table class="table-responsive table table-bordered table-striped" id="appointmentlist" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Details</th><th>Appointment Date</th><th>Next Visit Date</th><th>Appointment Mode</th><th>Appointment Type</th><th>Status</th></tr></thead><tbody>");
        $('#app_table_list').removeClass('us-db-loader-appoinments');
        var doctorid = $('#HiddenDoctorID').val();
        $.each(b, function (i, emp) {
            j++;
            var phone_number = "-", app_type = "-", doctor_patient_id = " ", appointment_date = "-", created_by = "-", status = "-", next_visit_date = "-";
            if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                phone_number = "-"
            }
            else {
                phone_number = emp.phone_number_1;
            }
            if (emp.appointment_type == "1") {
                app_type = "Walkin";
            }
            else if (emp.appointment_type == "2") {
                app_type = "Video";
            }
            else {
                app_type = "SMS";
            }
            if (emp.doctor_patient_id == null || emp.doctor_patient_id == '') {
                doctor_patient_id = emp.patient_id;
            }
            else {
                doctor_patient_id = emp.patient_id + '/' + emp.doctor_patient_id;
            }
            if (emp.appointment_date == null || emp.appointment_date == '') {
                appointment_date = "-"
            }
            else {
                appointment_date = emp.appointment_date;
            }
            if (emp.next_appointment_date == null || emp.next_appointment_date == '') {
                next_visit_date = "-"
            }
            else {
                next_visit_date = emp.next_appointment_date;
            }
            if (emp.created_by == "CHATBOT") {
                created_by = "CHATBOT";
            }
            else if (emp.created_by == doctorid) {
                created_by = "WEB";
            }
            else {
                created_by = "PHONE";
            }
            if (emp.status == "1" && (emp.check_status != "6" || emp.check_status == null)) {
                status = "Booked";
            }
            else if (emp.status == "4" || emp.status == "7") {
                status = "Visited";
            }
            else if (emp.status == "1" && emp.check_status == "6") {
                status = "Failed to Visit";
            }
            else {
                status = "cancelled";
            }
            row_data = "<tr><td>" + j + "</td><td class='align-middle'>" + emp.patient_name + "</span></a><br /><span class='mys-ph'>ph : " + phone_number + "</span>&nbsp;/&nbsp<span class='mys-id'>" + doctor_patient_id + "</span></td><td>" + appointment_date + "</td><td>" + next_visit_date + "</td><td>" + app_type + "</td><td>" + created_by + "</td><td>" + status + "</td></tr>";
            tr.append(row_data);
        });
        tr.append("</tbody>");
        $.when($('#app_table_list').append(tr)).then($('#appointmentlist').DataTable({
            "columnDefs": [{
                "target": [1, 8],
                "orderable": false,
            }]
        }));
        var data_app = '';
        $("#appsellist li span").each(function () { data_app += $(this).html().split("").join("").split("").join("")+", " })
        //       $("#appsellist li").each(function () { data_app += $(this).html().split("<span class='head-li-flter'>").join("").split("</span>").join("") + '\n\r' })
        $('#appointmentlist').DataTable({
            destroy: true,
            dom: 'Bfrtip',
            messageTop: data_app,
            buttons: [
                {
                    extend: 'pdf',
                    title: 'Appointment Report: \n\r' + data_app
                },
                {
                    extend: 'excel',
                    //customize: _customizeExcelOptions,
                    title: 'Appointment Report: \n\r' + data_app
                },
                {
                    extend: 'csv',
                    title: 'Appointment Report: \n\r' + data_app
                },
            ]
        });
    }
}

//apppointment report code ended



//medicine report code started

$('#med_name_report').on('input', function () {
    debugger;
    var doc_id = '';
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
        doc_id = $('#HiddenDoctorID').val();
    }
    else {
        if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
        else {
            if ($.trim($('#SelDoctormed').val()).length > 0) {
                doc_id = $('#SelDoctormed').val();
            }
            else {
                $('#PSelHospitalmed').show();
                $('#PSelHospitalmed').fadeOut(8000);
                $('#PSelHospitalmed').html('Please Select Doctor');
                $('#SelDoctormed').focus();
                $('#SelDoctormed').val('');
                return false;
            }
        }
    }

    if ($.trim($('#med_name_report').val()).length > 2) {
        $('#med_name_report').autocomplete({
            source: function (request, response) {
                $.ajax({
                    async: true,
                    url: "/reports/AutoComplete_MedName?rep_list=" + $('#med_name_report').val()+ "&doctor_id=" + doc_id,
                    type: "POST",
                    dataType: "json",
                    data: { Prefix: request.term },
                    success: function (data) {
                        var data2 = JSON.parse(data);
                        var data = data2.data;
                        response($.map(data, function (item) {
                            return { label: item.medicine_name, value: item.medicine_name };
                        }));

                    }
                });
            }
        });
    }
    else {

    }
});

function medicine_list_cur_month(val) {
    debugger;
    var doc_id = '';
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
    else { doc_id = $('#SelDoctormed').val(); }
    if (val == "0") {
        var medicine_data = {
            indicator_id: 'ML',
            doctor_id: doc_id
        }
    }
    else {
        var where_condition = '', medicine_name = '', date = '', from_date = '', to_date = '';
        medicine_name = $('#med_name_report').val();
        date = $('#fromdatetodatepres').val().split('-');
        from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");

        if (from_date != '' && to_date != '' && medicine_name != '') {
            where_condition = where_condition + "and CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "' and mp.medicine_name = '" + medicine_name + "' ";
        }
        else if (from_date != '' && to_date != '') {
            where_condition = where_condition + "and CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "'";
        }
        var medicine_data = {
            doctor_id: doc_id,
            indicator_id: 'MLF',
            from_date: from_date,
            to_date: to_date,
            medicine_name: where_condition
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_medicine_prescription',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(medicine_data),
        success: function (data) {
            console.log(data);
            debugger;
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                table_medicine(data);
                if (val == "0") {

                }
                else {
                }
            }
            else {
                console.log(data);
            }
            
        },
    });
}

function table_medicine(data) {
    debugger;
    if (jQuery.isEmptyObject((data)) || data.length == "0") {
        tr = $('<table class="table-responsive table table-bordered table-striped" id="medicine_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Id</th><th>Patient Name</th><th>Phone Number</th><th>Visit Date</th><th>Next Visit Date</th><th>Medicine Name</th><th>Days To Take</th></tr></thead><tbody>");
        tr.append("</tbody>");
    }
    else if (data.length > 0) {
        var data2 = JSON.parse(data);
        var data1 = data2.data;
        $('#med_table_list').empty();
        var j = 0;
        //var data1 = JSON.parse(data);
        var b = data1.Table;
        tr = $('<table class="table-responsive table table-bordered table-striped" id="medicine_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Id</th><th>Patient Name</th><th>Phone Number</th><th>Visit Date</th><th>Next Visit Date</th><th>Medicine Name</th><th>Days To Take</th></tr></thead><tbody>");
        $('#med_table_list').removeClass('us-db-loader-appoinments');
        $.each(b, function (i, emp) {
            j++;
            var phone_number = "-", next_appointment_date = "-", doctor_patient_id = " ", created_on = "-", generic_name = '', days_to_take = '';
            if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                phone_number = "-"
            }
            else {
                phone_number = emp.phone_number_1;
            }
            if (emp.doctor_patient_id == null || emp.doctor_patient_id == '') {
                doctor_patient_id = emp.patient_id;
            }
            else {
                doctor_patient_id = emp.patient_id + '/' + emp.doctor_patient_id;
            }
            if (emp.created_on == null || emp.created_on == '') {
                appointment_date = "-"
            }
            else {
                created_on = emp.created_on;
            }
            if (emp.next_appointment_date == null || emp.next_appointment_date == '') {
                next_appointment_date = "-"
            }
            else {
                next_appointment_date = emp.next_appointment_date;
            }
            if (emp.generic_name == null || emp.generic_name == '') {
                generic_name = emp.medicine_name;
            }
            else {
                generic_name = emp.medicine_name + '(' + emp.generic_name + ')';
            }
            if (emp.days_to_take == null || emp.days_to_take == '') days_to_take = '-';
            else days_to_take = emp.days_to_take;
            row_data = "<tr><td>" + j + "</td><td>" + doctor_patient_id + "</td><td>" + emp.first_name + "</td><td>" + phone_number + "</td><td>" + created_on + "</td><td>" + next_appointment_date + "</td><td>" + generic_name + "</td><td>" + days_to_take + "</td></tr>";
            tr.append(row_data);
        });
        tr.append("</tbody>");
        $.when($('#med_table_list').append(tr)).then($('#medicine_table_list').DataTable({
            "columnDefs": [{
                "target": [1, 7],
                "orderable": false,
            }]
        }));
        var data_med = "";
        $("#medsellist li span").each(function () { data_med += $(this).html().split("").join("").split("").join("") + ', ' })
        //$("#medsellist li").each(function () { data_med += $(this).html().split("").join("").split("").join("") + '\n\r' })
        $('#medicine_table_list').DataTable({
            destroy: true,
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'pdf',
                    title: 'Medicine Report\n\r' + data_med
                },
                {
                    extend: 'excel',
                    title: 'Medicine Report\n\r' + data_med
                },
                {
                    extend: 'csv',
                    title: 'Medicine Report\n\r' + data_med
                },
            ]
        });
    }
}

//medicine report code ended



//lab report code started

$('#lab_name_report').on('input', function () {
    var doc_id = '';
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
        doc_id = $('#HiddenDoctorID').val();
    }
    else {
        if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
        else {
            if ($.trim($('#SelDoctorlab').val()).length > 0) {
                doc_id = $('#SelDoctorlab').val();
            }
            else {
                $('#PSelHospitallab').show();
                $('#PSelHospitallab').fadeOut(8000);
                $('#PSelHospitallab').html('Please Select Doctor');
                $('#SelDoctorlab').focus();
                $('#SelDoctorlab').val('');
                return false;
            }
        }
    }
    $('#lab_name_report').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/reports/AutoComplete_LabName?rep_list=" + $('#lab_name_report').val() + "&doctor_id=" + doc_id,
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    var data2 = JSON.parse(data);
                    var data = data2.data;
                    response($.map(data, function (item) {
                        return { label: item.lab_name, value: item.lab_name };
                    }));

                }
            });
        }
    });
});

function lab_list_cur_month(val) {
    var doc_id = '';
    if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
    else { doc_id = $('#SelDoctorlab').val(); }
    if (val == "0") {
        var medicine_data = {
            indicator_id: 'LL',
            doctor_id: doc_id
        }
    }
    else {
        var where_condition = '', from_date = '', to_date = '', sug_from_date = '', Sug_to_date = '', date = '', date1 = '';
        if ($.trim($('#fromdatetodatelab').val()).length > 0) {
            var date = $('#fromdatetodatelab').val().split('-');
            var from_date = date[0];
            from_date = from_date.split("/").reverse().join("-");
            var to_date = date[1];
            to_date = to_date.split("/").reverse().join("-");
        }
        if ($.trim($('#fromdatetodatelabsugg').val()).length > 0) {
            date1 = $('#fromdatetodatelabsugg').val().split('-');
            sug_from_date = date1[0];
            sug_from_date = sug_from_date.split("/").reverse().join("-");
            Sug_to_date = date1[1];
            Sug_to_date = Sug_to_date.split("/").reverse().join("-");
        }
        lab_name = $('#lab_name_report').val();

        if (from_date != '' && to_date != '' && sug_from_date != '' && Sug_to_date != '' && lab_name != '') {
            where_condition = where_condition + "and (CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "') and (CONVERT(date,(mp.suggested_date)) between '" + sug_from_date + "' and '" + Sug_to_date + "') and mp.lab_prescription = '" + lab_name + "' ";
        }
        else if (sug_from_date != '' && Sug_to_date != '' && lab_name != '') {
            where_condition = where_condition + "and (CONVERT(date,(mp.suggested_date)) between '" + sug_from_date + "' and '" + Sug_to_date + "') and mp.lab_prescription = '" + lab_name + "' ";
        }
        else if (sug_from_date != '' && Sug_to_date != '') {
            where_condition = where_condition + "and (CONVERT(date,(mp.suggested_date)) between '" + sug_from_date + "' and '" + Sug_to_date + "' )";
        }
        else if (from_date != '' && to_date != '' && lab_name != '') {
            where_condition = where_condition + "and (CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "') and mp.lab_prescription = '" + lab_name + "' ";
        }
        else if (from_date != '' && to_date != '') {
            where_condition = where_condition + "and (CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "')";
        }
        else if (from_date != '' && to_date != '' && sug_from_date != '' && Sug_to_date != '') {
            where_condition = where_condition + "and ((CONVERT(date,(vr.created_on)) between '" + from_date + "' and '" + to_date + "') and (CONVERT(date,(mp.suggested_date)) between '" + sug_from_date + "' and '" + Sug_to_date + "')) ";
        }
        else if (lab_name != '') {
            where_condition = where_condition + " and mp.lab_prescription = '" + lab_name + "' ";
        }

        var medicine_data = {
            doctor_id: doc_id,
            indicator_id: 'LLF',
            from_date: from_date,
            to_date: to_date,
            lab_name: where_condition
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_lab_prescription',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(medicine_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            table_lab(data);
            if (val == "0") {

            }
            else {
            }
        },
    });
}

function table_lab(data) {
    if (jQuery.isEmptyObject((data)) || data.length == "0") {
        tr = $('<table class="table-responsive table table-bordered table-striped" id="labname_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Id</th><th>Patient Name</th><th>Phone Number</th><th>Visit Date</th><th>Next Visit Date</th><th>Lab Name</th><th>Lab Suggested Date</th></tr></thead><tbody>");
        tr.append("</tbody>");
    }
    else if (data.length > 0) {
        $('#lab_table_list').empty();

        var data2 = JSON.parse(data);
        var data1 = data2.data;
        var j = 0;
        //var data1 = JSON.parse(data);
        var b = data1.Table;
        tr = $('<table class="table-responsive table table-bordered table-striped" id="labname_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Id</th><th>Patient Name</th><th>Phone Number</th><th>Visit Date</th><th>Next Visit Date</th><th>Lab Name</th><th>Lab Suggested Date</th></tr></thead><tbody>");
        $('#lab_table_list').removeClass('us-db-loader-appoinments');
        $.each(b, function (i, emp) {
            j++;
            var phone_number = "-", doctor_patient_id = " ", created_on = "-", next_appointment_date = "-", suggested_date = "-";
            if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                phone_number = "-"
            }
            else {
                phone_number = emp.phone_number_1;
            }
            if (emp.doctor_patient_id == null || emp.doctor_patient_id == '') {
                doctor_patient_id = emp.patient_id;
            }
            else {
                doctor_patient_id = emp.patient_id + '/' + emp.doctor_patient_id;
            }
            if (emp.created_on == null || emp.created_on == '') {
                appointment_date = "-"
            }
            else {
                created_on = emp.created_on;
            }
            if (emp.next_appointment_date == null || emp.next_appointment_date == '') {
                next_appointment_date = "-"
            }
            else {
                next_appointment_date = emp.next_appointment_date;
            }
            if (emp.suggested_date == null || emp.suggested_date == '') {
                suggested_date = "-"
            }
            else {
                suggested_date = emp.suggested_date;
            }

            row_data = "<tr><td>" + j + "</td><td>" + doctor_patient_id + "</td><td>" + emp.first_name + "</td><td>" + phone_number + "</td><td>" + created_on + "</td><td>" + next_appointment_date + "</td><td>" + emp.lab_prescription + "</td><td>" + suggested_date + "</td></tr>";
            tr.append(row_data);
        });
        tr.append("</tbody>");
        $.when($('#lab_table_list').append(tr)).then($('#labname_table_list').DataTable({
            "columnDefs": [{
                "target": [1, 7],
                "orderable": false,
            }]
        }));
        var data_lab = "";
        $("#labsellist li span").each(function () { data_lab += $(this).html().split("").join("").split("").join("") + ', ' })
        //$("#labsellist li").each(function () { data_lab += $(this).html().split("").join("").split("").join("") + '\n\r' })
        $('#labname_table_list').DataTable({
            destroy: true,
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'pdf',
                    title: 'Lab Report\n\r ' + data_lab
                },
                {
                    extend: 'excel',
                    title: 'Lab Report\n\r ' + data_lab
                },
                {
                    extend: 'csv',
                    title: 'Lab Report\n\r ' + data_lab
                },
            ]
        });
    }
}

//lab report code ended


//revenue report code started

$('#pat_rev_report').on('input', function () {
    var doc_id = '';
    if ($('#HProductCode').val() == 1 || $('#HProductCode').val() == 4) {
        doc_id = $('#HiddenDoctorID').val();
    }
    else {
        if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); }
        else {
            if ($.trim($('#SelDoctorrev').val()).length > 0) {
                doc_id = $('#SelDoctorrev').val();
            }
            else {
                $('#PSelHospitalrev').show();
                $('#PSelHospitalrev').fadeOut(8000);
                $('#PSelHospitalrev').html('Please Select Doctor');
                $('#SelDoctorrev').focus();
                $('#SelDoctorrev').val('');
                return false;
            }
        }
    }
    $('#pat_rev_report').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/reports/AutoComplete_RevPatName?rep_list=" + $('#pat_rev_report').val() + "&doctor_id=" + doc_id,
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    var data2 = JSON.parse(data);
                    var data = data2.data;
                    response($.map(data, function (item) {
                        return { label: item.patient_name, value: item.patient_name };
                    }));

                }
            });
        }
    });
});

function revenue_list_cur_month(val) {
    debugger;
    var doc_id = '', dml_indicator = '';
    if (val == "0") {
        if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); dml_indicator = "RL" }
        else { doc_id = $('#SelDoctorrev').val(); dml_indicator = "RLA" }
        var medicine_data = {
            indicator_id: dml_indicator,
            doctor_id: doc_id
        }
    }
    else {
        if ($('#hiddenRole_id').val() == 1 || $('#hiddenRole_id').val() == 5) { doc_id = $('#HiddenDoctorID').val(); dml_indicator = "RLF" }
        else { doc_id = $('#SelDoctorrev').val(); dml_indicator = "RLAF" }
        var date = $('#fromdatetodaterevenue').val().split('-');
        var from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        var to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        var pending = '', partial = '', paid = '', chat = '', lab = '', consultation = '', appointment = '', video = '', prepaid = '', postpaid = '', where_condition = '', cash = '', online = '', paymemt_gatway = '', name = '';
        if ($('#rev_pending').prop("checked") == true) {
            pending = 1;
        }
        if ($('#rev_partial').prop("checked") == true) {
            partial = 2;
        }
        if ($('#rev_paid').prop("checked") == true) {
            paid = 3;
        }

        if ($('#rev_chat').prop("checked") == true) {
            chat = '%chat%';
        }
        if ($('#rev_lab').prop("checked") == true) {
            lab = '%lab%';
        }
        if ($('#rev_consul').prop("checked") == true) {
            consultation = '%consultation%';
        }
        if ($('#rev_app').prop("checked") == true) {
            appointment = '%appointment%';
        }

        if ($('#rev_prepaid').prop("checked") == true) {
            prepaid = '1';
        }
        if ($('#rev_postpaid').prop("checked") == true) {
            postpaid = '2';
        }

        if ($('#rev_cash').prop("checked") == true) {
            cash = '1';
        }
        if ($('#rev_card').prop("checked") == true) {
            online = '2';
        }
        if ($('#rev_gatway').prop("checked") == true) {
            paymemt_gatway = '3';
        }

        if (pending != '' && partial != '' && paid != '') {
            where_condition = where_condition + " and (das.invoice_status = " + pending + " or das.invoice_status = " + partial + " or das.invoice_status = " + paid + ")";
        }
        else if (pending != '' && partial != '') {
            where_condition = where_condition + " and (das.invoice_status = " + pending + " or das.invoice_status = " + partial + ")";
        }
        else if (pending != '' && paid != '') {
            where_condition = where_condition + " and (das.invoice_status = " + pending + " or das.invoice_status = " + paid + ")";
        }
        else if (partial != '' && paid != '') {
            where_condition = where_condition + " and (das.invoice_status = " + partial + " or das.invoice_status = " + paid + ")";
        }
        else if (pending != '') {
            where_condition = where_condition + " and das.invoice_status = " + pending;
        }
        else if (partial != '') {
            where_condition = where_condition + " and das.invoice_status = " + partial;
        }
        else if (paid != '') {
            where_condition = where_condition + " and das.invoice_status = " + paid;
        }

        if (chat != '' && lab != '' && consultation != '' && appointment != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + lab + "' or das.invoice_description like '" + consultation + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (chat != '' && lab != '' && consultation != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + lab + "' or das.invoice_description like '" + consultation + "')";
        }
        else if (lab != '' && consultation != '' && appointment != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + lab + "' or das.invoice_description like '" + consultation + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (consultation != '' && appointment != '' && chat != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + consultation + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (chat != '' && lab != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + lab + "')";
        }
        else if (chat != '' && appointment != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (chat != '' && consultation != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + chat + "' or das.invoice_description like '" + consultation + "')";
        }
        else if (lab != '' && consultation != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + lab + "' or das.invoice_description like '" + consultation + "')";
        }
        else if (lab != '' && appointment != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + lab + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (consultation != '' && appointment != '') {
            where_condition = where_condition + " and (das.invoice_description like '" + consultation + "' or das.invoice_description like '" + appointment + "')";
        }
        else if (chat != '') {
            where_condition = where_condition + " and das.invoice_description like '" + chat + "' ";
        }
        else if (lab != '') {
            where_condition = where_condition + " and das.invoice_description like '" + lab + "' ";
        }
        else if (appointment != '') {
            where_condition = where_condition + " and das.invoice_description like '" + appointment + "' ";
        }
        else if (consultation != '') {
            where_condition = where_condition + " and das.invoice_description like '" + consultation + "' ";
        }

        if (prepaid != '' && postpaid != '') {
            where_condition = where_condition + " and (das.created_by = '" + prepaid + "' or das.created_by like '" + postpaid + "')";
        }
        else if (prepaid != '') {
            where_condition = where_condition + " and (das.created_by = '" + prepaid + "')";
        }
        else if (postpaid != '') {
            where_condition = where_condition + " and (das.created_by = '" + postpaid + "')";
        }

        if (cash != '' && online != '' && paymemt_gatway != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + cash + "' or pp.payment_type = '" + online + "' or pp.payment_type = '" + paymemt_gatway + "')";
        }
        else if (cash != '' && paymemt_gatway != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + cash + "' or pp.payment_type = '" + paymemt_gatway + "')";
        }
        else if (online != '' && paymemt_gatway != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + online + "' or pp.payment_type = '" + paymemt_gatway + "')";
        }
        else if (cash != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + cash + "')";
        }
        else if (online != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + online + "')";
        }
        else if (paymemt_gatway != '') {
            where_condition = where_condition + " and (pp.payment_type = '" + paymemt_gatway + "')";
        }

        if ($.trim($('#pat_rev_report').val()).length > 0) {
            debugger;
            name = $('#pat_rev_report').val();
            name = name.split('/');
            if (name[1] != "-") {
                where_condition = where_condition + " and (mit.first_name = '" + name[0] + "' and mit.phone_number_1 = '" + name[1] + "' )";
            }
            else {
                where_condition = where_condition + " and (mit.first_name = '" + name[0] + "' )";
            }
        }

        where_condition = " and (convert(date,(das.invoice_date)) between '" + from_date + "' and '" + to_date + "' )" + where_condition + "";
        //where_condition = " and (convert(date,(das.invoice_date)) between '" + from_date + "' and '" + to_date + "' )" + where_condition + " group by das.invoice_id";

        var medicine_data = {
            doctor_id: doc_id,
            indicator_id: dml_indicator,
            condition: where_condition
        }
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_revenue',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(medicine_data),
        success: function (data) {

            var data2 = JSON.parse(data);
            table_revenue(data);
            if (val == "0") {
            }
            else {
                $('#rev_table_list').removeClass('us-db-loader-appoinments');
            }
        },
    });
}

function table_revenue(data) {
    if (jQuery.isEmptyObject((data)) || data.length == "0") {
        tr = $('<table class="table-responsive table table-bordered table-striped" id="reveue_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Details</th><th>Invoice</th><th>Invoice/Paid Date</th><th>Invoice Amount(Rs)</th><th>Paid Amount(Rs)</th><th>Balance Amount(Rs)</th></tr></thead><tbody>");
        tr.append("</tbody>");
    }
    else if (data.length > 0) {

        var data2 = JSON.parse(data);
        var data1 = data2.data;
        $('#rev_table_list').empty();
        var j = 0, total_invoice = 0, total_paid = 0, total_balance = 0;
        //var data1 = JSON.parse(data);
        var b = data1.Table;
        tr = $('<table class="table-responsive table table-bordered table-striped" id="reveue_table_list" />');
        tr.append("<thead><tr><th>S No</th><th>Patient Details</th><th>Invoice</th><th>Invoice/Paid Date</th><th>Invoice Amount(Rs)</th><th>Paid Amount(Rs)</th><th>Balance Amount(Rs)</th></tr></thead><tbody>");
        $('#rev_table_list').removeClass('us-db-loader-appoinments');
        $.each(b, function (i, emp) {
            j++;
            var phone_number = "-", doctor_patient_id = " ", invoice_date = "-", paid_date = "-", invoice_amount = "0", balance_amount = "0", paid_amount = "0", payment_mode = '', total_invoice_amount = 0, total_balance_amount = 0, total_paid_amount = 0;
            if (emp.phone_number_1 != null || emp.phone_number_1 != '') {
                phone_number = emp.phone_number_1
            }
            if (emp.doctor_patient_id == null || emp.doctor_patient_id == '') {
                doctor_patient_id = emp.patient_id;
            }
            else {
                doctor_patient_id = emp.patient_id + '/' + emp.doctor_patient_id;
            }
            if (emp.invoice_date == null || emp.invoice_date == '') {
                invoice_date = "-";
            }
            else {
                invoice_date = emp.invoice_date;
            }
            if (emp.paid_date == null || emp.paid_date == '') {
                paid_date = "-";
            }
            else {
                paid_date = emp.paid_date;
            }
            if (emp.invoice_amount == null || emp.invoice_amount == '') {
                invoice_amount = "0"
            }
            else {
                invoice_amount = emp.invoice_amount;
            }
            if (emp.balance_amount == null || emp.balance_amount == '') {
                balance_amount = "0"
            }
            else {
                balance_amount = emp.balance_amount;
            }
            if (emp.payment_type == "1") {
                payment_mode = "Cash";
            }
            else if (emp.payment_type == "2") {
                payment_mode = "Card";
            }
            else if (emp.payment_type == "3") {
                payment_mode = "Payment Gateway";
            }
            else {
                payment_mode = '-';
            }
            paid_amount = (parseFloat(invoice_amount) - parseFloat(balance_amount)).toFixed(2);
            total_invoice = (parseFloat(total_invoice) + parseFloat(invoice_amount)).toFixed(2);
            total_balance = (parseFloat(total_balance) + parseFloat(balance_amount)).toFixed(2);
            total_paid = (parseFloat(total_paid) + parseFloat(paid_amount)).toFixed(2);
            row_data = "<tr><td>" + j + "</td><td class='align-middle'>" + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone_number + "</span>&nbsp;/&nbsp<span class='mys-id'>" + emp.patient_id + "</span></td><td class='align-middle'>" + emp.invoice_description + "</td><td class='align-middle'>" + invoice_date + "</span></a><br />&nbsp;<span class='mys-ph'>" + paid_date + "</span></td><td  class='align-middle'>" + invoice_amount + "</td><td class='align-middle'>" + paid_amount + "</span></a><br />&nbsp;<span class='mys-ph'>" + payment_mode + "</span><td  class='align-middle'>" + balance_amount + "</td></tr>";
            tr.append(row_data);
        });
        tr.append("</tbody>");
        row_data1 = "<tfoot><tr><td></td><td></td><td></td><td><b class = 'pull-right'>" + 'Total(Rs)' + "</td><td>" + total_invoice + "</td><td>" + total_paid + "</td><td>" + total_balance + "</td></tr> </tfoot>";
        tr.append(row_data1);
       
        $.when($('#rev_table_list').append(tr)).then($('#reveue_table_list').DataTable({
            "columnDefs": [{
                "target":[1,9],
                "orderable": false,
            }]
        }));
        var data_rev = "";
        $("#revsellist li span").each(function () { data_rev += $(this).html().split("").join("").split("").join("") + ', ' })
        // $("#revsellist li").each(function () { data_rev += $(this).html().split("").join("").split("").join("") + '\n\r' })
        $('#reveue_table_list').DataTable({
            destroy: true,
            dom: 'Bfrtip',
            header: 'true',
            footer: 'true',
            buttons: [
                {
                    extend: 'pdf',
                    title: 'Revenue Report: \n\r' + data_rev,
                    footer: true
                },
                {
                    extend: 'excel',
                    title: 'Revenue Report: \n\r' + data_rev,
                    footer: true
                },
                {
                    extend: 'csv',
                    title: 'Revenue Report: \n\r' + data_rev,
                    footer: true
                },
            ]
        });
    }
}

//report report code ended

//daily summary report code start

function summary_sel_options() {
    $('#summarysellist').empty();
    var medicine_name, date, from_date, to_date, med_date;
    if ($.trim($('#fromdatetodatesummary').val()).length > 0) {
        date = $('#fromdatetodatesummary').val().split('-');
        from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        med_date = from_date + " to " + to_date;
        $('#summarysellist').append('<li class="label label-primary"> <span class="head-li-filter">From date: ' + med_date + '</span> <i class="fa fa-times" onclick = summary_sel_del(' + '1' + ')></i> </li>');
    }

}

function summary_sel_del(val) {
    $('#fromdatetodatesummary').val('');
    summary_sel_options();
}

function Daily_SummaryList() {
    debugger;
    var appointment_data = {
        indicator_id: "ADSL",
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                if (jQuery.isEmptyObject((data1)) || data1.length == "0") {

                }
                else if (Object.keys(data1).length > 0) {
                    $('#divDailySummary').empty();
                    var j = 0;
                    var b = data1.Table;
                    if ($('#selSummaryReportType').val() == 1) {
                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Doctor Name</td><td>Appointment Type</td><td>Booked</td><td>Completed</td><td>Prescribed</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.DoctorName + '</td><td>' + emp.Type + '</td><td>' + ((emp.Booked != 0) ? emp.Booked : "-") + '</td><td>' + ((emp.Completed != 0) ? emp.Completed : "-") + '</td><td>' + ((emp.Prescribed != 0) ? emp.Prescribed : "-") + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }
                    else if ($('#selSummaryReportType').val() == 2) {

                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Speciality Name</td><td>Appointment Type</td><td>Booked</td><td>Completed</td><td>Prescribed</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.speciality_name + '</td><td>' + emp.Type + '</td><td>' + ((emp.Booked != 0) ? emp.Booked : "-") + '</td><td>' + ((emp.Completed != 0) ? emp.Completed : "-") + '</td><td>' + ((emp.Prescribed != 0) ? emp.Prescribed : "-") + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }
                    else {

                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Doctor Name</td><td>Patient Name</td><td>Appointment Type</td><td>Engage Time</td><td>Waiting Time</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            var WaitingTime = 0;
                            if (emp.check_status > 1) {
                                var checkin_timeminutes = (emp.checkin_timeminutes);
                                var checkout_timeminutes = (emp.checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (emp.check_status == null || emp.check_status == '') {
                                WaitingTime = '-';
                            }
                            else {

                                var dt = new Date();

                                var time = (dt.getHours() < 10 ? '0' : '') + dt.getHours() + ':' +
                          (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes() + ':' + (dt.getSeconds() < 10 ? '0' : '') + dt.getSeconds();
                                var checkin_timeminutes = emp.checkin_timeminutes;
                                if (checkin_timeminutes != '' && checkin_timeminutes != null) {
                                    var CurrentTime = emp.CurrentTime;
                                    WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")

                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                                else {
                                    WaitingTime = '-';
                                }
                            }




                            var EngagedTime = emp.enage_time;
                            if (EngagedTime == null || EngagedTime == '') {

                                EngagedTime = '-';

                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';

                            }

                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.DoctorName + '</td><td>' + emp.PatientName + '</td><td>' + emp.Type + '</td><td>' + EngagedTime + '</td><td>' + WaitingTime + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }

                }
            }
            else {
                console.log(data);
            }

        },
    });
}

$('#btnSearchSummary').click(function () {
    debugger;
    if ($.trim($('#fromdatetodatesummary').val()).length == "") {
        $('#Pfromdatetodatesummary').show();
        $('#Pfromdatetodatesummary').fadeOut(8000);
        $('#Pfromdatetodatesummary').html('Please Select Date');
        $('#fromdatetodatesummary').focus();
        $('#fromdatetodatesummary').val('');
        return false;
    }

    if ($('#selSummaryReportType').val() == 0) {
        $('#PSelSummaryType').show();
        $('#PSelSummaryType').fadeOut(8000);
        $('#PSelSummaryType').html('Please Select Report Type');
        $('#selSummaryReportType').focus();
        $('#selSummaryReportType').val('');
        return false;
    }

    if ($('#selSummaryReportType').val() != 3) {

        if ($('#selSummaryAppointment').val() == "") {
            $('#PSelSummaryAppointment').show();
            $('#PSelSummaryAppointment').fadeOut(8000);
            $('#PSelSummaryAppointment').html('Please Select Appointment Type');
            $('#selSummaryAppointment').focus();
            $('#selSummaryAppointment').val('');
            return false;
        }
    }

    var date = $('#fromdatetodatesummary').val().split('-');
    var from_date = date[0];
    from_date = from_date.split("/").reverse().join("-");
    var to_date = date[1];
    to_date = to_date.split("/").reverse().join("-");
    var where_condition = '';
    var DML_indicator = '';
    if ($('#selSummaryReportType').val() == 1) {
        if ($('#selSummaryDoctor').val() != '' && $('#selSummaryDoctor').val() != 0) {
            DML_indicator = 'DS';
            if ($('#selSummaryAppointment').val() == 0) {
                where_condition = " ds.doctor_id ='" + $('#selSummaryDoctor').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " ds.doctor_id ='" + $('#selSummaryDoctor').val() + "' and das.appointment_type='" + $('#selSummaryAppointment').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
        }
        else {
            DML_indicator = 'DS';
            if ($('#selSummaryAppointment').val() == 0) {
                where_condition = " (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " das.appointment_type='" + $('#selSummaryAppointment').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
        }
    }
    else if ($('#selSummaryReportType').val() == 2) {
        if ($('#selSummarySpeciality').val() != '' && $('#selSummarySpeciality').val() != 0) {
            DML_indicator = 'SS';
            if ($('#selSummaryAppointment').val() == 0) {
                where_condition = " mds.medway_speciality_id ='" + $('#selSummarySpeciality').val() + "' and (date(das.slot_start_time) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " mds.medway_speciality_id ='" + $('#selSummarySpeciality').val() + "' and das.appointment_type='" + $('#selSummaryAppointment').val() + "' and (convert(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
        }
        else {
            DML_indicator = 'SS';
            if ($('#selSummaryAppointment').val() == 0) {
                where_condition = " (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " das.appointment_type='" + $('#selSummaryAppointment').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
        }
    }
    else {
        DML_indicator = 'ES';
        if ($('#selSummaryDoctor').val() != '' && $('#selSummaryDoctor').val() != 0) {
            if ($('#selSummaryAppointment').val() == 0) {
            where_condition = " ds.doctor_id ='" + $('#selSummaryDoctor').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " ds.doctor_id ='" + $('#selSummaryDoctor').val() + "' and das.appointment_type='" + $('#selSummaryAppointment').val() + "' and (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
       }
        else {
            if ($('#selSummaryAppointment').val() == 0) {
                where_condition = "  (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            else {
                where_condition = " and das.appointment_type='" + $('#selSummaryAppointment').val() + "' (CONVERT(date,(das.slot_start_time)) between '" + from_date + "' and '" + to_date + "' )";
            }
            }
    }

    console.log(where_condition);
    var appointment_data = {
        indicator_id: DML_indicator,
        from_date: from_date,
        to_date: to_date,
        where_condition: where_condition
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data)) || data.length == "0") {

            }
            else if (data.length > 0) {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    $('#divDailySummary').empty();
                    var j = 0;
                    var b = data1.Table;
                    if ($('#selSummaryReportType').val() == 1) {
                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Doctor Name</td><td>Appointment Type</td><td>Booked</td><td>Completed</td><td>Prescribed</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.DoctorName + '</td><td>' + emp.Type + '</td><td>' + ((emp.Booked != 0) ? emp.Booked : "-") + '</td><td>' + ((emp.Completed != 0) ? emp.Completed : "-") + '</td><td>' + ((emp.Prescribed != 0) ? emp.Prescribed : "-") + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Doctor Wise Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }
                    else if ($('#selSummaryReportType').val() == 2) {

                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Speciality Name</td><td>Appointment Type</td><td>Booked</td><td>Completed</td><td>Prescribed</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.speciality_name + '</td><td>' + emp.Type + '</td><td>' + ((emp.Booked != 0) ? emp.Booked : "-") + '</td><td>' + ((emp.Completed != 0) ? emp.Completed : "-") + '</td><td>' + ((emp.Prescribed != 0) ? emp.Prescribed : "-") + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Speciality Wise Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }
                    else {

                        var tr = $('<table class="table table-bordered table-striped" id="tblDailySummary" />');
                        tr.append('<thead><tr><td>Date</td><td>Doctor Name</td><td>Patient Name</td><td>Appointment Type</td><td>Engage Time</td><td>Waiting Time</td></tr></thead><tbody>')

                        $.each(b, function (i, emp) {
                            j++;
                            var WaitingTime = 0;
                            if (emp.check_status > 1) {
                                var checkin_timeminutes = (emp.checkin_timeminutes);
                                var checkout_timeminutes = (emp.checkout_timeminutes);
                                if ((checkin_timeminutes == null || checkin_timeminutes == '') || (checkout_timeminutes == null || checkout_timeminutes == '')) {
                                    WaitingTime = '-';
                                }
                                else {

                                    WaitingTime = moment.utc(moment(checkout_timeminutes, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm");
                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                            }
                            else if (emp.check_status == null || emp.check_status == '') {
                                WaitingTime = '-';
                            }
                            else {

                                var dt = new Date();

                                var time = (dt.getHours() < 10 ? '0' : '') + dt.getHours() + ':' +
                          (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes() + ':' + (dt.getSeconds() < 10 ? '0' : '') + dt.getSeconds();
                                var checkin_timeminutes = emp.checkin_timeminutes;
                                if (checkin_timeminutes != '' && checkin_timeminutes != null) {
                                    var CurrentTime = emp.CurrentTime;
                                    WaitingTime = moment.utc(moment(CurrentTime, "HH:mm:ss").diff(moment(checkin_timeminutes, "HH:mm:ss"))).format("HH:mm")

                                    var WaitingTimes = WaitingTime.split(':');
                                    WaitingTime = WaitingTimes[0] + 'h ' + WaitingTimes[1] + 'm';
                                }
                                else {
                                    WaitingTime = '-';
                                }
                            }




                            var EngagedTime = emp.enage_time;
                            if (EngagedTime == null || EngagedTime == '') {

                                EngagedTime = '-';

                            }
                            else {
                                var EngagedTimes = EngagedTime.split(':');
                                EngagedTime = EngagedTimes[0] + 'h ' + EngagedTimes[1] + 'm';

                            }

                            row_data = '<tr><td>' + emp.appointment_date + '</td><td>' + emp.DoctorName + '</td><td>' + emp.PatientName + '</td><td>' + emp.Type + '</td><td>' + EngagedTime + '</td><td>' + WaitingTime + '</td></tr>';
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#divDailySummary').append(tr)).then($('#tblDailySummary').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                        var data_lab = "";
                        $('#tblDailySummary').DataTable({
                            destroy: true,
                            dom: 'Bfrtip',
                            buttons: [
                                {
                                    extend: 'pdf',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'excel',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                                {
                                    extend: 'csv',
                                    title: 'Waiting/Engage Time Summary Report\n\r ' + data_lab
                                },
                            ]
                        });
                    }
                }
                else {
                    console.log(data);
                }
            }

        },
    });
});
//dialy summary report code end



// patient report code start

function patient_report_sel_options() {
    $('#patientReportSelList').empty();
    var medicine_name, date, from_date, to_date, med_date;
    if ($.trim($('#fromdatetodatepatientreport').val()).length > 0) {
        date = $('#fromdatetodatepatientreport').val().split('-');
        from_date = date[0];
        from_date = from_date.split("/").reverse().join("-");
        to_date = date[1];
        to_date = to_date.split("/").reverse().join("-");
        med_date = from_date + " to " + to_date;
        $('#patientReportSelList').append('<li> <span class="head-li-filter">From date: ' + med_date + '</span> <i class="fa fa-times" onclick = patient_report_sel_del(' + '1' + ')></i> </li>');
    }

}

function patient_report_sel_del(val) {
    $('#fromdatetodatepatientreport').val('');
    patient_report_sel_options();
}


$('#btnSearchPatientReport').click(function () {
    if ($.trim($('#fromdatetodatepatientreport').val()).length == "") {
        $('#Pfromdatetodatepatientreport').show();
        $('#Pfromdatetodatepatientreport').fadeOut(8000);
        $('#Pfromdatetodatepatientreport').html('Please Select Date');
        $('#fromdatetodatepatientreport').focus();
        $('#fromdatetodatepatientreport').val('');
        return false;
    }

    if ($.trim($('#selPatientReportType').val()) == "") {
        $('#PselPatientReportType').show();
        $('#PselPatientReportType').fadeOut(8000);
        $('#PselPatientReportType').html('Please Select Type');
        $('#selPatientReportType').val('');
        $('#selPatientReportType').focus();
        return false;
    }

    var date = $('#fromdatetodatepatientreport').val().split('-');
    var from_date = date[0];
    from_date = from_date.split("/").reverse().join("-");
    var to_date = date[1];
    to_date = to_date.split("/").reverse().join("-");

    var where_condition = $('#selPatientReportType option:selected').toArray().map(item => item.text).join();
    var appointment_data = {
        indicator_id: "PRS",
        from_date: from_date,
        to_date: to_date,
        where_condition: where_condition,
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data)) || data.length == "0") {

            }
            else if (data.length > 0) {
                var data1 = data2.data;
                $('#divPatientReport').empty();
                var j = 0;
                //var data1 = JSON.parse(data);
                var b = data1.Table;
                
                var tr = $('<table class="table table-bordered table-striped" id="tblPatientReport" style="width: 100% !important;" />');
                tr.append('<thead><tr><td>Date</td><td>Patient ID</td><td>Patient Name</td><td>Phone Number</td><td>Type</td></tr></thead><tbody>')

                $.each(b, function (i, emp) {
                    j++;
                    row_data = '<tr><td>' + emp.Date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td>' + emp.phone_number_1 + '</td><td>' + emp.type + '</td></tr>';
                    tr.append(row_data);
                });
                tr.append("</tbody>");
                $.when($('#divPatientReport').append(tr)).then($('#tblPatientReport').DataTable({
                    "columnDefs": [{
                        "orderable": false,
                    }]
                }));
                var data_lab = "";
                $('#tblPatientReport').DataTable({
                    destroy: true,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'pdf',
                            title: 'Patient Report\n\r ' + data_lab
                        },
                        {
                            extend: 'excel',
                            title: 'Patient Report\n\r ' + data_lab
                        },
                        {
                            extend: 'csv',
                            title: 'Patient Report\n\r ' + data_lab
                        },
                    ]
                });

                LoadPatientReportGraph();
            }
        }
    });
});


function LoadPatientReportGraph() {
    var date = $('#fromdatetodatepatientreport').val().split('-');
    var from_date = date[0];
    from_date = from_date.split("/").reverse().join("-");
    var to_date = date[1];
    to_date = to_date.split("/").reverse().join("-");

    var where_condition = $('#selPatientReportType option:selected').toArray().map(item => item.text).join();
    var appointment_data = {
        indicator_id: "PRSC",
        from_date: from_date,
        to_date: to_date,
        where_condition: where_condition,
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data)) || data.length == "0") {

            }
            else if (data.length > 0) {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var a = data1.Table;
                    var b = data1.Table1;
                    var c = data1.Table2;
                    var d = data1.Table3;
                    var e = data1.Table4;
                    var f = data1.Table5;

                    var chartColors = {
                        green: 'rgb(75, 192, 192)',
                        blue: 'rgb(54, 162, 235)',
                        greenfade: 'rgba(75, 192, 192,0.8)',
                        bluefade: 'rgba(54, 162, 235,0.4)',
                        white: 'rgb(255, 255, 255)',
                        whitefade: 'rgba(255, 255, 255,0.7)',
                        newgreen: '#94fc13',
                        neworange: '#ff502f',
                        darkblue: '#36a2eb',
                        darkpink: '#ff6b8b',
                        lightwhite: '#fff'
                    };

                    if (a.length > 0 && a[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < a.length; i++) {
                            totalCount.push(a[i].Total);
                            date.push(a[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Cholesterol",
                                    backgroundColor: chartColors.blue,  //blue
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Cholesterol",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };

                        $('#divPRCholestrolGraph').show();
                        var ctx = document.getElementById("pRCholestrolGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);

                    }
                    else {
                        $('#divPRCholestrolGraph').hide();
                    }


                    if (b.length > 0 && b[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < b.length; i++) {
                            totalCount.push(b[i].Total);
                            date.push(b[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Hypertension",
                                    backgroundColor: chartColors.greenfade,  //green fade
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Hypertension",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRHyperTensionGraph').show();
                        var ctx = document.getElementById("pRHyperTensionGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRHyperTensionGraph').hide();
                    }

                    if (c.length > 0 && c[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < c.length; i++) {
                            totalCount.push(c[i].Total);
                            date.push(c[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "PeripheralNeuropathy",
                                    backgroundColor: chartColors.neworange,  //orange
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],
                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "PeripheralNeuropathy",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRPeripheralNeuropathyGraph').show();
                        var ctx = document.getElementById("pRPeripheralNeuropathyGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRPeripheralNeuropathyGraph').hide();
                    }

                    if (d.length > 0 && d[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < d.length; i++) {
                            totalCount.push(d[i].Total);
                            date.push(d[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "PDR",
                                    backgroundColor: chartColors.darkblue,   //dark blue
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "PDR",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRPDRGraph').show();
                        var ctx = document.getElementById("pRPDRGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRPDRGraph').hide();
                    }

                    if (e.length > 0 && e[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < e.length; i++) {
                            totalCount.push(e[i].Total);
                            date.push(e[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "nPDR",
                                    backgroundColor: chartColors.darkpink,  //pink
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "nPDR",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRnPDRGraph').show();
                        var ctx = document.getElementById("pRnPDRGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRnPDRGraph').hide();
                    }

                    if (f.length > 0 && f[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < f.length; i++) {
                            totalCount.push(f[i].Total);
                            date.push(f[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Autonomic Neuropathy",
                                    backgroundColor: chartColors.bluefade, //blue fade
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Autonomic Neuropathy",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRAutonomicNeuropathyGraph').show();
                        var ctx = document.getElementById("pRAutonomicNeuropathyGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRAutonomicNeuropathyGraph').hide();
                    }
                }
                else {
                    console.log(data);
                }
            }  
            
        }
    });
}


$('#patientReportTab').click(function () {
    LoadAllPatientReport();
});

function LoadAllPatientReport () {
    debugger;
    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; 
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();


    from_date = year + "-" + month + "-" + 1;;

    to_date = year + "-" + month + "-" + day;
    

    var where_condition = "AutonomicNeuropathy,PeripheralNeuropathy,PDR,nPDR,Hypertension,Cholesterol";
    var appointment_data = {
        indicator_id: "PRS",
        from_date: from_date,
        to_date: to_date,
        where_condition: where_condition,
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {

            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data)) || data.length == "0") {

            }
            else if (data.length > 0) {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    $('#divPatientReport').empty();
                    var j = 0;
                    var b = data1.Table;

                    var tr = $('<table class="table table-bordered table-striped" id="tblPatientReport" style="width:100% !important" />');
                    tr.append('<thead><tr><td>Date</td><td>Patient ID</td><td>Patient Name</td><td>Phone Number</td><td>Type</td></tr></thead><tbody>')

                    $.each(b, function (i, emp) {
                        j++;
                        row_data = '<tr><td>' + emp.Date + '</td><td>' + emp.patient_id + '</td><td>' + emp.first_name + '</td><td>' + emp.phone_number_1 + '</td><td>' + emp.type + '</td></tr>';
                        tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    $.when($('#divPatientReport').append(tr)).then($('#tblPatientReport').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                    var data_lab = "";
                    $('#tblPatientReport').DataTable({
                        destroy: true,
                        dom: 'Bfrtip',
                        buttons: [
                            {
                                extend: 'pdf',
                                title: 'Patient Report\n\r ' + data_lab
                            },
                            {
                                extend: 'excel',
                                title: 'Patient Report\n\r ' + data_lab
                            },
                            {
                                extend: 'csv',
                                title: 'Patient Report\n\r ' + data_lab
                            },
                        ]
                    });

                    LoadAllPatientReportGraph();

                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


function LoadAllPatientReportGraph() {
    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1;
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();


    from_date = year + "-" + month + "-" + 1;;

    to_date = year + "-" + month + "-" + day;

    var where_condition = "AutonomicNeuropathy,PeripheralNeuropathy,PDR,nPDR,Hypertension,Cholesterol";
    var appointment_data = {
        indicator_id: "PRSC",
        from_date: from_date,
        to_date: to_date,
        where_condition: where_condition,
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/report_daily_summary',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(appointment_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data)) || data.length == "0") {

            }
            else if (data.length > 0) {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var a = data1.Table;
                    var b = data1.Table1;
                    var c = data1.Table2;
                    var d = data1.Table3;
                    var e = data1.Table4;
                    var f = data1.Table5;

                    var chartColors = {
                        green: 'rgb(75, 192, 192)',
                        blue: 'rgb(54, 162, 235)',
                        greenfade: 'rgba(75, 192, 192,0.8)',
                        bluefade: 'rgba(54, 162, 235,0.4)',
                        white: 'rgb(255, 255, 255)',
                        whitefade: 'rgba(255, 255, 255,0.7)',
                        newgreen: '#94fc13',
                        neworange: '#ff502f',
                        darkblue: '#36a2eb',
                        darkpink: '#ff6b8b',
                        lightwhite: '#fff'
                    };

                    if (a.length > 0 && a[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < a.length; i++) {
                            totalCount.push(a[i].Total);
                            date.push(a[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Cholesterol",
                                    backgroundColor: chartColors.blue,  //blue
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Cholesterol",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };

                        $('#divPRCholestrolGraph').show();
                        var ctx = document.getElementById("pRCholestrolGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);

                    }
                    else {
                        $('#divPRCholestrolGraph').hide();
                    }


                    if (b.length > 0 && b[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < b.length; i++) {
                            totalCount.push(b[i].Total);
                            date.push(b[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Hypertension",
                                    backgroundColor: chartColors.greenfade,  //green fade
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Hypertension",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRHyperTensionGraph').show();
                        var ctx = document.getElementById("pRHyperTensionGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRHyperTensionGraph').hide();
                    }

                    if (c.length > 0 && c[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < c.length; i++) {
                            totalCount.push(c[i].Total);
                            date.push(c[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "PeripheralNeuropathy",
                                    backgroundColor: chartColors.neworange,  //orange
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "PeripheralNeuropathy",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRPeripheralNeuropathyGraph').show();
                        var ctx = document.getElementById("pRPeripheralNeuropathyGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRPeripheralNeuropathyGraph').hide();
                    }

                    if (d.length > 0 && d[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < d.length; i++) {
                            totalCount.push(d[i].Total);
                            date.push(d[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "PDR",
                                    backgroundColor: chartColors.darkblue,   //dark blue
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "PDR",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRPDRGraph').show();
                        var ctx = document.getElementById("pRPDRGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRPDRGraph').hide();
                    }

                    if (e.length > 0 && e[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < e.length; i++) {
                            totalCount.push(e[i].Total);
                            date.push(e[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "nPDR",
                                    backgroundColor: chartColors.darkpink,  //pink
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "nPDR",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRnPDRGraph').show();
                        var ctx = document.getElementById("pRnPDRGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRnPDRGraph').hide();
                    }

                    if (f.length > 0 && f[0].StatusMsg == "success") {
                        var date = [], totalCount = [];
                        for (var i = 0; i < f.length; i++) {
                            totalCount.push(f[i].Total);
                            date.push(f[i].Date);
                        }

                        var config = {
                            type: 'bar',
                            data: {
                                labels: date,
                                datasets: [{
                                    label: "Autonomic Neuropathy",
                                    backgroundColor: chartColors.bluefade, //blue fade
                                    borderColor: chartColors.darkblue,
                                    data: totalCount,
                                }],

                            },
                            options: {
                                responsive: true,
                                tooltips: {
                                    mode: 'label',
                                },
                                legend: {
                                    display: false,
                                },
                                scales: {
                                    xAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: true,
                                            labelString: "Autonomic Neuropathy",
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }],
                                    yAxes: [{
                                        display: true,
                                        scaleLabel: {
                                            display: false,
                                            labelString: 'Value',
                                            fontSize: 9
                                        },
                                        ticks: {
                                            fontSize: 9,
                                            beginAtZero: true
                                        },
                                        gridLines: {
                                            display: false
                                        }
                                    }]
                                }
                            }
                        };
                        $('#divpRAutonomicNeuropathyGraph').show();
                        var ctx = document.getElementById("pRAutonomicNeuropathyGraph").getContext("2d");
                        window.myLine = new Chart(ctx, config);
                    }
                    else {
                        $('#divpRAutonomicNeuropathyGraph').hide();
                    }
                }
                else {
                    console.log(data);
                }
                
            }

        }
    });
}

// patient report code end