$(document).ready(function () {
    debugger;
    loadlab_id();
});

function loadlab_id() {
    var country = {
        Dml_Indicator: "DI",
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var Country;
                    $.each(data1, function (i, emp) {
                        $('#lab_id').val(emp.lab_id);
                    });
                }
                else {
                    console.log(data);
                }
            }

            debugger;
            LoadIPLabOrder();
            LoadIPActiveInvoices();
        }
    });
}

function LoadIPLabOrder() {
    var Template = {       
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'IPLL',
        visit_report_id: $('#IPVisitReportId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#tblExistingLabOrders').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#tblExistingLabOrders').html("Norecord");
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {

                            tr = tr + '<tr><td>' + data1[i].order_id + '</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + data1[i].total_cost + '</td></tr>'

                        }

                        var head = ('<thead><tr><th>Order No</th><th>Order Date</th><th>Name</th><th>Mobile No</th><th>Invoice Amount</th></tr></thead>');
                        var Sbody = ('<tbody id=tblExistingLabOrders_body>');
                        var Ebody = ('</tbody>');
                        $('#tblExistingLabOrders').append(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#tblExistingLabOrders').html("Norecord");
                    }
                }
                else {
                    console.log(data);
                }
            }
           
        }
    });
}

function LoadIPActiveInvoices() {
    var pateintdata = {
        Dml_Indicator: "SVL",
        visit_report_id: $('#IPVisitReportId').val(),
        patient_id: $('#IPPatient_Id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/IPVisitPatientDetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(pateintdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject(data2.data)) {

            }
            else {

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

                    if (data1.Table2.length > 0) {
                        $('#tblActiveInvoice tbody').empty();
                        var tr = "";
                        for (var i = 0; i < data1.Table2.length; i++) {

                            tr = tr + '<tr><td>' + data1.Table2[i].invoice_id + '</td><td>' + data1.Table2[i].invoice_date + '</td><td>' + data1.Table2[i].invoice_description + '</td><td>' + data1.Table2[i].invoice_amount + '</td></tr>';

                        }

                        $('#tblActiveInvoice tbody').append(tr);
                    }
                    else {
                        $('#tblActiveInvoice tbody').empty();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#btnGenerateInvoice').click(function () {

    var totalRows = $('#tblExistingLabOrders tbody tr').length;
    if (totalRows == 0) {
        toastr.warning("No lab orders shown");
        return false;
    }
    var j = 0;
    $('#tblExistingLabOrders tbody tr').each(function () {
        
        var order_id = $(this).find("td").eq(0).html();
        var InvoiceAmount = $(this).find("td").eq(4).html();

        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = d.getFullYear() + '-' +
            (month < 10 ? '0' : '') + month + '-' +
            (day < 10 ? '0' : '') + day;
        var InvoiceDate = output;
        var InvoiceName = 'LabOrder ' + order_id;       
        var inv_status = '1';

        var invoice = {
            Patient_id: $('#IPPatient_Id').val(),
            doctor_id: $('#HiddenDoctorID').val(),
            invoice_description: InvoiceName,
            invoice_date: InvoiceDate,
            invoice_amount: InvoiceAmount,
            invoice_status: inv_status,
            balance_amount: InvoiceAmount,
            order_id: order_id,
            Dml_Indicator: 'IPI',
            visit_report_id: $('#IPVisitReportId').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/invoice_payment',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(invoice),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                    toastr.warning("Something went wrong. Try again later");
                }
                else {

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

                        j++;
                        if (totalRows == j) {
                            toastr.success("Invoice Added successfully");
                            LoadIPLabOrder();
                            LoadIPActiveInvoices();
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
       
    });
   
});


$('#btnAddInvoice').click(function () {
    var InvoiceDate = $('#InvoiceDate').val();
    var InvoiceName = $('#InvoiceName').val();
    var InvoiceAmount = $('#InvoiceAmount').val();
    if ($.trim(InvoiceDate) == '') {
        $('#PInvoiceDate').show();
        $('#PInvoiceDate').fadeOut(8000);
        $('#PInvoiceDate').html('Select the invoice date');
        $('#InvoiceDate').focus();
        $('#InvoiceDate').val('');
        return false;
    }
    if ($.trim(InvoiceName) == '') {
        $('#PInvoiceName').show();
        $('#PInvoiceName').fadeOut(8000);
        $('#PInvoiceName').html('Enter the invoice name');
        $('#InvoiceName').focus();
        $('#InvoiceName').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the invoice amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '0') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the valid amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    var InvoiceDates = InvoiceDate.split('/');
    InvoiceDate = InvoiceDates[2] + "-" + InvoiceDates[1] + "-" + InvoiceDates[0];
    var invoice = {
        Patient_id: $('#IPPatient_Id').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        invoice_description: $('#InvoiceName').val(),
        invoice_date: InvoiceDate,
        invoice_amount: $('#InvoiceAmount').val(),
        invoice_status: 1,
        balance_amount: $('#InvoiceAmount').val(),
        Dml_Indicator: 'IPI',
        visit_report_id: $('#IPVisitReportId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data1.length > 0) {
                        debugger;
                        $('#tblActiveInvoice tbody').empty();
                        var tr = "";
                        for (var i = 0; i < data1.length; i++) {
                            tr = tr + '<tr><td>' + data1[i].invoice_id + '</td><td>' + data1[i].invoice_date + '</td><td>' + data1[i].invoice_description + '</td><td>' + data1[i].invoice_amount + '</td></tr>';

                        }

                        $('#tblActiveInvoice tbody').append(tr);
                    }
                }
                else {
                    console.log(data);
                }

            }
            $('#InvoiceDate').val('');
            $('#InvoiceName').val('');
            $('#InvoiceAmount').val('');

        }
    });
});