let reportdetail;
$(document).ready(function () {

    //transfer stock
    //not send
    // sent
    // transfer no

    //receive stock
    //pending
    //confirmed
    //confirm no

    //return stock
    //pending
    //confirmed
    //return no

    loadbranches(JSON.parse(GET_BranchList()))

    $('#fromdatepicker').val(getDateTime().substr(0, 10))
    $('#todatepicker').val(getDateTime().substr(0, 10))

})

$(function () {
    $('#fromdatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
    $('#todatepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
});

$(document).on('click', '#ul-reports  li a', function () {

    document.getElementById('btn-report').innerText = $(this)[0].innerText;

    if ($(this)[0].innerText.toLowerCase().trim() == 'transfer stock') {
        $('#label-status').text('Send Status');
        $('#label-no').text('Transfer No. :');
        let status = [{ 'status': 'Pending' }, { 'status': 'Sent' }]

        document.getElementById('ul-status').innerHTML = ''
        var li = document.createElement('li')
        li.id = "u-status"
        document.getElementById('ul-status').appendChild(li)
        for (const item of status) {
            //console.log()
            var a = document.createElement('a')
            a.className = 'dropdown-item text-capitalize'
            a.innerHTML = item['status']
            document.getElementById(li.id).appendChild(a)
        }
    }

    if ($(this)[0].innerText.toLowerCase().trim() == 'receive stock') {
        $('#label-status').text('Confirm Status');
        $('#label-no').text('Confirm No. :');
        let status = [{ 'status': 'Pending' }, { 'status': 'Confirmed' }]

        document.getElementById('ul-status').innerHTML = ''
        var li = document.createElement('li')
        li.id = "u-status"
        document.getElementById('ul-status').appendChild(li)
        for (const item of status) {
            //console.log()
            var a = document.createElement('a')
            a.className = 'dropdown-item text-capitalize'
            a.innerHTML = item['status']
            document.getElementById(li.id).appendChild(a)
        }
    }

    if ($(this)[0].innerText.toLowerCase().trim() == 'return stock') {
        $('#label-no').text('Return No. :');
        $('#label-status').text('Confirm Status');
        let status = [{ 'status': 'Pending' }, { 'status': 'Confirmed' }]

    }
});

$(document).on('click', '#ul-frombranch  li a', function () {
    document.getElementById('btn-frombranch').innerText = $(this)[0].innerText;
});

$(document).on('click', '#ul-tobranch  li a', function () {
    document.getElementById('btn-tobranch').innerText = $(this)[0].innerText;
});

$(document).on('click', '#ul-status  li a', function () {
    document.getElementById('btn-status').innerText = $(this)[0].innerText;
});


$(document).on('click', '#button-generate', function () {

    //if (('#btn-report').text().toLowerCase().trim()) {
    //    Swal.fire({
    //        position: "center",
    //        icon: "info",
    //        text: "Please select item",
    //        showConfirmButton: false,
    //        timer: 1500
    //    }).then((result) => {
    //        return;
    //    });
    //}

    let frombranch = $('#btn-frombranch').text().toLowerCase().trim();
    let tobranch = $('#btn-tobranch').text().toLowerCase().trim();
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))

    let fromdb = branches.filter((e) => e['fullname'].toLowerCase().trim() == frombranch);
    let todb = branches.filter((e) => e['fullname'].toLowerCase().trim() == tobranch);

    let fromdate = $('#fromdatepicker').val();

    let todate = $('#todatepicker').val();

    let status = $('#btn-status').text().toLowerCase().trim();

    let reportlist;

    if ($('#btn-report').text().toLowerCase().trim() == 'transfer stock') {
        reportlist = JSON.parse(GET_TransferStockList(fromdb['0']['name']))

        if ($('#btn-tobranch').text().toLowerCase().trim() != 'all') {
            reportlist = reportlist.filter((e) => e['tobranchid'] == todb[0]['branchid']);
        }

        if (status == 'pending') {
            reportlist = reportlist.filter((e) => e['sendflag'] == 0)
        }

        if (status == 'sent') {
            reportlist = reportlist.filter((e) => e['sendflag'] == 1)
        }

        //filter by date
        reportlist = reportlist.filter((e) => e['transferdate'].substring(0, 10) >= fromdate && e['transferdate'].substring(0, 10) <= todate);

        //search by transfer no
        if ($('#input-no').val().toLowerCase().trim() != '') {
            reportlist = reportlist.filter((e) => e['transferno'].toLowerCase().trim() == $('#input-no').val().toLowerCase().trim());
        }

     
        if (reportlist.length == 0) {
            Swal.fire({
                position: "center",
                icon: "info",
                text: "No report found",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                return;
            });
        }

       
        load_TransferData(reportlist)
    }

    if ($('#btn-report').text().toLowerCase().trim() == 'receive stock') {
        //transfer
        reportlist = JSON.parse(GET_ReceiveStockList(todb[0]['name']));

        if ($('#btn-tobranch').text().toLowerCase().trim() != 'all') {
            reportlist = reportlist.filter((e) => e['frombranchid'] == fromdb[0]['branchid']);
        }

        if (status == 'pending') {
            reportlist = reportlist.filter((e) => e['confirmflag'] == 0)
        }

        if (status == 'confirmed') {
            reportlist = reportlist.filter((e) => e['confirmflag'] == 1)
        }

        //filter by date
        reportlist = reportlist.filter((e) => e['confirmdatetime'].substring(0, 10) >= fromdate && e['confirmdatetime'].substring(0, 10) <= todate);


        //search by confirm no
        if ($('#input-no').val().toLowerCase().trim() != '') {
            reportlist = reportlist.filter((e) => e['confirmno'].toLowerCase().trim() == $('#input-no').val().toLowerCase().trim());
        }

        if (reportlist.length == 0) {
            Swal.fire({
                position: "center",
                icon: "info",
                text: "No report found",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                return;
            });
        }
        load_ReceiveData(reportlist)
    }

    if ($('#btn-report').text().toLowerCase().trim() == 'return stock') {
        reportlist = JSON.parse(GET_ReturnStockList(fromdb[0]['name']));
        if ($('#btn-tobranch').text().toLowerCase().trim() != 'all') {
            reportlist = reportlist.filter((e) => e['tobranchid'] == todb[0]['branchid']);
        }

        reportlist = reportlist.filter((e) => e['returndate'].substring(0, 10) >= fromdate && e['returndate'].substring(0, 10) <= todate);

        //search by confirm no
        if ($('#input-no').val().toLowerCase().trim() != '') {
            reportlist = reportlist.filter((e) => e['returnno'].toLowerCase().trim() == $('#input-no').val().toLowerCase().trim());
        }

        if (reportlist.length == 0) {
            Swal.fire({
                position: "center",
                icon: "info",
                text: "No report found",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                return;
            });
        }
        load_ReturnData(reportlist)
    }
})

$(document).on('click', 'button', function () {
    if ($(this)[0].innerHTML.toLowerCase().trim() == 'preview') {

        reportdetail = '';
        let no = $(this).closest('tr').find('td:eq(1)').text();
        let frombranchname = $(this).closest('tr').find('td:eq(3)').text();
        let tobranchname = $(this).closest('tr').find('td:eq(4)').text();
        let tobranch = $('#btn-tobranch').text().toLowerCase().trim();
        
        let branches = JSON.parse(sessionStorage.getItem('branchlist'))
        let fromdb = branches.filter((e) => e['fullname'].toLowerCase().trim() == frombranchname.toLowerCase().trim());
        let todb = branches.filter((e) => e['fullname'].toLowerCase().trim() == tobranchname.toLowerCase().trim());
      

        let generatereport;

        if ($('#btn-report').text().toLowerCase().trim() == 'transfer stock') {
            $('#modal-preview-tranfer').modal('show');           
            generatereport = JSON.parse(GET_TransferStockList(fromdb[0]['name']))
            generatereport = generatereport.filter((e) => e['transferno'].toLowerCase().trim() == no.toLowerCase().trim());
            reportdetail = generatereport;

            let sendstatus;
            if (reportdetail[0]['sendflag'] == 0) {
                sendstatus = 'Pending'
            } else {
                sendstatus = 'Sent'
            }

            let confirmstatus;
            if (reportdetail[0]['confirmflag'] == 0) {
                confirmstatus = 'Pending'
            } else {
                confirmstatus = 'Confirmed'
            }


            $('#label-Tfrombranchname').text(fromdb[0]['fullname'].toUpperCase().trim());
            $('#label-Ttransferno').text(reportdetail[0]['transferno']);
            $('#label-Ttransferdate').text(reportdetail[0]['transferdate'].substring(0,10));
            $('#label-Tfromsenddate').text(reportdetail[0]['senddatetime'].substring(0,10));
            $('#label-Tfromstatus').text(sendstatus);

            $('#label-Ttobranchname').text(todb[0]['fullname'].toUpperCase().trim());
            $('#label-Tconfirmno').text(reportdetail[0]['confirmno']);
            $('#label-Ttosenddate').text(reportdetail[0]['senddatetime'].substring(0, 10));
            $('#label-Ttoconfirmdate').text(reportdetail[0]['confirmdatetime'].substring(0, 10));            
            $('#lbl-Ttostatus').text(confirmstatus);

            generatePreviewTransfer(generatereport, fromdb[0]['name'])
        }

        if ($('#btn-report').text().toLowerCase().trim() == 'receive stock') {
            $('#modal-preview-receive').modal('show');
            generatereport = JSON.parse(GET_ReceiveStockList(todb[0]['name']));
            generatereport = generatereport.filter((e) => e['confirmno'].toLowerCase().trim() == no.toLowerCase().trim());
            //GenerateReceivePDF(generatereport, $('#btn-report').text())
            reportdetail = generatereport;


            let sendstatus;
            if (reportdetail[0]['sendflag'] == 0) {
                sendstatus = 'Pending'
            } else {
                sendstatus = 'Sent'
            }

            let confirmstatus;
            if (reportdetail[0]['confirmflag'] == 0) {
                confirmstatus = 'Pending'
            } else {
                confirmstatus = 'Confirmed'
            }

            $('#label-Rfrombranchname').text(fromdb[0]['fullname'].toUpperCase().trim());
            $('#label-Rtransferno').text(reportdetail[0]['transferno']);
            $('#label-Rtransferdate').text(reportdetail[0]['transferdate'].substring(0, 10));
            $('#label-Rfromsenddate').text(reportdetail[0]['senddatetime'].substring(0, 10));
            $('#label-Rfromstatus').text(sendstatus);

            $('#label-Rtobranchname').text(todb[0]['fullname'].toUpperCase().trim());
            $('#label-Rconfirmno').text(reportdetail[0]['confirmno']);
            $('#label-Rtosenddate').text(reportdetail[0]['senddatetime'].substring(0, 10));
            $('#label-Rtoconfirmdate').text(reportdetail[0]['confirmdatetime'].substring(0, 10));
            $('#lbl-Rtostatus').text(confirmstatus);

            generatePreviewReceive(generatereport, todb[0]['name'])
        }

        if ($('#btn-report').text().toLowerCase().trim() == 'return stock') {
            $('#modal-preview-return').modal('show');
            generatereport = JSON.parse(GET_ReturnStockList(fromdb[0]['name']));
            generatereport = generatereport.filter((e) => e['returnno'].toLowerCase().trim() == no.toLowerCase().trim());
            //GenerateReceivePDF(generatereport, $('#btn-report').text())
            reportdetail = generatereport;


            let sendstatus;
          

            let confirmstatus;
            if (reportdetail[0]['confirmflag'] == 0) {
                confirmstatus = 'Pending'
            } else {
                confirmstatus = 'Confirmed'
            }

            $('#label-Retfrombranchname').text(fromdb[0]['fullname'].toUpperCase().trim());
            $('#label-Rettransferno').text(reportdetail[0]['returnno']);
            $('#label-Rettransferdate').text(reportdetail[0]['returndate'].substring(0, 10));
            $('#label-Retfromsenddate').text(reportdetail[0]['transdate'].substring(0, 10));
            $('#label-Retfromstatus').text('Confirmed');

            $('#label-Rettobranchname').text(todb[0]['fullname'].toUpperCase().trim());
            $('#label-Retconfirmno').text(reportdetail[0]['confirmno']);
            //$('#label-Rettosenddate').text(reportdetail[0]['returndate'].substring(0, 10));
            $('#label-Rettoconfirmdate').text(reportdetail[0]['returndate'].substring(0, 10));
            $('#lbl-Rettostatus').text('Confirmed');


            generatePreviewReturn(generatereport, fromdb[0]['name'])
        }
    }

});

$(document).on('click', '#button-pdf', function () {
    if ($('#btn-report').text().toLowerCase().trim() == 'transfer stock') {
        GenerateTransferPDF(reportdetail, $('#btn-report').text())
    }

    if ($('#btn-report').text().toLowerCase().trim() == 'receive stock') {
        GenerateReceivePDF(reportdetail, $('#btn-report').text())
    }

    if ($('#btn-report').text().toLowerCase().trim() == 'return stock') {
        GenerateReturnPDF(reportdetail, $('#btn-report').text())
    }

});

function generatePreviewTransfer(data,db) {

    const tblbody = document.getElementById('tbody-preivew-report')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    //let inventory = JSON.parse(GET_InventoryDetail(db));
    let inventory = InventoryWithCostDetail(db);
    tblbody.innerHTML = "";
    $.each(data[0]['transferStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        let x = key + 1;

        let tr = document.createElement('tr');

        let tdcount = document.createElement('td');
        tdcount.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let count = document.createTextNode(x);

        let tdinventoryid = document.createElement('td');
        tdinventoryid.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let inventoryid = document.createTextNode(detail['inventoryid'].toString().trim());

        let tdbarcode = document.createElement('td');
        tdbarcode.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let barcode = document.createTextNode(item[0]['barcode'].toString().trim());

        let tdname = document.createElement('td');
        tdname.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let name = document.createTextNode(item[0]['name'].toString().trim());

        let tddesc = document.createElement('td');
        tddesc.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let desc = document.createTextNode(item[0]['description'].toString().trim());

        let tdunit = document.createElement('td')
        tdunit.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let unit = document.createTextNode("PCS")

        let tdbatch = document.createElement('td');
        tdbatch.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let batch = document.createTextNode(detail['batchid'].toString().trim());

        let tdcost = document.createElement('td');
        tdcost.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let cost = document.createTextNode(detail['cost']);

        let tdquantity = document.createElement('td');
        tdquantity.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let quantity = document.createTextNode(detail['qty'].toFixed(2))

        tdcount.appendChild(count);
        tdinventoryid.appendChild(inventoryid);
        tdbarcode.appendChild(barcode);
        tdname.appendChild(name);
        tddesc.appendChild(desc);
        tdunit.appendChild(unit);
        tdbatch.appendChild(batch);
        tdcost.appendChild(cost);
        tdquantity.appendChild(quantity);

        tr.appendChild(tdcount)
        tr.appendChild(tdinventoryid);
        tr.appendChild(tdbarcode);
        tr.appendChild(tdname);
        tr.appendChild(tddesc);
        tr.appendChild(tdunit);
        tr.appendChild(tdbatch);
        tr.appendChild(tdcost)
        tr.appendChild(tdquantity);
        tblbody.appendChild(tr);
    })
}

function generatePreviewReceive(data,db) {
    console.log(data)
    const tblbody = document.getElementById('tbody-report-receive')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    //let inventory = JSON.parse(GET_InventoryDetail(db));
    let inventory = InventoryWithCostDetail(db);
    tblbody.innerHTML = "";
    $.each(data[0]['receiveStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        let x = key + 1;

        let tr = document.createElement('tr');

        let tdcount = document.createElement('td');
        tdcount.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let count = document.createTextNode(x);

        let tdinventoryid = document.createElement('td');
        tdinventoryid.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let inventoryid = document.createTextNode(detail['inventoryid'].toString().trim());

        let tdbarcode = document.createElement('td');
        tdbarcode.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let barcode = document.createTextNode(item[0]['barcode'].toString().trim());

        let tdname = document.createElement('td');
        tdname.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let name = document.createTextNode(item[0]['name'].toString().trim());

        let tddesc = document.createElement('td');
        tddesc.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let desc = document.createTextNode(item[0]['description'].toString().trim());

        let tdunit = document.createElement('td')
        tdunit.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let unit = document.createTextNode("PCS")

        let tdbatch = document.createElement('td');
        tdbatch.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let batch = document.createTextNode(detail['batchid'].toString().trim());

        let tdcost = document.createElement('td');
        tdcost.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let cost = document.createTextNode(detail['cost']);

        let tdquantity = document.createElement('td');
        tdquantity.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let quantity = document.createTextNode(detail['qty'].toFixed(2))

        let tdacceptqty = document.createElement('td');
        tdacceptqty.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let acceptqty = document.createTextNode(detail['acceptedqty'].toFixed(2))

        let tdrejectqty = document.createElement('td');
        tdrejectqty.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let rejectqty = document.createTextNode(detail['rejectedqty'].toFixed(2))

        tdcount.appendChild(count);
        tdinventoryid.appendChild(inventoryid);
        tdbarcode.appendChild(barcode);
        tdname.appendChild(name);
        tddesc.appendChild(desc);
        tdunit.appendChild(unit);
        tdbatch.appendChild(batch);
        tdcost.appendChild(cost);
        tdquantity.appendChild(quantity);
        tdacceptqty.appendChild(acceptqty);
        tdrejectqty.appendChild(rejectqty);

        tr.appendChild(tdcount)
        tr.appendChild(tdinventoryid);
        tr.appendChild(tdbarcode);
        tr.appendChild(tdname);
        tr.appendChild(tddesc);
        tr.appendChild(tdunit);
        tr.appendChild(tdbatch);
        tr.appendChild(tdcost)
        tr.appendChild(tdquantity);
        tr.appendChild(tdacceptqty)
        tr.appendChild(tdrejectqty);
        tblbody.appendChild(tr);
    })
}

function generatePreviewReturn(data,db) {

    const tblbody = document.getElementById('tbody-report-return')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    //let inventory = JSON.parse(GET_InventoryDetail(db));
      let inventory = InventoryWithCostDetail(db);
    tblbody.innerHTML = "";


    console.log(data)
    $.each(data[0]['returnStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        let x = key + 1;

        let tr = document.createElement('tr');

        let tdcount = document.createElement('td');
        tdcount.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let count = document.createTextNode(x);

        let tdinventoryid = document.createElement('td');
        tdinventoryid.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let inventoryid = document.createTextNode(detail['inventoryid'].toString().trim());

        let tdbarcode = document.createElement('td');
        tdbarcode.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let barcode = document.createTextNode(item[0]['barcode'].toString().trim());

        let tdname = document.createElement('td');
        tdname.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let name = document.createTextNode(item[0]['name'].toString().trim());

        let tddesc = document.createElement('td');
        tddesc.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let desc = document.createTextNode(item[0]['description'].toString().trim());

        let tdunit = document.createElement('td')
        tdunit.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let unit = document.createTextNode("PCS")

        let tdbatch = document.createElement('td');
        tdbatch.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let batch = document.createTextNode(detail['batchid'].toString().trim());

        let tdcost = document.createElement('td');
        tdcost.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let cost = document.createTextNode(detail['cost']);

        let tdquantity = document.createElement('td');
        tdquantity.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
        let quantity = document.createTextNode(detail['returnqty'].toFixed(2))

        tdcount.appendChild(count);
        tdinventoryid.appendChild(inventoryid);
        tdbarcode.appendChild(barcode);
        tdname.appendChild(name);
        tddesc.appendChild(desc);
        tdunit.appendChild(unit);
        tdbatch.appendChild(batch);
        tdcost.appendChild(cost);
        tdquantity.appendChild(quantity);

        tr.appendChild(tdcount)
        tr.appendChild(tdinventoryid);
        tr.appendChild(tdbarcode);
        tr.appendChild(tdname);
        tr.appendChild(tddesc);
        tr.appendChild(tdunit);
        tr.appendChild(tdbatch);
        tr.appendChild(tdcost)
        tr.appendChild(tdquantity);
        tblbody.appendChild(tr);
    })
}

function load_TransferData(data) {

    const tblbody = document.getElementById('tbody-report-list')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    tblbody.innerHTML = "";
    $.each(data, function (key, detail) {
        let frombranch = branches.filter((e) => e['branchid'] == detail['frombranchid'])
        let tobranch = branches.filter((e) => e['branchid'] == detail['tobranchid'])

        let tr = document.createElement('tr');
        //send status
        let sendstatus;
        if (detail['sendflag'] == 0) {
            sendstatus = 'Pending'
        } else {
            sendstatus = 'Sent'
        }

        let tdnumber = document.createElement('td');
        tdnumber.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let number = document.createTextNode(parseInt(key) + 1);


        let tdtransferno = document.createElement('td');
        tdtransferno.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let transferno = document.createTextNode(detail['transferno'].toString().trim());


        let tddate = document.createElement('td');
        tddate.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let date = document.createTextNode(detail['transferdate'].substring(0, 10).toString().trim());

        let tdfrom = document.createElement('td');
        tdfrom.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let from = document.createTextNode(frombranch[0]['fullname'].toString().trim());

        let tdto = document.createElement('td');
        tdto.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let to = document.createTextNode(tobranch[0]['fullname'].toString().trim());

        let tdstatus = document.createElement('td');
        tdstatus.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let status = document.createTextNode(sendstatus);

        let tdaction = document.createElement('td');
        tdaction.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';

        var action = document.createElement('div')
        action.id = Math.random().toString(16).substring(2, 16);

        tdnumber.appendChild(number);
        tdtransferno.appendChild(transferno);
        tddate.appendChild(date);
        tdfrom.appendChild(from);
        tdto.appendChild(to);
        tdstatus.appendChild(status);
        tdaction.appendChild(action);

        tr.appendChild(tdnumber);
        tr.appendChild(tdtransferno);
        tr.appendChild(tddate);
        tr.appendChild(tdfrom);
        tr.appendChild(tdto);
        tr.appendChild(tdstatus);
        tr.appendChild(tdaction);

        tblbody.appendChild(tr);


        var viewdetail = document.createElement('button')
        viewdetail.type = 'button'
        viewdetail.className = 'btn btn-outline-primary btn-xs m-1'
        viewdetail.innerText = 'Preview'
        document.getElementById(action.id).appendChild(viewdetail);
    });
}

function load_ReceiveData(data) {
    const tblbody = document.getElementById('tbody-report-list')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    tblbody.innerHTML = "";
    $.each(data, function (key, detail) {
        let frombranch = branches.filter((e) => e['branchid'] == detail['frombranchid'])
        let tobranch = branches.filter((e) => e['branchid'] == detail['tobranchid'])

        let tr = document.createElement('tr');
        //send status
        let sendstatus;
        if (detail['confirmflag'] == 0) {
            sendstatus = 'Pending'
        } else {
            sendstatus = 'Confirmed'
        }

        let tdnumber = document.createElement('td');
        tdnumber.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let number = document.createTextNode(parseInt(key) + 1);


        let tdtransferno = document.createElement('td');
        tdtransferno.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let transferno = document.createTextNode(detail['confirmno'].toString().trim());


        let tddate = document.createElement('td');
        tddate.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let date = document.createTextNode(detail['confirmdatetime'].substring(0, 10).toString().trim());

        let tdfrom = document.createElement('td');
        tdfrom.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let from = document.createTextNode(frombranch[0]['fullname'].toString().trim());

        let tdto = document.createElement('td');
        tdto.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let to = document.createTextNode(tobranch[0]['fullname'].toString().trim());

        let tdstatus = document.createElement('td');
        tdstatus.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let status = document.createTextNode(sendstatus);

        let tdaction = document.createElement('td');
        tdaction.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';

        var action = document.createElement('div')
        action.id = Math.random().toString(16).substring(2, 16);

        tdnumber.appendChild(number);
        tdtransferno.appendChild(transferno);
        tddate.appendChild(date);
        tdfrom.appendChild(from);
        tdto.appendChild(to);
        tdstatus.appendChild(status);
        tdaction.appendChild(action);

        tr.appendChild(tdnumber);
        tr.appendChild(tdtransferno);
        tr.appendChild(tddate);
        tr.appendChild(tdfrom);
        tr.appendChild(tdto);
        tr.appendChild(tdstatus);
        tr.appendChild(tdaction);

        tblbody.appendChild(tr);


        var viewdetail = document.createElement('button')
        viewdetail.type = 'button'
        viewdetail.className = 'btn btn-outline-primary btn-xs m-1'
        viewdetail.innerText = 'Preview'
        document.getElementById(action.id).appendChild(viewdetail);
    });
}

function load_ReturnData(data) {

    const tblbody = document.getElementById('tbody-report-list')
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    if (tblbody == null) {
        return
    }

    tblbody.innerHTML = "";
    $.each(data, function (key, detail) {
        let frombranch = branches.filter((e) => e['branchid'] == detail['frombranchid'])
        let tobranch = branches.filter((e) => e['branchid'] == detail['tobranchid'])

        let tr = document.createElement('tr');
        //send status
        let sendstatus;
        if (detail['confirmflag'] == 0) {
            sendstatus = 'Pending'
        } else {
            sendstatus = 'Confirmed'
        }

        let tdnumber = document.createElement('td');
        tdnumber.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let number = document.createTextNode(parseInt(key) + 1);


        let tdtransferno = document.createElement('td');
        tdtransferno.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let transferno = document.createTextNode(detail['returnno'].toString().trim());


        let tddate = document.createElement('td');
        tddate.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let date = document.createTextNode(detail['returndate'].substring(0, 10).toString().trim());

        let tdfrom = document.createElement('td');
        tdfrom.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let from = document.createTextNode(frombranch[0]['fullname'].toString().trim());

        let tdto = document.createElement('td');
        tdto.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center text-capitalize';
        let to = document.createTextNode(tobranch[0]['fullname'].toString().trim());

        let tdstatus = document.createElement('td');
        tdstatus.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
        let status = document.createTextNode(sendstatus);

        let tdaction = document.createElement('td');
        tdaction.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';

        var action = document.createElement('div')
        action.id = Math.random().toString(16).substring(2, 16);

        tdnumber.appendChild(number);
        tdtransferno.appendChild(transferno);
        tddate.appendChild(date);
        tdfrom.appendChild(from);
        tdto.appendChild(to);
        tdstatus.appendChild(status);
        tdaction.appendChild(action);

        tr.appendChild(tdnumber);
        tr.appendChild(tdtransferno);
        tr.appendChild(tddate);
        tr.appendChild(tdfrom);
        tr.appendChild(tdto);
        tr.appendChild(tdstatus);
        tr.appendChild(tdaction);

        tblbody.appendChild(tr);


        var viewdetail = document.createElement('button')
        viewdetail.type = 'button'
        viewdetail.className = 'btn btn-outline-primary btn-xs m-1'
        viewdetail.innerText = 'Preview'
        document.getElementById(action.id).appendChild(viewdetail);
    });
}

function GenerateTransferPDF(data, header) {
    let lineY = 30;
    let lineX = 15;
    let sendstatus;
    let confirmstatus;
    let confirmdate;
    let senddate;

    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let frombranch = branches.filter((e) => e['branchid'] == data[0]['frombranchid'])

    let tobranch = branches.filter((e) => e['branchid'] == data[0]['tobranchid'])

    senddate = data[0]['senddatetime'].substring(0, 10);
    confirmdate = data[0]['confirmdatetime'].substring(0, 10);

    if (senddate == '0001-01-01') {
        senddate = "N/A"
    }

    if (confirmdate == '0001-01-01') {
        confirmdate = "N/A"
    }

    if (data[0]['sendflag'] == 0) {
        sendstatus = 'Pending'
    } else {
        sendstatus = 'Sent'
    }

    if (data[0]['confirmflag'] == 0) {
        confirmstatus = 'Pending'
    } else {
        confirmstatus = 'Confirmed'
    }

    //let inventory = JSON.parse(GET_InventoryDetail(frombranch[0]['name']));
  let inventory = InventoryWithCostDetail(frombranch[0]['name']);
    const doc = new jsPDF();

    // Invoice Header
    doc.setFontSize(20);
    doc.text(header.toUpperCase() + " REPORT", 60, 20);


    // Company Information
    doc.setFontSize(12);
    doc.text("Branch From : " + frombranch[0]['fullname'].toUpperCase(), lineX, lineY);
    doc.text("Transfer No. : " + data[0]['transferno'], lineX, 35);
    doc.text("Transfer Date : " + data[0]['transferdate'].substring(0, 10), lineX, 40);
    doc.text("Send Date : " + data[0]['transferdate'].substring(0, 10), lineX, 45);
    doc.text("Status : " + sendstatus, lineX, 50);


    // Client Information
    doc.text("Branch To : " + tobranch[0]['fullname'].toUpperCase(), lineX, 60);
    doc.text("Confirm  No. : " + data[0]['confirmno'], lineX, 65);
    doc.text("Sent Date : " + senddate, lineX, 70);
    doc.text("Confirm Date : " + confirmdate, lineX, 75);
    doc.text("Status : " + confirmstatus, lineX, 80);
    //console.log(JSON.stringify(data[0]['transferStockDetailedCosts']))

    // Invoice Table

    let arritem = [];
    let i = 1;
    $.each(data[0]['transferStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        item = [i, item[0]['barcode'], item[0]['name'], item[0]['description'], "PCS", detail['batchid'], detail['cost'].toFixed(2), detail['qty'].toFixed(2)]
        arritem.push(item)
        i = i + 1
    })

    doc.autoTable({
        startY: 90,
        head: [['#', 'Barcode', 'Name', 'Description', 'Unit', 'Batch #', 'Cost', 'Send QTY']],
        columnStyles: { 0: { halign: 'center' }, 6: { halign: 'center' }, 7: { halign: 'center' } },
        body: arritem,
    });


    // Invoice Total
    //let finalY = doc.previousAutoTable.finalY; // The y position after the table
    //doc.setFontSize(12);
    //doc.text('Subtotal: $65.00', 150, finalY + 10);
    //doc.text('Tax (10%): $6.50', 150, finalY + 20);
    //doc.text('Total: $71.50', 150, finalY + 30);

    // Footer
    doc.setFontSize(10);
    //doc.text('Thank you for your business!', 20, 280);
    //doc.text('Please make the payment by the due date.', 20, 285);

    // Save the PDF
    doc.save(header.toUpperCase() + getDateTime() + '.pdf');
    console.log(document.location.href)

}

function GenerateReceivePDF(data, header) {
    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let frombranch = branches.filter((e) => e['branchid'] == data[0]['frombranchid'])

    let tobranch = branches.filter((e) => e['branchid'] == data[0]['tobranchid'])

    let lineY = 30;
    let sendstatus;
    let confirmstatus;

    if (data[0]['sendflag'] == 0) {
        sendstatus = 'Pending'
    } else {
        sendstatus = 'Sent'
    }

    if (data[0]['confirmflag'] == 0) {
        confirmstatus = 'Pending'
    } else {
        confirmstatus = 'Confirmed'
    }

    //let inventory = JSON.parse(GET_InventoryDetail(frombranch[0]['name']));
     let inventory = InventoryWithCostDetail(frombranch[0]['name']);
    const doc = new jsPDF();

    // Invoice Header
    doc.setFontSize(20);
    doc.text(header.toUpperCase() + " REPORT", 60, 20);

    // Company Information
    doc.setFontSize(11);
    doc.text("Branch From : " + frombranch[0]['fullname'].toUpperCase(), 20, lineY);
    doc.text("Transfer No. : " + data[0]['transferno'], 20, 35);
    doc.text("Transfer Date : " + data[0]['transferdate'].substring(0, 10), 20, 40);
    doc.text("Send Date : " + data[0]['transferdate'].substring(0, 10), 20, 45);
    doc.text("Status : " + sendstatus, 20, 50);


    // Client Information
    doc.text("Branch To : " + tobranch[0]['fullname'].toUpperCase(), 20, 60);
    doc.text("Confirm  No. : " + data[0]['confirmno'], 20, 65);
    doc.text("Sent Date : " + data[0]['senddatetime'].substring(0, 10), 20, 70);
    doc.text("Confirm Date : " + data[0]['confirmdatetime'].substring(0, 10), 20, 75);
    doc.text("Status : " + confirmstatus, 20, 80);


    // Invoice Table
    let arritem = [];
    let i = 1;
    $.each(data[0]['receiveStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        item = [i, item[0]['barcode'], item[0]['name'], item[0]['description'], "PCS", detail['batchid'], detail['cost'].toFixed(2), detail['qty'].toFixed(2), detail['acceptedqty'].toFixed(2), detail['rejectedqty'].toFixed(2)]
        arritem.push(item)
        i = i + 1
    })

    doc.autoTable({
        startY: 90,
        styles: { halign: 'center' },
        columnStyles: { 0: { halign: 'center' }, 6: { halign: 'right' }, 7: { halign: 'right' }, 8: { halign: 'right' }, 9: { halign: 'right' } }, // Cells in first column centered and green
        head: [['#', 'Barcode', 'Name', 'Description', 'Unit', 'Batch#', 'Cost', 'Send QTY', 'Accept QTY', 'Return QTY']],
        body: arritem,
        //body: [
        //    ['Item 1', '2', '$10.00', '$20.00'],
        //    ['Item 2', '1', '$15.00', '$15.00'],
        //    ['Item 3', '4', '$7.50', '$30.00']
        //],
    });

    // Footer
    //doc.setFontSize(10);
    //doc.text('Thank you for your business!', 20, 280);
    //doc.text('Please make the payment by the due date.', 20, 285);

    // Save the PDF
    doc.save(header.toUpperCase() + getDateTime() + '.pdf');
}

function GenerateReturnPDF(data, header) {
    let lineY = 30;
    let lineX = 15;
    let sendstatus;
    let confirmstatus;
    let confirmdate;
    let senddate;

    let branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let frombranch = branches.filter((e) => e['branchid'] == data[0]['frombranchid'])

    let tobranch = branches.filter((e) => e['branchid'] == data[0]['tobranchid'])

    senddate = data[0]['returndate'].substring(0, 10);
    confirmdate = data[0]['returndate'].substring(0, 10);

    if (senddate == '0001-01-01') {
        senddate = "N/A"
    }

    if (confirmdate == '0001-01-01') {
        confirmdate = "N/A"
    }

    if (data[0]['sendflag'] == 0) {
        sendstatus = 'Pending'
    } else {
        sendstatus = 'Sent'
    }

    if (data[0]['confirmflag'] == 0) {
        confirmstatus = 'Pending'
    } else {
        confirmstatus = 'Confirmed'
    }

    //let inventory = JSON.parse(GET_InventoryDetail(frombranch[0]['name']));
    let inventory = InventoryWithCostDetail(frombranch[0]['name']);
    const doc = new jsPDF();

    // Invoice Header
    doc.setFontSize(20);
    doc.text(header.toUpperCase() + " REPORT", 60, 20);


    // Company Information
    doc.setFontSize(12);
    doc.text("Branch From : " + frombranch[0]['fullname'].toUpperCase(), lineX, lineY);
    doc.text("Return No. : " + data[0]['returnno'], lineX, 35);
    doc.text("Confirm Date : " + data[0]['returndate'].substring(0, 10), lineX, 40);
    doc.text("Send Date : " + data[0]['returndate'].substring(0, 10), lineX, 45);
    doc.text("Status : " + "Confirmed", lineX, 50);


    // Client Information
    doc.text("Branch To : " + tobranch[0]['fullname'].toUpperCase(), lineX, 60);
    doc.text("Confirm  No. : " + data[0]['confirmno'], lineX, 65);    
    doc.text("Confirm Date : " + confirmdate, lineX, 75);
    doc.text("Status : " + "Confirmed", lineX, 80);
    //console.log(JSON.stringify(data[0]['transferStockDetailedCosts']))

    // Invoice Table

    let arritem = [];
    let i = 1;
    $.each(data[0]['returnStockDetailedCosts'], function (key, detail) {
        let item = inventory.filter((e) => e['inventoryid'] == detail['inventoryid'])
        item = [i, item[0]['barcode'], item[0]['name'], item[0]['description'], "PCS", detail['batchid'], detail['cost'].toFixed(2), detail['returnqty'].toFixed(2)]
        arritem.push(item)
        i = i + 1
    })

    doc.autoTable({
        startY: 90,
        head: [['#', 'Barcode', 'Name', 'Description', 'Unit', 'Batch #', 'Cost', 'Send QTY']],
        columnStyles: { 0: { halign: 'center' }, 6: { halign: 'center' }, 7: { halign: 'center' } },
        body: arritem,
    });


    // Invoice Total
    //let finalY = doc.previousAutoTable.finalY; // The y position after the table
    //doc.setFontSize(12);
    //doc.text('Subtotal: $65.00', 150, finalY + 10);
    //doc.text('Tax (10%): $6.50', 150, finalY + 20);
    //doc.text('Total: $71.50', 150, finalY + 30);

    // Footer
    doc.setFontSize(10);
    //doc.text('Thank you for your business!', 20, 280);
    //doc.text('Please make the payment by the due date.', 20, 285);

    // Save the PDF
    doc.save(header.toUpperCase() + getDateTime() + '.pdf');
    console.log(document.location.href)

}


function GET_BranchList() {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "StockReport.aspx/BranchList",
        // data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function loadbranches(branchlist) {
    let branches = [];
    for (const item of branchlist) {
        var branch = {
            'branchid': item[0],
            'name': item[1].toLowerCase().trim(),
            'fullname': item[2].toLowerCase().trim(),
            'prefix': item[4].toLowerCase().trim(),
        }
        branches.push(branch)
    }
    sessionStorage.setItem('branchlist', JSON.stringify(branches))
}

function GET_TransferStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "StockReport.aspx/GET_TransferStockList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

//get receivestocklist
function GET_ReceiveStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "StockReport.aspx/GET_ReceiveStockList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_InventoryDetail(db) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/InventoryWithCostDetail",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            returnvalue = result.d;
        }
    });
    return returnvalue;
}

function GET_ReturnStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "StockReport.aspx/GET_ReturnStockDetailList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}


function Get_Inventories(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryList",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_Categories(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_Categories",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_InventoryCostAverageDetail(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryCostAverageDetail",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function GET_InventoryCostAverage(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/GET_InventoryCostAverage",
        data: "{'db':'" + db + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error")
        },
        success: function (result) {
            RetValue = result.d
        }
    });
    return RetValue;
}

function InventoryWithCostDetail(db) {
  
    let sessioncategory = GET_Categories(db);
    let sessionitem = Get_Inventories(db);
    
    let sessionica = GET_InventoryCostAverage(db);
    let sessionicadetail =GET_InventoryCostAverageDetail(db);
  
    let ica = JSON.parse(sessionica);
    
    let inventory = JSON.parse(sessionitem).filter((e) => e['Active'] != 0 && e['Barcode'].toLowerCase() != 'round' && e['Class'] == '0');
    let category = JSON.parse(sessioncategory).filter((e) => e['Active'] != 0 && e['CategoryName'].toLowerCase() != 'round');
    let icadetail = JSON.parse(sessionicadetail);
    let arrinventory = [];
    let arricadetail = [];

    category.forEach(function (category) {
        inventory.forEach(function (inventory) {
            if (category['CategoryID'] == inventory['CategoryID']) {
                ica.forEach(function (ica) {
                    if (ica['InventoryID'] == inventory['InventoryID']) {
                        arricadetail = [];
                            icadetail.forEach(function (detail) {
                                if (detail['inventoryid'] == ica['InventoryID']) {
                                    let icadetail = {
                                        'stockid': detail['stockid'],
                                        'inventoryid': detail['inventoryid'],
                                        'batchid': detail['batchid'].trim(),
                                        'inqty': detail['inqty'],
                                        'outqty': detail['outqty'],
                                        'unitcost': detail['unitcost'],
                                        'stockdate': detail['stockdate'].trim(),
                                        'notes': detail['notes'].trim(),
                                        'expirydate': detail['expirydate'].trim(),
                                        'expiryalarm': detail['expiryalarm']
                                    }
                                    arricadetail.push(icadetail);
                                }
                            });

                        let inqty = 0;
                        let outqty = 0;

                        arricadetail.forEach(function (x) {
                            inqty = inqty + x.inqty;
                            outqty = outqty + x.outqty;

                        });

                        let item = {
                            'inventoryid': inventory['InventoryID'],
                            'barcode': inventory['Barcode'].trim(),
                            'name': inventory['InventoryName'].trim(),
                            'description': inventory['Description'].trim(),
                            'categoryid': category['CategoryID'],
                            'category': category['CategoryName'].trim(),
                            //'pquantity': ica['PQuantity'],
                            //'retailqty': ica['RetailQTY'],
                            //'qoh': parseFloat(ica['PQuantity']) - parseFloat(ica['RetailQTY']),
                            'totalinqty': inqty,
                            'totaloutqty': outqty,
                            'qoh': parseFloat(inqty) - parseFloat(outqty),
                            'icadetail': arricadetail
                        }
                        arrinventory.push(item);
                    }
                });
            }
        });
    });

    return arrinventory;
}

function getDateTime() {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    if (month.toString().length == 1) {
        month = '0' + month;
    }
    if (day.toString().length == 1) {
        day = '0' + day;
    }
    if (hour.toString().length == 1) {
        hour = '0' + hour;
    }
    if (minute.toString().length == 1) {
        minute = '0' + minute;
    }
    if (second.toString().length == 1) {
        second = '0' + second;
    }
    var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    return dateTime;

}


