let inventorydetaildata;
let itemarr = [];
let branches = [];
let transferdata;


$(document).ready(function () {
    let default_data = JSON.parse(sessionStorage.getItem('default_data'))
    const urlParams = new URL(window.location.href).searchParams;
    const transfernumber = urlParams.get('TransferNo');

    if ($(location).attr('href').toLowerCase().trim().includes('addtransferstock.aspx')) {
        if (transfernumber != null) {
            let branch = default_data['branch']
            branches = JSON.parse(sessionStorage.getItem('branchlist'))
            let selecteddb = branches.filter((e) => e['fullname'].toLowerCase().trim() == branch.toLowerCase().trim());
            transferdata = JSON.parse(get_TransferStockList(selecteddb[0]['name']));
            loadTransferStock(transferdata)
            //inventorydetaildata = JSON.parse(get_InventoryDetail(selecteddb[0]['name']));
            inventorydetaildata = InventoryWithCostDetail(selecteddb[0]['name']);

            let selecttransferdata = transferdata.filter((e) => e['transferno'].toString().trim() == transfernumber.toString().trim());
            loadExistingTransfer(selecttransferdata, selecteddb[0]['fullname'])
              $('#btn-save').attr('disabled', 'disabled');
        } else {
            let branch = default_data['branch']

            branches = JSON.parse(sessionStorage.getItem('branchlist'))
            let selecteddb = branches.filter((e) => e['fullname'].toLowerCase().trim() == branch.toLowerCase().trim());

            transferdata = JSON.parse(get_TransferStockList(selecteddb[0]['name']));

            loadTransferStock(transferdata)
            //console.log(InventoryWithCostDetail('da1'))
            //console.log(JSON.parse(get_InventoryDetail(selecteddb[0]['name'])))
            //console.log(get_InventoryDetail(selecteddb[0]['name']))
            //inventorydetaildata = JSON.parse(get_InventoryDetail(selecteddb[0]['name']));
            inventorydetaildata = InventoryWithCostDetail(selecteddb[0]['name']);

            let frombranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == branch.toLowerCase().trim())
            let transferno = 0;
            let transfernolength = '0000000';
            let newtransferno;

            if (transferdata.length > 0) {
                transferno = transferdata.slice(-1)[0]['transferno'];

                transferno = transferno.split('-')
                transferno = parseInt(transferno[1]) + 1;

                newtransferno = transfernolength + transferno;
                newtransferno = newtransferno.substring(newtransferno.length - transfernolength.length);

                $('#input-transfernumber').val(transferno[0] + "-" + newtransferno)

            } else {
                transferno = parseInt(transferno) + 1;
                newtransferno = transfernolength + transferno;
                newtransferno = newtransferno.substring(newtransferno.length - transfernolength.length);

            }

            let currentbranch = (new URL(location.href)).searchParams.get('Branchname');
            $('#input-transfernumber').val(frombranch[0]['prefix'].toString().toUpperCase() + "-" + newtransferno)
            $('#input-date').val(getDateTime().substr(0, 10))
            $('#input-branchfrom').val(currentbranch)

            const inputsearch = document.querySelector('input[type="search"]');
            if (inputsearch != null) {
                inputsearch.addEventListener("search", () => {
                    let inventories = inventorydetaildata;
                    loadSearchItem(inventories)
                });
            }
          
            $('#btn-confirm').attr('disabled', 'disabled');
        }
        dp_branch(branches)
    } else {
   

        selectedbranch()
    }



});



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

        let transferno = $(this).closest('tr').find('td:eq(1)').text();
        window.location.href = '/AddTransferStock.aspx?Branchname=' + getSelectedBranch() + '&TransferNo=' + transferno;
        let selecttransferdata = transferdata.filter((e) => e['transferno'].toString().trim() == transferno.toString().trim());
        loadExistingTransfer(selecttransferdata, branchname)

    }
    
   
    if ($(this)[0].children.length > 0) {
        if ($(this)[0].children[0].innerHTML.toLowerCase().trim() == 'edit') {
            let index = $(this).closest('tr').find('td:eq(0)').text();
            let barcode = $(this).closest('tr').find('td:eq(2)').text();
            let name = $(this).closest('tr').find('td:eq(3)').text();
            let description = $(this).closest('tr').find('td:eq(4)').text();

            let inventorydetail = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == barcode.toLowerCase().trim())
            let batchno = $(this).closest('tr').find('td:eq(6)').text();
            let icadetail = inventorydetail[0]['icadetail'].filter((e) => e['batchid'] == batchno.toLowerCase().trim())
            let qoh = parseFloat(icadetail[0]['inqty']) - parseFloat(icadetail[0]['outqty'])
            let adjustqty = $(this).closest('tr').find('td:eq(8)').text();

            $('#header-additem').text('Edit Item')
            $('#modal-additem').modal('show')

            $('#label-index').text(index);
            $('#input-barcode').val(barcode);
            $('#input-name').val(name)
            $('#input-desc').val(description)
            $('#input-batch').val(batchno)

            $('#input-qoh').val(qoh.toFixed(2))
            $('#input-cost').val(icadetail[0]['unitcost'].toFixed(2))
            $('#input-qty').val(adjustqty)
            $('#input-qty').select()

            $('#btn-search-item').attr('disabled', 'disabled');

        }

        if ($(this)[0].children[0].innerHTML.toLowerCase().trim() == 'delete') {
            Swal.fire({
                //title: "Are you sure you want to stock in with zero cost?",
                text: "Are you sure you want to delete this batch?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes"
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#btn-confirm').attr('disabled', 'disabled');
     
                    $('#btn-save').removeAttr("disabled");
                 }
            });
            //let index = $(this).closest('tr').find('td:eq(0)').text();
            //let barcode = $(this).closest('tr').find('td:eq(1)').text();
            //let name = $(this).closest('tr').find('td:eq(2)').text();
            //let description = $(this).closest('tr').find('td:eq(3)').text();

            //let inventorydetail = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == barcode.toLowerCase().trim())
            //let batchno = $(this).closest('tr').find('td:eq(5)').text();
            //let icadetail = inventorydetail[0]['icadetail'].filter((e) => e['batchid'] == batchno.toLowerCase().trim())
            //let qoh = parseFloat(icadetail[0]['inqty']) - parseFloat(icadetail[0]['outqty'])
            //let adjustqty = $(this).closest('tr').find('td:eq(7)').text();

            //$('#header-additem').text('Edit Item')
            //$('#modal-additem').modal('show')

            //$('#label-index').text(index);
            //$('#input-barcode').val(barcode);
            //$('#input-name').val(name)
            //$('#input-desc').val(description)
            //$('#input-batch').val(batchno)

            //$('#input-qoh').val(qoh.toFixed(2))
            //$('#input-cost').val(icadetail[0]['unitcost'].toFixed(2))
            //$('#input-qty').val(adjustqty)
            //$('#input-qty').select()

            //$('#btn-search-item').attr('disabled', 'disabled');
        }

        
    }

});




$(function () {
    $(document).on("click", ".sev_check", function () {
        $('.sev_check').not(this).prop('checked', false);
    });
});

$('#btn-selecteditem').click(function () {
    let hasSelected = false;
    $('#table_body_items tr').each(function () {
        $(this).find('td input:checked').each(function () {
            hasSelected = true;
        });
    });

    if (hasSelected == false) {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please select item",
            showConfirmButton: false,
            timer: 1500
        }).then((result) => {
            return;
        });
    }

    $("input.sev_check:checked").each(function () {
        let barcode = $(this).closest('tr').find('td:eq(1)').text();
        let name = $(this).closest('tr').find('td:eq(2)').text();
        let description = $(this).closest('tr').find('td:eq(3)').text();
        let inventory = inventorydetaildata.filter((e) => e['barcode'] == barcode);

        $('#lblbarcode').text(barcode);
        $('#lblname').text(name);
        $('#lbldesc').text(description);

        const tblbody = document.getElementById('table_body_batch')
        tblbody.innerHTML = "";

        const output = inventory[0]['icadetail'].reduce((accumulator, currentItem) => {
            const matchedItem = accumulator.find((item) => item['batchid'] === currentItem['batchid']);
            if (!matchedItem) {
                return [...accumulator, currentItem];
            } else {
                matchedItem['inqty'] += currentItem['inqty']
                matchedItem['outqty'] += currentItem['outqty']
                return accumulator
            }
        }, []);

        //check if already selected

        let existbatch = selectedtransferitem(output[0]['inventoryid'])
        $.each(output, function (key, detail) {
            let qoh = parseFloat(detail['inqty']) - parseFloat(detail['outqty']);

            if (qoh > 0) {

                let ifbactchexist = existbatch.filter((e) => e['Batch #'].toString().trim() == detail['batchid'].toString().trim())
                if (ifbactchexist.length == 0) {
                    let tr = document.createElement("tr");

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

                    let divchkitem = document.createElement("div");
                    divchkitem.className = "checkbox text-center";

                    let labelchkitem = document.createElement("label")
                    labelchkitem.className = "form-checkbox form-icon";
                    labelchkitem.setAttribute("for", "s_facbatch")

                    let inputchkitem = document.createElement("input")
                    inputchkitem.id = "s_facbatch";
                    inputchkitem.className = "sev_check";
                    inputchkitem.type = "checkbox"


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

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

                    let tdunitcost = document.createElement("td");
                    tdunitcost.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
                    let unitcost = document.createTextNode(detail['unitcost'].toFixed(2).trim())

                    let tdtotalqty = document.createElement("td");
                    tdtotalqty.className = 'border-start border-end border-bottom  text-left px-1 py-1 align-content-center';
                    let totalqty = document.createTextNode(qoh.toFixed(2))

                    tdchkitem.appendChild(divchkitem);
                    divchkitem.appendChild(labelchkitem);
                    labelchkitem.appendChild(inputchkitem);

                    tdbatch.appendChild(batch);
                    tdunitcost.appendChild(unitcost);
                    tdtotalqty.appendChild(totalqty);

                    tr.appendChild(tdchkitem)
                    tr.appendChild(tdbatch);
                    tr.appendChild(tdunitcost);
                    tr.appendChild(tdtotalqty);
                    tblbody.appendChild(tr);
                }
            }
        });
        $('#modal-batch-item').modal('show')
    });


})

$('#btn-select-batch').click(function () {

    let hasSelected = false;
    $('#table_body_batch tr').each(function () {
        $(this).find('td input:checked').each(function () {
            hasSelected = true;
        });
    });

    if (hasSelected == false) {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please select batch",
            showConfirmButton: false,
            timer: 1500
        }).then((result) => {

        });
    }

    $("#s_facbatch.sev_check:checked").each(function () {
        let barcode = $('#lblbarcode').text();
        let name = $('#lblname').text();
        let description = $('#lbldesc').text();
        let batchno = $(this).closest('tr').find('td:eq(1)').text();
        let unitcost = $(this).closest('tr').find('td:eq(2)').text();
        let quantity = $(this).closest('tr').find('td:eq(3)').text();

        $('#input-barcode').val(barcode);
        $('#input-name').val(name)
        $('#input-desc').val(description)
        $('#input-batch').val(batchno)
        $('#input-qoh').val(quantity)
        $('#input-cost').val(unitcost)

        $('#modal-batch-item').modal('hide')
        $('#modal-search-item').modal('hide')

        hasSelected = true
    });
})

$('#modal-batch-item').on('hidden.bs.modal', function () {
    $('#input-qty').focus();
})

$('#btn-add').click(function () {
    if ($('#input-barcode').val() == '') {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please select item",
            showConfirmButton: false,
            timer: 1500,
            didClose: (e) => {
                $('#input-qty').select()
                $('#input-qty').focus()
            },
        });
        return;
    }

    if ($('#input-qty').val() == '') {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please enter quantity",
            showConfirmButton: false,
            timer: 1500,
            didClose: (e) => {
                $('#input-qty').select()
                $('#input-qty').focus()
            },
        })
        return;
    }

    // $('#btn-search-item').attr('disabled', 'false');

    if (parseFloat($('#input-qty').val()) > parseFloat($('#input-qoh').val())) {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Enter quantity is greater than QOH",
            showConfirmButton: false,
            timer: 1500,
            didClose: (e) => {
                $('#input-qty').select()
                $('#input-qty').focus()
            },
        });
        return;
    }

    if ($('#header-additem').text() == "Add Item") {
        let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == $('#input-barcode').val().toLowerCase().trim())

        let item = {
            "inventoryid": inventory[0]['inventoryid'],
            "barcode": $('#input-barcode').val(),
            "name": $('#input-name').val(),
            "description": $('#input-desc').val(),
            "unit": "PCS",
            "batch": $('#input-batch').val(),
            "cost": $('#input-cost').val(),
            "qty": $('#input-qty').val(),
        }

        //console.log(item)
        itemarr.push(item);
        loaditemlist(itemarr);
    } else {
        let index = $('#label-index').text();

        $('#tbl-items tr:eq(' + index + ') td:eq(8)').html($('#input-qty').val());
    }

    $('#btn-confirm').attr('disabled', 'disabled');
    $('#btn-save').removeAttr("disabled");
    $('#modal-additem').modal('hide')
})

$('#textarea-notes').keypress(function() { 
  
    $('#btn-confirm').attr('disabled', 'disabled');
    $('#btn-save').removeAttr("disabled");
});

$('#btn-additem').click(function () {
   
    $('#label-index').text('');
    $('#input-qty').attr("placehodler", "0.00");
    $('#input-qty').val('');
    $("#btn-search-item").removeAttr('disabled');
    $('#modal-additem').modal('show');

});

$('#modal-additem').on('shown.bs.modal', function () {
    $('#input-barcode').val('');
    $('#input-name').val('');
    $('#input-desc').val('');
    $('#input-batch').val('');
    $('#input-qoh').val('0');
    $('#input-cost').val('0.00');
    $('#input-qty').attr("placehodler", "0.00");
    $('#input-qty').focus();
})

$('#btn-additem-close').click(function () {
    $('#modal-additem').modal('close')
});

$('#btn-create').click(function () {
    //console.log(ctl00_ContentPlaceHolder1_cmbBranches)
    //$("#(ctl00_ContentPlaceHolder1_cmbBranches option:selected" ).val()
    window.location.href = '/AddTransferStock.aspx?Branchname=' + getSelectedBranch();
});

$('#btn-search-item').click(function () {
    let inventories = inventorydetaildata;

    $('#input-search').val('')
    $("#selectedsearch").val("Category")

    loadSearchItem(inventories)
    $('#modal-search-item').modal('show')
});

$('#btn-searchitem-close').click(function () {
    $('#btn-search-close').modal('close')
});

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

$('#btn-cancel').click(function () {
    window.location.href = '/Stocktransfer.aspx'
})

$('#input-search').on("keyup", function () {
    var value = $(this).val().toLowerCase();
    var searchby = $('#selectedsearch').find(":selected").text().toLowerCase().trim();
    if (searchby.toLowerCase() == 'searchby') {
        return;
    }

    //let input = $('#input-search').val().toLowerCase().trim();
    //console.log(searchby)

    let searcheddata = inventorydetaildata.filter(function (obj) {
        for (key in obj) {
            if (obj[searchby].toLowerCase().trim().includes(value)) {
                return obj;
            }
        }
    });

    //console.log(searcheddata)
    loadSearchItem(searcheddata)
})

$("#selectedsearch").on("change", function () {
    $('#input-search').val('')
    let inventories = inventorydetaildata;
    loadSearchItem(inventories)
});

$('#search-clear').on('click', function () {
    let inventories = inventorydetaildata;
    loadSearchItem(inventories)
})

$('#btn-save').on('click', function () {
    if ($('#btn-branch').text().toLowerCase().trim() == "select branch") {
        Swal.fire({
            position: "center",
            icon: "info",
            text: "Please select branch",
            showConfirmButton: false,
            timer: 1500
        });
        return;
    }

    Swal.fire({
        //title: "Are you sure you want to stock in with zero cost?",
        text: "Are you sure you want to save details?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes"
    }).then((result) => {
        if (result.isConfirmed) {
            let tobranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#btn-branch').text().toLowerCase().trim());
            let frombranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#input-branchfrom').val().toLowerCase().trim())
            let transferid;
            if (transferdata.length > 0) {
                transferid = parseInt(transferdata.slice(-1)[0]['transferid']) + 1;
            } else {
                transferid = 1;
            }
            let frombranchid = frombranch[0]['branchid'];
            let tobranchid = tobranch[0]['branchid'];
            let transferno = $('#input-transfernumber').val();
            let transferdate = getDateTime();
            let senddatetime = '0001-01-01 00:00:00';
            let confirmno;
            let confirmdatetime = '0001-01-01 00:00:00';;
            let adjustdatetime = '0001-01-01 00:00:00';;
            let sinvoiceno;
            let subtotal = 0.00;
            let discount = 0.00;
            let gst = 0.00;
            let ttotal = 0.00;
            let tnotes = $('#textarea-notes').val();
            let employeename = $('#input-user').val();
            let sendflag = 0;
            let confirmflag = 0;
            let originalbranchid;
            let originaltransferno = $('#input-transfernumber').val();
            let db = frombranch[0]['name']

            let itemid = 0
            let detaillist = [];

            var table = $('#tbl-items').tableToJSON();

            //check if exist
            let ifExist = transferdata.filter((e) => e['transferno'].toLowerCase().trim() == transferno.toLowerCase().trim());

            if (ifExist.length == 0) {
                table.forEach(function (tbl) {
                    let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
                    itemid = parseInt(itemid) + 1
                    detail = {
                        "transferid": transferid,
                        "itemid": itemid,
                        "inventoryid": inventory[0]['inventoryid'],
                        "batchid": tbl['Batch #'],
                        "qty": tbl['Quantity'],
                        "cost": tbl['Cost'],
                        "rejectedqty": 0.00,
                        "reason": "",
                        "stockdate": getDateTime()
                    }
                    detaillist.push(detail);
                })


                let json_transferstock = {
                    "transferStockDetailedCosts": detaillist,
                    "transferid": transferid,
                    "frombranchid": frombranchid,
                    "tobranchid": tobranchid,
                    "transferno": transferno,
                    "transferdate": getDateTime(),
                    "senddatetime": senddatetime,
                    "confirmno": "N/A",
                    "confirmdatetime": confirmdatetime,
                    "adjustdatetime": adjustdatetime,
                    "sinvoiceno": "N/A",
                    "subtotal": 0,
                    "discount": 0,
                    "gst": 0,
                    "ttotal": 0,
                    "tnotes": tnotes,
                    "employeename": employeename,
                    "sendflag": 0,
                    "confirmflag": 0,
                    "originalbranchid": frombranchid,
                    "originaltransferno": transferno,
                }
                POST_TransferStock(frombranch[0]['name'], json_transferstock)
            } else {
                table.forEach(function (tbl) {
                    let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
                    itemid = parseInt(itemid) + 1
                    detail = {
                        "transferid": ifExist[0]['transferid'],
                        "itemid": itemid,
                        "inventoryid": inventory[0]['inventoryid'],
                        "batchid": tbl['Batch #'],
                        "qty": tbl['Quantity'],
                        "cost": tbl['Cost'],
                        "rejectedqty": 0.00,
                        "reason": "",
                        "stockdate": getDateTime()
                    }
                    detaillist.push(detail);
                })

                let data = {
                    "transferid": ifExist[0]['transferid'],
                    "senddatetime": senddatetime,
                    "confirmno": "",
                    "confirmdatetime": confirmdatetime,
                    "adjustdatetime": adjustdatetime,
                    "sinvoiceno": "",
                    "subtotal": 0,
                    "discount": 0,
                    "gst": 0,
                    "ttotal": 0,
                    "tnotes": tnotes,
                    "employeename": employeename,
                    "sendflag": sendflag,
                    "confirmflag": confirmflag,
                    "originalbranchid": 0,
                    "originaltransferno": $('#input-transfernumber').val(),
                    "dbname": frombranch[0]['name']
                }

                DELETE_TransferStockDetailedCost(frombranch[0]['name'], ifExist[0]['transferid'])

                PUT_TransferStockDetailedCost(data)

                detaillist.forEach(function (item) {
                    POST_TransferStockDetailedCost(frombranch[0]['name'], item)
                })
            }

            Swal.fire({
                position: "center",
                icon: "success",
                text: "Stock successfully save",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {
                const urlParams = new URL(window.location.href).searchParams;
                const transfernumber = urlParams.get('TransferNo');
                if (transfernumber == null) {                  
                    window.location.replace(window.location.href + "&TransferNo=" + transferno);
                }

                $('#btn-save').attr('disabled', 'disabled');
                $('#btn-confirm').removeAttr("disabled");
            });
        }
    });
})

$('#btn-confirm').on('click', function () {
    Swal.fire({
        //title: "Are you sure you want to stock in with zero cost?",
        text: "Are you sure you want to confirm details?",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes"
    }).then((result) => {
        if (result.isConfirmed) {
            let frombranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#input-branchfrom').val().toLowerCase().trim())
            let tobranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#btn-branch').text().toLowerCase().trim());
            let transferstock = transferdata.filter((e) => e['transferno'].toLowerCase().trim() == $('#input-transfernumber').val().toLowerCase().trim())
            let frombranchid = transferstock[0]['frombranchid'];
            let tobranchid = transferstock[0]['tobranchid'];
            let transferno = $('#input-transfernumber').val();
            let transderdata = getDateTime();
            let senddatetime = getDateTime();
            let confirmno = "";
            let confirmdatetime = getDateTime();
            let adjustdatetime = getDateTime();
            let sinvoiceno = "";
            let subtotal = 0.00;
            let discount = 0.00;
            let gst = 0.00;
            let ttotal = 0.00;
            let tnotes = $('#textarea-notes').val();
            let employeename = $('#input-user').val();
            let sendflag = 1;
            let confirmflag = 0;
            let originalbranchid = transferstock[0]['branchid'];
            let originaltransferno = $('#input-transfernumber').val();
            let db = frombranch[0]['name'];
            let data = {
                "transferid": transferstock[0]['transferid'],
                "senddatetime": senddatetime,
                "confirmno": "",
                "confirmdatetime": confirmdatetime,
                "adjustdatetime": adjustdatetime,
                "sinvoiceno": "",
                "subtotal": 0,
                "discount": 0,
                "gst": 0,
                "ttotal": 0,
                "tnotes": tnotes,
                "employeename": employeename,
                "sendflag": sendflag,
                "confirmflag": confirmflag,
                "originalbranchid": 0,
                "originaltransferno": $('#input-transfernumber').val(),
                "dbname": db
            }

            PUT_TransferStock(data);
            Swal.fire({
                position: "center",
                icon: "success",
                text: "Stock Transfer Confirmed",
                showConfirmButton: false,
                timer: 1500
            }).then((result) => {

                let tobranch = branches.filter((e) => e['fullname'].toLowerCase().trim() == $('#btn-branch').text().toLowerCase().trim());
                let receivedata = JSON.parse(get_ReceiveStockList(tobranch[0]['name']));

                let itemid = 0
                let receiveid = 0;
                if (receivedata.length > 0) {
                    receiveid = parseInt(receivedata.slice(-1)[0]['receiveid']) + 1;
                } else {
                    receiveid = 1;
                }

                detaillist = [];
                var table = $('#tbl-items').tableToJSON();
                table.forEach(function (tbl) {
                    let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
                    itemid = parseInt(itemid) + 1
                    detail = {
                        "receiveid": transferstock[0]['transferid'],
                        "itemid": itemid,
                        "inventoryid": inventory[0]['inventoryid'],
                        "batchid": tbl['Batch #'],
                        "qty": tbl['Quantity'],
                        "cost": tbl['Cost'],
                        "acceptedqty": 0.00,
                        "rejectedqty": 0.00,
                        "reason": "",
                        "stockdate": getDateTime()
                    }
                    detaillist.push(detail);
                })

                let json_receivestock = {
                    "receiveStockDetailedCosts": detaillist,
                    "receiveid": transferstock[0]['transferid'],
                    "frombranchid": frombranchid,
                    "tobranchid": tobranchid,
                    "transferno": transferno,
                    "transferid": transferstock[0]['transferid'],
                    "transferdate": getDateTime(),
                    "senddatetime": senddatetime,
                    "confirmno": "",
                    "confirmdatetime": "0001-01-10 00:00:00",
                    "replyflag": 0,
                    "erroroccur": 0,
                    "subtotal": 0,
                    "discount": 0,
                    "gst": 0,
                    "ttotal": 0,
                    "accepttotal": 0,
                    "employeename": employeename,
                    "confirmflag": 0,
                    "sinvoiceno": "",
                    "tnotes": ""
                }

           
                POST_ReceiveStock(tobranch[0]['name'],json_receivestock);
                window.location.replace(window.location.href + "&TransferNo=" + transferno);

            });
        }
    });
})

function ini_load(branch, fromdate, todate) {

    const urlParams = new URL(window.location.href).searchParams;
    const transfernumber = urlParams.get('TransferNo');
    const branchname = urlParams.get('Branchname');

    //branches = JSON.parse(sessionStorage.getItem('branchlist'))
    let selecteddb = branches.filter((e) => e['fullname'].toLowerCase().trim() == branch.toLowerCase().trim());
    //console.log(selecteddb[0]['name'])
    transferdata = JSON.parse(get_TransferStockList(selecteddb[0]['name']));
    transferdata = transferdata.filter((e) => e['transferdate'].substring(0, 10) >= fromdate && e['transferdate'].substring(0, 10) <= todate);

    loadTransferStock(transferdata)
    
}

function fillheaderdata(tranferno, branchfrom) {

}

function loaditemlist(itemarr) {
    const tblbody = document.getElementById('table-body-transfer-item')
    tblbody.innerHTML = "";
    $.each(itemarr, function (key, detail) {
        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(detail['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(detail['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(detail['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(detail['unit'].toString().trim())

        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['batch'].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'])
        //let inputquantity = document.createElement('input')
        //inputquantity.type = 'number'
        //inputquantity.style = "width:80px"
        //inputquantity.value = detail['qty'];

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

        let buttonedit = document.createElement('button');
        buttonedit.className = 'btn p-1';

        buttonedit.type = 'button'

        var iconedit = document.createElement('i');
        iconedit.className = 'bi bi-pencil-square';
        iconedit.innerHTML = ' Edit'
        iconedit.style = "font-style: normal;"


        let buttondelete = document.createElement('button');
        buttondelete.className = 'btn p-1';
        buttondelete.type = 'button'
        //buttondelete.innerText = 'Delete';


        var icondelete = document.createElement('i');
        icondelete.className = 'bi bi-trash';
        icondelete.style = "font-style: normal;"
        icondelete.innerText = ' Delete'




        //<i class="fa-solid fa-pen-to-square"></i>

        buttonedit.appendChild(iconedit);
        buttondelete.appendChild(icondelete);

        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);
        tdaction.appendChild(buttonedit);
        tdaction.appendChild(buttondelete)

        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(tdaction);


        tblbody.appendChild(tr);



    });
}

function dp_branch(branchlist) {

    branchlist = branchlist.filter((e) => e['fullname'].toLowerCase().trim() != $('#input-branchfrom').val().toLowerCase().trim())
    var li = document.createElement('li')
    li.id = "u-branches"
    document.getElementById('ul-branches').appendChild(li)
    for (const item of branchlist) {
        //console.log()
        var a = document.createElement('a')
        a.className = 'dropdown-item text-capitalize'
        a.innerHTML = item['fullname']
        document.getElementById(li.id).appendChild(a)
    }
}

function loadbranches(branchlist) {
    
    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: "AddTransferStock.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;
}

function get_InventoryDetail(db) {
    //console.log(db)
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/InventoryWithCostDetail",
        //url: "AddTransferStock.aspx/ICAD",
        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 loadSearchItem(inventories) {
    const tblbody = document.getElementById('table_body_items')
    tblbody.innerHTML = "";
    $.each(inventories, function (key, detail) {

        if (detail['qoh'] <= 0) {
            return;
        }
        let tr = document.createElement("tr");

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

        let divchkitem = document.createElement("div");
        divchkitem.className = "checkbox text-center";

        let labelchkitem = document.createElement("label")
        labelchkitem.className = "form-checkbox form-icon";
        labelchkitem.setAttribute("for", "s_fac")

        let inputchkitem = document.createElement("input")
        inputchkitem.id = "s_fac";
        inputchkitem.className = "sev_check";
        inputchkitem.type = "checkbox"

        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(detail['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(detail['name']);

        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(detail['description']);

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

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

        tdchkitem.appendChild(divchkitem);
        divchkitem.appendChild(labelchkitem);
        labelchkitem.appendChild(inputchkitem);

        tdbarcode.appendChild(barcode);
        tdname.appendChild(name)
        tddesc.appendChild(desc);
        tdcategory.appendChild(category);
        tdqoh.appendChild(qoh);

        tr.appendChild(tdchkitem);
        tr.appendChild(tdbarcode);
        tr.appendChild(tdname);
        tr.appendChild(tddesc);
        tr.appendChild(tdcategory);
        tr.appendChild(tdqoh);

        tblbody.appendChild(tr);

    })

}

function loadTransferStock(transferstockdata) {
 
    const tblbody = document.getElementById('table-body-transferstock')
    if (tblbody == null) {
        return
    }
    tblbody.innerHTML = "";
    $.each(transferstockdata, 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 = 'Send'
        }


        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'].replace("T", " ").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.toString().trim());

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

        //let action = document.createTextNode(sendstatus.toString().trim());
        //action.id = 'btn-' + detail['transferno'].toString().trim();
        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 = 'View Detail'
        document.getElementById(action.id).appendChild(viewdetail);
    });

}

function loadExistingTransfer(data, frombranchname) {

    //console.log(data[0]['transferStockDetailedCosts'])
    //let branch = 
    //let branches = JSON.parse(sessionStorage.getItem('branchlist'));
    let branchname = branches.filter((e) => e['branchid'] == data[0]['tobranchid'])

    $('#input-transfernumber').val(data[0]['transferno']);
    $('#input-date').val(getDateTime(data[0]['transferdate']).substr(0, 10));
    $('#input-branchfrom').val(frombranchname);

    $('#textarea-notes').val(data[0]['tnotes'])
    $('#input-senddate').val(data[0]['senddatetime'].replace("T", " "));
  
    $('#input-receive').val(data[0]['confirmno']);

   

    if(data[0]['confirmflag'] == 1){
        $('#input-receive-status').val('Confirmed');
    }
    
    if (data[0]['senddatetime'].replace("T", " ") == "0001-01-01 00:00:00") {
        $('#input-senddate').val('N/A');
    }

    let status = 'Pending';

    if(data[0]['sendflag']== 1){
        status = 'Sent'
    }
        
    $('#input-send-status').val(status);
    //$('#btn-branch').text('Bishan')
    document.getElementById('btn-branch').innerText = branchname[0]['fullname']

    let itemdata = data[0]['transferStockDetailedCosts']
    itemdata.forEach(function (item) {
        let inventory = inventorydetaildata.filter((e) => e['inventoryid'] == item['inventoryid'])
        let x = {
            "inventoryid": item['inventoryid'],
            "barcode": inventory[0]['barcode'],
            "name": inventory[0]['name'],
            "description": inventory[0]['description'],
            "unit": "PCS",
            "batch": item['batchid'],
            "cost": item['cost'].toFixed(2),
            "qty": item['qty'].toFixed(2),
        }
        itemarr.push(x);
    })

    loaditemlist(itemarr)

    if (data[0]['sendflag'] == 1) {
        status = 'Sent'
        $('#btn-save').attr('disabled', 'disabled');
        $('#btn-confirm').attr('disabled', 'disabled');
        $('#btn-branch').attr('disabled', 'disabled');
        $('#btn-additem').attr('disabled', 'disabled');
        $('#btn-void').attr('disabled', 'disabled');
        $("#tbl-items :button").prop("disabled", true);

    }

    //$('#input-branchfrom').val(currentbranch)
}
//function get_Inventories() {
//    var returnvalue;
//    $.ajax({
//        type: "POST",
//        url: "AddTransferStock.aspx/GET_InventoryList",
//        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_InventoriesCostAverageDetail() {
//    var returnvalue;
//    $.ajax({
//        type: "POST",
//        url: "AddTransferStock.aspx/GET_InventoryCostAverageDetail",
//        async: false,
//        contentType: 'application/json;charset=utf8',
//        dataType: 'json',
//        error: function (XMLHttpRequest, textStatus, errorThrown) {
//            console.log("error get_InventoriesCostAverageDetail()")
//        }, success: function (result) {
//            returnvalue = result.d;
//        }
//    });
//    return returnvalue;
//}

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

//save(new)
function POST_TransferStock(db, json) {
    var returnvalue;

    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/POST_TransferStock",
        data: "{'db':'" + db + "', 'jsondata':'" + JSON.stringify(json) + "'}",
        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;
}

//confirm
function PUT_TransferStock(json) {

    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/PUT_TransferStock",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        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;
}

//edit TransderDetail
function PUT_TransferStockDetailedCost(json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/PUT_TransferStockDetailedCost",
        data: "{'jsondata':'" + JSON.stringify(json) + "'}",
        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;
}

//save(transferdetailedcost)
function POST_TransferStockDetailedCost(db, json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/POST_TransferStockDetailedCost",
        data: "{'db':'" + db + "','jsondata':'" + JSON.stringify(json) + "'}",
        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;
}

//delete TransferStockDetailCost
function DELETE_TransferStockDetailedCost(db, transferid) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/DELETE_TransferStockDetailedCost",
        data: "{'db':'" + db + "','transferid':" + transferid + "}",
        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;
}

//post receivestock
function POST_ReceiveStock(db, json) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.aspx/POST_ReceiveStock",
        data: "{'db':'" + db + "','jsondata':'" + JSON.stringify(json) + "'}",
        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;
}

//get receivestocklist
function get_ReceiveStockList(db) {
    var RetValue;
    $.ajax({
        type: "POST",
        url: "AddTransferStock.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_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;
}

//convert table data to json
function selectedtransferitem(inventoryid) {
    let selecteditem = []
    //console.log(inventoryid)
    var table = $('#tbl-items').tableToJSON();
    table.forEach(function (tbl) {

        //let inventory = inventorydetaildata.filter((e) => e['barcode'].toLowerCase().trim() == tbl['Barcode'].toLowerCase().trim())
        //itemid = parseInt(itemid) + 1
        //detail = {
        //    "transferid": ifExist[0]['transferid'],
        //    "itemid": itemid,
        //    "inventoryid": inventory[0]['inventoryid'],
        //    "batchid": tbl['Batch #'],
        //    "qty": tbl['Quantity'],
        //    "cost": tbl['Cost'],
        //    "stockdate": getDateTime()
        //}
        if (tbl['ID'] == inventoryid) {
            selecteditem.push(tbl);
        }
    })

    return selecteditem;
}

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;

}


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;
}
