let url = readWebConfig();
$(document).ready(function () {
    //console.log( getBatchID());
    init();
});

function init() {
    $(window).keydown(function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });



    //let db = JSON.parse(sessionStorage.getItem('data'));    
    //if (db == null) {
    //    generateInventoryWithQOH();
    //    generateStockAdjustUnit();
    //} else {    
    //    if (db['setting']['branch'] != loadDB()) {
    //        sessionStorage.clear();
    //        generateInventoryWithQOH();
    //        generateStockAdjustUnit();
    //    }
    //}

    sessionStorage.clear();
    generateInventoryWithQOH();
    generateStockAdjustUnit();
    //loadtblInventory();
    loadCatgories();

    const dateControl = document.querySelector('input[type="date"]');
    dateControl.value = new Date().toJSON().slice(0, 10);

    //trigger load
    $("#btnUnit").prop("disabled", true);

    $(document).on('click', 'button', function () {
        //stock adjust button(stock in)
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'stock adjust') {
            $('#inputnumberofqty').val('0')
            $('#inputqty').val('0')
            $('#inputcost').val('0.00')

            document.getElementById('btnalarm').innerHTML = 'No';
            loadDropDownGoupUnit(getStockAdjustGroupUnit())
            document.getElementById('staticBackdropLabel').innerHTML = $(this)[0].innerHTML;

            var $row = $(this).closest("tr");    // Find the row
            var tdbarcode = $row.find("td");

            let barcode = tdbarcode[0].innerHTML.trim();
            //let items = JSON.parse(sessionStorage.getItem('inventory'));
            let items = JSON.parse(sessionStorage.getItem('data'))['item'];

            let item = items.filter((e) => e['barcode'].trim().toLowerCase() == barcode.toLowerCase());

            $('#inputbarcode').val(item[0]['barcode']);
            $('#inputname').val(item[0]['name']);
            $('#inputdesc').val(item[0]['description']);
            $('#inputbatchid').val(getBatchID());

            generateInventoryCostAverageDetailRow(item[0]['inventoryid'])

            $('#modalInventoryAdjust').modal('show');
        }

        //view stock detail
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'view detail') {

            var $row = $(this).closest("tr");    // Find the row
            var tdbarcode = $row.find("td");

            let barcode = tdbarcode[0].innerHTML.trim();
            let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];

            //let items = JSON.parse(sessionStorage.getItem('inventory'));
            let qoh = tdbarcode[4].innerHTML.trim();
            let item = inventories.filter((e) => e['barcode'].trim().toLowerCase() == barcode.toLowerCase());
            //let inventories = JSON.parse(sessionStorage.getItem('inventory'));         
            let inventory = inventories.filter((e) => e['inventoryid'] == item[0]['inventoryid']);

            //tblBodyStockDetail.remove()
            if (parseFloat(qoh) == 0) {
                Swal.fire({
                    icon: "info",
                    text: "No stock activities for this item",
                }).then(function () {
                    $('#inputcost').focus();

                });
                return;
            }
            const sorterbyBatch = (a, b) => a['batchid'] > b['batchid'] ? 1 : -1;
            inventory[0]['icadetail'].sort(sorterbyBatch);


            $('#inputdetailbarcode').val(inventory[0]['barcode']);
            $('#inputdetailname').val(inventory[0]['name']);
            $('#inputdetaildesc').val(inventory[0]['description']);
            $('#inputqoh').val(parseFloat(qoh).toFixed(2));
            inventoryDetailedView(inventory[0]['icadetail']);


            $('#modalviewdetail').modal('show');
        };

        //confirm(stock in) button
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'confirm stock in') {
            let action = document.getElementById('staticBackdropLabel').innerHTML.toLowerCase();

            if ($('#inputnumberofqty').val() == '') {
                $('#inputqty').attr('readonly', false);
                $('#inputnumberofqty').val('1');
                let unitname = document.getElementById('btnUnit').innerText.trim();
                let units = JSON.parse(sessionStorage.getItem('arrUnit'));
                let unit = units.filter((e) => e['stockunitname'] == unitname.toLowerCase().trim());
                let totalqty = parseFloat($(this).val()) * parseFloat(unit[0]['totalqty']);
                $('#inputqty').val(totalqty);
                $('#inputqty').attr('readonly', true);
            }

            if ($('#inputqty').val() == '' || $('#inputqty').val() == '0' || $('#inputqty').val() == '0.00') {
                Swal.fire({
                    icon: "error",
                    text: "Invalid value for Quanity",
                }).then(function () {
                    $("#inputqty").trigger("focus");
                });
                return;
            }

            if ($('#inputcost').val() == '') {
                Swal.fire({
                    icon: "error",
                    text: "Invalid value for Cost",
                }).then(function () {
                    $('#inputcost').focus();

                });
                return;
            }

            var postdata;
            var inventoryadjust;


            //let items = JSON.parse(sessionStorage.getItem('arrData'));
            //let items = JSON.parse(sessionStorage.getItem('inventory'));
            let items = JSON.parse(sessionStorage.getItem('data'))['item'];
            let item = items.filter((e) => e['barcode'].trim().toLowerCase() == $('#inputbarcode').val().trim().toLowerCase());

            let id = item[0]['inventoryid'];
            let qty = parseFloat($('#inputqty').val());
            let cost = parseFloat($('#inputcost').val());
            let batchid = $('#inputbatchid').val()
            let expdate = $('#date').val()
            let date = getDateTime();
            let notes = 'Adj In';
            let alarm = 0;
            let isbatchexist = item[0]['icadetail'].filter((e) => e['batchid'].trim() == batchid.trim());

            if (document.getElementById('btnalarm').innerHTML.toLowerCase().trim() == 'yes') {
                alarm = 1;
            }

            if (isbatchexist.toString()) {
                Swal.fire({
                    text: "Something went wrong. Please stock in again",
                    icon: "warning",
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                }).then((result) => {
                    $('#modalInventoryAdjust').modal('hide');
                });
                return;
            }

            postdata = {
                "inventoryid": id,
                "batchid": batchid,
                "inqty": qty,
                "outqty": 0,
                "unitcost": cost,
                "stockdate": date,
                "notes": notes,
                "expirydate": expdate,
                "expiryalarm": alarm
            }

            inventoryadjust = {
                "inventoryid": id,
                "adjustquantity": qty,
                "unitcost": cost,
                "notes": notes,
                "dateadjusted": date,
                "employeeid": 0,
                "userid": alarm
            }

            if (parseFloat($('#inputcost').val()) <= 0) {
                Swal.fire({
                    //title: "Are you sure you want to stock in with zero cost?",
                    text: "Are you sure you want to " + action + " with zero cost?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#3085d6",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "Yes"
                }).then((result) => {
                    if (result.isConfirmed) {
                        postInventoryCostAverageDetail(postdata);
                        postInventoryAdjust(inventoryadjust);

                        Swal.fire({
                            position: "center",
                            icon: "success",
                            text: "Stock successfully adjust",
                            showConfirmButton: false,
                            timer: 1500
                        }).then((result) => {
                            generateInventoryWithQOH();
                            //loadtblInventory();
                            generateInventoryCostAverageDetailRow(id);
                            //$('#modalInventoryAdjust').modal('hide');
                        });
                    }
                });
                return;
            }

            Swal.fire({
                //title: "Are you sure you want to stock in with zero cost?",
                text: "Are you sure you want to confirm stock in?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes"
            }).then((result) => {
                if (result.isConfirmed) {
                    postInventoryCostAverageDetail(postdata);
                    postInventoryAdjust(inventoryadjust);
                    Swal.fire({
                        position: "center",
                        icon: "success",
                        text: "Stock successfully adjust",
                        showConfirmButton: false,
                        timer: 1500
                    }).then((result) => {
                        generateInventoryWithQOH();
                        //loadtblInventory();
                        //$('#modalInventoryAdjust').modal('hide');
                        generateInventoryCostAverageDetailRow(id);
                    });
                }
                return;
            });
        }

        //stock out button
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'stock out') {
            var $row = $(this).closest("tr");    // Find the row
            var tdbatchid = $row.find("td");

            let batchid = tdbatchid[0].innerHTML.trim();
            //let inventories = JSON.parse(sessionStorage.getItem('inventory'));
            let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
            let inventory = inventories.filter((e) => e['barcode'].toString().toLowerCase().trim() == $('#inputbarcode').val().toLowerCase().trim())
            let item = inventory[0]['icadetail'].filter((e) => e['batchid'].trim().toLowerCase() == batchid.toLowerCase());
            let alarmvalue = tdbatchid[7].innerHTML.trim();

            $('#inputsobarcode').val($('#inputbarcode').val());
            $('#inputsoname').val($('#inputname').val());
            $('#inputsodesc').val($('#inputdesc').val());
            $('#inputsobatchid').val(batchid);
            $('#inputalarm').val(alarmvalue);
            $('#inputsounitcost').val(item[0]['unitcost']);
            $('#modalstockout').modal('show');
            $('#modalInventoryAdjust').modal('hide');
        }

        if ($(this)[0].innerHTML.toLowerCase().trim() == 'confirm stock out') {

            //let items = JSON.parse(sessionStorage.getItem('arrData'));
            //let items = JSON.parse(sessionStorage.getItem('inventory'));
            let items = JSON.parse(sessionStorage.getItem('data'))['item'];
            let item = items.filter((e) => e['barcode'].trim().toLowerCase() == $('#inputsobarcode').val().trim().toLowerCase());

            let id = item[0]['inventoryid']
            let qty = parseFloat($('#inputsoqty').val());
            let cost = parseFloat($('#inputsounitcost').val());
            let batchid = $('#inputsobatchid').val()
            let expdate = $('#date').val()
            let date = getDateTime();
            let notes = 'Adj Out';
            let alarm = $('#inputalarm').val()

            if (alarm == 'no') {
                alarm = 0;
            } else {
                alarm = 1;
            }

            Swal.fire({
                //title: "Are you sure you want to stock in with zero cost?",
                text: "Are you sure you want to confirm stock out?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes"
            }).then((result) => {
                if (result.isConfirmed) {
                    postdata = {
                        "inventoryid": id,
                        "batchid": batchid,
                        "inqty": 0,
                        "outqty": qty,
                        "unitcost": cost,
                        "stockdate": date,
                        "notes": notes,
                        "expirydate": expdate,
                        "expiryalarm": alarm
                    }

                    inventoryadjust = {
                        "inventoryid": id,
                        "adjustquantity": -Math.abs(qty),
                        "unitcost": cost,
                        "notes": notes,
                        "dateadjusted": date,
                        "employeeid": alarm,
                        "userid": 0
                    }


                    postInventoryCostAverageDetail(postdata);
                    postInventoryAdjust(inventoryadjust);

                    Swal.fire({
                        position: "center",
                        icon: "success",
                        text: "Stock successfully adjust",
                        showConfirmButton: false,
                        timer: 1500
                    }).then((result) => {
                        generateInventoryWithQOH();
                        generateInventoryCostAverageDetailRow(id);
                        $('#modalstockout').modal('hide');
                        $('#modalInventoryAdjust').modal('show');
                    });
                }
                return;
            });
        }

        //close button
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'cancel') {
            $('#modalstockout').modal('hide');
            $('#modalInventoryAdjust').modal('show');
        }

        //close button
        if ($(this)[0].innerHTML.toLowerCase().trim() == 'close') {
            //generateInventoryWithQOH();
            loadtblInventory();
            let categoryname = $('#selectedsearch').find(":selected").text().toLowerCase().trim();
            let input = $('#inputsearch').val().toLowerCase().trim();
            if (categoryname != '' || input != '') {
                $('#inputsearch').keyup();
            }
        }
    });

    $("#inputnumberofqty").on("keyup", function () {
        $('#inputqty').attr('readonly', false);
        if ($(this).val() == '') {
            return;
        }

        let unitname = document.getElementById('btnUnit').innerText.trim();
        //let groupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'))
        let groupunit = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit']
        let unit = groupunit.filter((e) => e['groupunitname'].toLowerCase().trim() == document.getElementById('btnGroupUnit').innerText.toLowerCase().trim());

        let selectedunit = unit[0]['units'].filter((e) => e['unitname'].toLowerCase().trim() == document.getElementById('btnUnit').innerText.toLowerCase().trim());
        let totalqty = parseFloat($(this).val()) * parseFloat(selectedunit[0]['totalqty']);

        $('#inputqty').val(totalqty);
        $('#inputqty').attr('readonly', true);
    });

    $("input").on("focusout", function () {

        if ($('#inputnumberofqty').val() == '') {
            $('#inputqty').attr('readonly', false);
            $('#inputnumberofqty').val('1');
            let unitname = document.getElementById('btnUnit').innerText.trim();
            let units = JSON.parse(sessionStorage.getItem('arrUnit'));
            let unit = units.filter((e) => e['stockunitname'] == unitname.toLowerCase().trim());
            let totalqty = parseFloat($(this).val()) * parseFloat(unit[0]['totalqty']);
            $('#inputqty').val(totalqty);
            $('#inputqty').attr('readonly', true);
        }

        //if ($('#inputqty').val() == '') {            
        //    $('#inputqty').val('1');                      
        //}

        //if ($('#inputcost').val() == '') {
        //    $('#inputcost').val('0.00');
        //}
    });

    $(".numbersonly").keypress(function (e) {
        if (e.which < 48 || 57 < e.which)
            e.preventDefault();
    });

    $("#inputsearch").on("keyup", function () {
        var value = $(this).val().toLowerCase();

        //if ($(this).val() != '') {
        //    $("#tblbody tr").filter(function () {               
        //        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        //    });
        //}

        //let data = JSON.parse(sessionStorage.getItem('inventory'));
        let data = JSON.parse(sessionStorage.getItem('data'))['item'];
        let currentpage = sessionStorage.getItem('currentpage')

        if (currentpage == null || currentpage == 'undefined') {
            currentpage = 1;
        }

        let filterdatabycategory;
        let filterdatabynamedesc;
        let category = $('#input-datalist-category').val().toLowerCase().trim();
        let input = $('#inputsearch').val().toLowerCase().trim();

        //let input = $('#inputsearch').val().toLowerCase().trim();
        var searchby = $('#selectedsearch').find(":selected").text().toLowerCase().trim();

        if (category != '') {
            filterdatabycategory = data.filter(function (obj) {
                for (key in obj) {
                    if (obj['category'].toLowerCase().trim().includes(category)) {
                        return obj;
                    }
                }
            });

            filterdatabynamedesc = filterdatabycategory.filter(function (obj) {
                for (key in obj) {
                    if (obj[searchby].toLowerCase().trim().includes(input)) {
                        //if (obj['description'].includes(input)) {
                        return obj;
                    }
                }
            });
            paginateInventory(filterdatabynamedesc, currentpage);

        } else {
            filterdatabynamedesc = data.filter(function (obj) {
                for (key in obj) {
                    if (obj[searchby].toLowerCase().trim().includes(input)) {
                        //if (obj['description'].includes(input)) {
                        return obj;
                    }
                }
            });

            if (value == '') {
                filterdatabynamedesc = []
            }

            paginateInventory(filterdatabynamedesc, currentpage);


        }
    });

    //dropdown
    $(document).on('click', '#ddGroupUnit li', function () {
        document.getElementById('btnGroupUnit').innerText = $(this)[0].innerText;

        //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
        let stockgroupunit = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit'];
        let groupunit = stockgroupunit.filter((e) => e['groupunitname'].trim().toLowerCase() == $(this)[0].innerText.trim().toLowerCase());
        let unit = groupunit[0]['units'];

        if (groupunit[0]['groupunitid'] == '1') {
            $('#inputnumberofqty').attr('readonly', true);
            $('#inputnumberofqty').val('0');
            $('#inputqty').attr('readonly', false);
            $('#inputqty').val('1');
            $("#btnUnit").prop("disabled", true);
        } else {
            $('#inputnumberofqty').val('1');
            $('#inputnumberofqty').attr('readonly', false);
            $('#inputqty').attr('readonly', true);
            $('#inputqty').val(unit[0]['totalqty']);
            $("#btnUnit").prop("disabled", false);
        }

        if ($(this)[0].innerText.toLowerCase() != 'loose') {
            let labelElement = document.getElementById("lblNo");
            labelElement.innerHTML = 'No. of ' + $(this)[0].innerText.trim()
            //$('#lblNo').value = 'sample'
        } else {
            let labelElement = document.getElementById("lblNo");
            labelElement.innerHTML = 'No.'
        }

        loadDropDownUnit(JSON.stringify(unit))

    });

    $(document).on('click', '#ddUnit li', function () {
        document.getElementById('btnUnit').innerText = $(this)[0].innerText

        /*let units = JSON.parse(sessionStorage.getItem('arrUnit'));
        let unit = units.filter((e) => e['stockunitname'].trim().toLowerCase() == $(this)[0].innerText.trim().toLowerCase());*/
        //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
        let stockgroupunit = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit'];
        let groupunit = stockgroupunit.filter((e) => e['groupunitname'].trim().toLowerCase() == document.getElementById('btnGroupUnit').innerText.toLowerCase().trim());
        let unit = groupunit[0]['units'].filter((e) => e['unitname'].trim().toLowerCase() == document.getElementById('btnUnit').innerText.toLowerCase().trim());;

        $('#inputqty').val(unit[0]['totalqty']);
    });

    $(document).on('click', '#ddalarm li', function () {
        document.getElementById('btnalarm').innerText = $(this)[0].innerText;
    });

    $(document).on('click', '#ddcategory li', function () {
        document.getElementById('btncategory').innerHTML = $(this)[0].innerText;
        let categories = JSON.parse(sessionStorage.getItem('categories'));
        let category = categories.filter((e) => e['CategoryName'].toLowerCase() != 'round' && e['Active'] != 0);
        //console.log(category)
        //category.forEach(function (item) {
        //    // Create a new <option> element.
        //    var option = document.createElement('option');
        //    // Set the value using the item in the JSON array.
        //    option.value = item['CategoryName'];
        //    // Add the <option> element to the <datalist>.
        //    dataList.appendChild(option);
        //});

    });

    document.addEventListener('DOMContentLoaded', e => {
        $('#input-datalist-category').autocomplete()
    }, false);

    $("#input-datalist-category").on("keyup", function () {

        var value = $(this).val().toLowerCase();
        //console.log(value)
        //var input, filter, table, tr, td, i;

        //filter = $(this).val().toLowerCase();
        //table = document.getElementById("tblbody");
        //tr = table.getElementsByTagName("tr");
        //$('#tblbody tr').filter(function () {
        //    $(this).toggle($(this).find("td:eq(3)").text().toLowerCase().indexOf(filter) > -1)
        //});       

        //let data = JSON.parse(sessionStorage.getItem('inventory'));
        let data = JSON.parse(sessionStorage.getItem('data'))['item'];

        let currentpage = sessionStorage.getItem('currentpage')

        if (currentpage == null || currentpage == 'undefined') {
            currentpage = 1;
        }

        let filterdatabycategory;
        let filterdatabynamedesc;
        let category = $('#input-datalist-category').val().toLowerCase().trim();
        let input = $('#inputsearch').val().toLowerCase().trim();

        filterdatabycategory = data.filter(function (obj) {
            for (key in obj) {
                if (obj['category'].toLowerCase().trim().includes(category)) {
                    return obj;
                }
            }
        });
        //filterdatabycategory = data.filter((e) => e['category'].toLowerCase().trim() == category.toLowerCase().trim())
        // console.log(filterdatabycategory)
        if (value == '') {
            filterdatabycategory = []
        }
        paginateInventory(filterdatabycategory, currentpage);
    });

    $('#chkshownegative').click(function () {
        let inventoryid = $('#inputdetailbarcode').val();
        let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
        let item = inventories.filter((e) => e['barcode'].trim().toLowerCase() == inventoryid.toLowerCase().trim());
        let inventory = inventories.filter((e) => e['inventoryid'] == item[0]['inventoryid']);
        inventoryDetailedView(inventory[0]['icadetail'])
    });

    $(document).on('click', 'button', function () { });

    //category
    const inputcat = document.querySelector('input[type="search"]');
    inputcat.addEventListener("search", () => {
        paginateInventory([], 1);

    });

    //barcode,name,desc
    const inputbarcpde = document.querySelector('#inputsearch');
    inputbarcpde.addEventListener("search", () => {
        paginateInventory([], 1);

    });
}

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;

}

// main table inventory
function loadtblInventory() {
    //let data = JSON.parse(sessionStorage.getItem('inventory'));
    let data = JSON.parse(sessionStorage.getItem('data'))['item'];
    let currentpage = sessionStorage.getItem('currentpage')

    if (currentpage == null || currentpage == 'undefined') {
        currentpage = 1;
    }

    //paginateInventory(data, currentpage);
    if ($('#input-datalist-category').val().trim() != '') {
        let filterdata;
        let category = $('#input-datalist-category').val().toLowerCase().trim();
        filterdata = data.filter(function (obj) {
            for (key in obj) {
                if (obj['category'].toLowerCase().trim().includes(category)) {
                    return obj;
                }
            }
        });
        paginateInventory(filterdata, currentpage);
    } else {

        paginateInventory(data, currentpage);
    }
}

function paginateInventory(data, pageno) {
    //let arrInventoryCostAverage = JSON.parse(sessionStorage.getItem('arrInventoryCostAverage'));
    //let arrcategory = JSON.parse(sessionStorage.getItem('category'))
    const tblBody = document.getElementById('tblbody')
    $(".paginationjs").remove();
    $("#inventory-list").pagination({
        dataSource: data,
        pageSize: 50,
        pageNumber: pageno,
        afterRender: function () {
            document.getElementById('tblbody').innerHTML = '';
            //$(".paginationjs")

            if ($("#inventory-list div.paginationjs").length == 1) {
                $("#inventory-list div.paginationjs").insertBefore("#inventory-list")
            }
        },
        callback: function (data, pagination) {
            sessionStorage.setItem('currentpage', pagination['pageNumber']);
            //document.getElementById('divInventoryCostAverage').innerHTML = '';
            $("#inventory-list").empty();
            $.each(data, function (key, item) {
                //let itemInventoryCostAverage = arrInventoryCostAverage.filter((e) => e['InventoryID'] == item['InventoryID']);             
                //let itemCategory = arrcategory.filter((e) => e['CategoryID'] == item['CategoryID']);

                const tr = document.createElement("tr");

                const tdbarcode = document.createElement("td");
                tdbarcode.className = 'col-2 border-start border-end p-1 align-content-center'
                const barcode = document.createTextNode(item['barcode'].trim());

                var tdname = document.createElement('td')
                tdname.className = 'col-2 border-end p-1 align-content-center'
                var name = document.createElement('text')
                name.innerHTML = item['name'].trim();

                var tddesc = document.createElement('td')
                tddesc.className = 'col-2 border-end p-1 align-content-center'
                var desc = document.createElement('text')
                desc.innerHTML = item['description'].trim();

                var tdcategory = document.createElement('td')
                tdcategory.className = 'col-2 border-end p-1 align-content-center text-start'
                var category = document.createElement('text')
                //category.innerHTML = itemCategory[0]['CategoryName'].trim();
                category.innerHTML = item['category'].trim();

                var tdqoh = document.createElement('td')
                tdqoh.className = 'col-1 border-end p-1 align-content-center  text-end'
                var qoh = document.createTextNode(item['qoh'].toFixed(2));
                //var qoh = document.createElement('text')
                //qoh.innerHTML = (parseFloat(itemInventoryCostAverage[0]['PQuantity']) - parseFloat(itemInventoryCostAverage[0]['RetailQTY'])).toFixed(2)
                //qoh.innerHTML = item['qoh'];


                var tdaction = document.createElement('td')
                tdaction.className = 'col-3 border-end text-end p-1 text-center'
                var action = document.createElement('div')
                action.id = Math.random().toString(16).substring(2, 16);

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

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

                tblBody.appendChild(tr);

                var viewdetail = document.createElement('button')
                viewdetail.type = 'button'
                viewdetail.id = 'vd' + item['barcode'].toLowerCase().trim()
                viewdetail.className = 'btn btn-outline-primary btn-xs m-1'
                viewdetail.innerText = 'View Detail'
                //divButton.setAttribute("onclick", "UpdateWebKDSDetailWebKDSServerItemStatus('" + DB + "', '" + TransID + "', '" + ItemID + "', '" + Barcode + "','" + docketPos + "')");
                document.getElementById(action.id).appendChild(viewdetail);

                var stockin = document.createElement('button')
                stockin.type = 'button'
                stockin.id = 'si' + item['barcode'].toLowerCase().trim()
                stockin.className = 'btn btn-outline-success btn-xs m-1'
                stockin.innerText = 'Stock Adjust'

                document.getElementById(action.id).appendChild(stockin);
                //var stockout = document.createElement('button')
                //stockout.type = 'button'
                //stockout.id = 'so' + item['Barcode'].toLowerCase().trim()
                //stockout.className = 'btn btn-outline-danger btn-xs m-1'
                //stockout.innerText = 'Stock Out'
                //document.getElementById(action.id).appendChild(stockout);
            });
        },
    });

}

$('#modal-addgroup').on('shown.bs.modal', function () {
    $('#input-groupname').focus();
})

$("#btn-viewgroup").click(function () {
    $('#input-groupid').val('')
    $('#input-groupname').val('');
  
    loadGroupTbody()    
    $('#modal-addgroup').modal('show')
});

function loadGroupTbody() {
    let group = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit']
    
    dp_groups(group)
    const tblBody = document.getElementById('tblbody-groupunit')
    tblBody.innerHTML = ""
    $.each(group, function (key, detail) {

        const tr = document.createElement("tr");
        tr.style = "height:1vh";

        const tdid = document.createElement("td")
        tdid.className = 'col-1 border-start border-end border-bottom  text-center px-1 align-content-center';      
        const id = document.createTextNode(detail['groupunitid'].toString().trim());

        const tdgroupname = document.createElement("td");
        tdgroupname.className = 'col-1 border-start border-end border-bottom  text-center px-1 align-content-center'
        const groupname = document.createTextNode(detail['groupunitname'].toString().trim());

        const tdaction = document.createElement("td");
        tdaction.className = 'col-2 border-start border-end border-bottom  text-right px-1 align-content-center'
        //tdaction.colSpan = 2;

        const btnedit = document.createElement("button")
        btnedit.id = "btn-edit-group";
        btnedit.type = "button";
        btnedit.className = "btn"

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


        const btnview = document.createElement("button")
        btnview.id = "btn-viewunit";
        btnview.type = "button";
        btnview.className = "btn "

        var iconview = document.createElement('i');
        iconview.className = 'bi bi-plus-square text-center';
        iconview.innerHTML = ' View'
        iconview.style = "font-style: normal;"

        btnedit.appendChild(iconedit);
        btnview.appendChild(iconview);

        tdid.appendChild(id);
        tdgroupname.appendChild(groupname);
        tdaction.append(btnedit);
        tdaction.appendChild(btnview)

        tr.appendChild(tdid);
        tr.appendChild(tdgroupname);
        tr.appendChild(tdaction);
        tblBody.appendChild(tr);

    })

}

$(document).on('click', '#btn-edit-group', function () {
    var $row = $(this).closest("tr");    // Find the row
    var tdgroup = $row.find("td");
    var groupid = tdgroup[0].innerHTML;
    var groupname = tdgroup[1].innerHTML;

    $('#input-groupid').val(groupid);
    $('#input-groupname').val(groupname);

})

$("#btn-save-group").click(function () {
    let group = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit']
    let groupid = $('#input-groupid').val();    
    let is_exist = group.filter((e) => e['groupunitname'].toLowerCase().trim() == $('#input-groupname').val().toLowerCase().trim());
    
    if ($('#input-groupname').val() == '') {
        Swal.fire({
            icon: "error",
            text: "Please enter group name",
        }).then(function () {
            $("#input-groupname").trigger("focus");
        });
        return;
    }

    if (is_exist.length > 0) {
        Swal.fire({
            icon: "error",
            text: "Group name already exist",
        }).then(function () {
            $("#input-groupname").trigger("focus");
        });
        return;
    }

    if ($('#input-groupid').val() == '') {
        Swal.fire({
            text: "Are you sure you want to save this group name?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                var json = {
                    "stockgroupunitname": $('#input-groupname').val().trim()
                }

                POST_StockAdjustGroup(json);
                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Group name sucessfully saved!",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    generateInventoryWithQOH();
                    loadGroupTbody();
                });
            }
        });
    } else {
        Swal.fire({
            text: "Are you sure you want to update this group name?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                let id = $('#input-groupid').val().trim()
                let name = $('#input-groupname').val().trim()
                let db = loadDB();
                var json = {
                    "id": id,
                    "groupname": name,
                    "dbname": db
                }

                PUT_StockAdjustGroup_by_ID(json);
                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Group name sucessfully saved!",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    generateInventoryWithQOH();
                    loadGroupTbody();
                });
            }
        });
    }
});

$('#modal-viewunit').on('shown.bs.modal', function () {
    $('#input-unitname').focus();
})


$(document).on('click', '#btn-viewunit', function () {

    $('#input-unitid').val('');
    $('#input-unitname').val('');
    $('#input-totalqty').val(1);

    var $row = $(this).closest("tr");    // Find the row
    var tdid = $row.find("td");
    var id = tdid[0].innerHTML;
    var groupname = tdid[1].innerHTML;
    loadUnitTBody(id);

    //$("#modal-viewunit").removeAttr("aria-hidden");
    $('#modal-viewunit').modal('show')
});

function loadUnitTBody(id, groupname) {
    let units = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit']
    units = units.filter(e => e['groupunitid'] == id)

    document.getElementById('btn-group').innerHTML = units[0]['groupunitname'];

    const tblBody = document.getElementById('tblbody-unit')
    tblBody.innerHTML = ""

    $.each(units[0]['units'], function (key, detail) {
        //console.log(detail)
        const tr = document.createElement("tr");
        tr.style = "height:1vh";

        const tdid = document.createElement("td")
        tdid.className = 'col-1 border-start border-end border-bottom  text-center px-1 align-content-center';
        const id = document.createTextNode(detail['unitid'].toString().trim());

        const tdname = document.createElement("td")
        tdname.className = 'col-2 border-start border-end border-bottom  text-center px-1 align-content-center';
        const name = document.createTextNode(detail['unitname'].toString().trim());

        const tdtotalqty = document.createElement("td")
        tdtotalqty.className = 'col-2 border-start border-end border-bottom  text-center px-1 align-content-center';
        const qty = document.createTextNode(detail['totalqty'].toFixed(2))

        const tdaction = document.createElement("td")
        tdaction.className = 'col-2 border-start border-end border-bottom  text-center px-1 align-content-center';
        //const action = document.createTextNode('');

        const btnedit = document.createElement("button")
        btnedit.id = "btn-edit-unit";
        btnedit.type = "button";
        btnedit.className = "btn p-1"

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

        const btndelete = document.createElement("button")
        btndelete.id = "btn-delete-unit";
        btndelete.type = "button";
        btndelete.className = "btn p-1"

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

        btnedit.appendChild(iconedit);
        btndelete.appendChild(icondelete);

        tdid.appendChild(id);
        tdname.appendChild(name);
        tdtotalqty.appendChild(qty)
        tdaction.appendChild(btnedit);
        //tdaction.appendChild(btndelete);

        tr.appendChild(tdid);
        tr.appendChild(tdname);
        tr.appendChild(tdtotalqty);
        tr.appendChild(tdaction);
        tblBody.appendChild(tr);


    });

}

$(document).on('click', '#btn-edit-unit', function () {
    var $row = $(this).closest("tr");    // Find the row
    var tdunit = $row.find("td");
    var unitid = tdunit[0].innerHTML;
    var unitname = tdunit[1].innerHTML;
    var unittotalqty = tdunit[2].innerHTML;

    $('#input-unitid').val(unitid);
    $('#input-unitname').val(unitname);
    $('#input-totalqty').val(unittotalqty);
});




$('input[type=search]').on('search', function () {
    $('#input-totalqty').val(1);
});

$('#btn-save-unit').click(function () {
   
    if ($('#input-unitname').val() == '') {
        Swal.fire({
            icon: "error",
            text: "Please enter unit name",
        }).then(function () {
            $("#input-groupname").trigger("focus");
        });
        return;
    }

    if ($('#input-totalqty').val() == '') {
        Swal.fire({
            icon: "error",
            text: "Please enter unit total qty",
        }).then(function () {
            $("#input-groupname").trigger("focus");
        });
        return;
    }

    if ($('#input-unitid').val() == '') {
        Swal.fire({
            text: "Are you sure you want to save this unit name?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                let unitname = $('#input-unitname').val();
                let totalqty = $('#input-totalqty').val();
                let groupname = document.getElementById('btn-group').innerHTML;
               
                let groups = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit'];
              
                let groupid = groups.filter((e) => e['groupunitname'].toLowerCase().trim() == groupname.toLowerCase().trim());
              
                var json = {
                    "stockunitname": unitname,
                    "totalqty": totalqty,
                    "stockgroupunitid": groupid[0]['groupunitid']
                }

                POST_StockAdjustUnit(json);
                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Unit name sucessfully saved!",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    generateInventoryWithQOH();
                    loadUnitTBody(groupid[0]['groupunitid']);
                    //generateInventoryWithQOH();
                    //loadGroupTbody();
                });
            }
        });
    } else {
        Swal.fire({
            text: "Are you sure you want to update this unit?",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes"
        }).then((result) => {
            if (result.isConfirmed) {
                let id = $('#input-unitid').val().trim();
                let name = $('#input-unitname').val().trim();
                let totalqty = $('#input-totalqty').val().trim();
                let groupname = document.getElementById('btn-group').innerHTML;
                let groups = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit'];
                let groupid = groups.filter((e) => e['groupunitname'].toLowerCase().trim() == groupname.toLowerCase().trim());
                let db = loadDB();
                var json = {
                    "id": id,
                    "name": name,
                    "qty": totalqty,
                    "groupid": groupid[0]['groupunitid'],
                    "dbname": db
                }

                PUT_StockAdjustUnit_by_ID(json);
                Swal.fire({
                    position: "center",
                    icon: "success",
                    text: "Unit sucessfully saved!",
                    showConfirmButton: false,
                    timer: 1500
                }).then((result) => {
                    generateInventoryWithQOH();
                    loadUnitTBody(groupid[0]['groupunitid']);
                });
            }
        });
    }



});

function dp_groups(groups) {

    //branchlist = branchlist.filter((e) => e['fullname'].toLowerCase().trim() != $('#input-branchfrom').val().toLowerCase().trim())
    document.getElementById('ul-group').innerHTML = '';
  var li = document.createElement('li')
    li.id = "u-groups" 

    document.getElementById('ul-group').appendChild(li)

  
    for (const item of groups) {    

  
        var a = document.createElement('a')
        a.className = 'dropdown-item text-capitalize'
        a.innerHTML = item['groupunitname']
        document.getElementById(li.id).appendChild(a)
    }
}

$(document).on('click', '#ul-group li', function () {
    //e.preventDefault(); // stop navigation
    
    document.getElementById('btn-group').innerText = $(this)[0].innerText;
});

function loadDropDownGoupUnit() {
    //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
    let stockgroupunit = JSON.parse(sessionStorage.getItem('data'))['stockgroupunit']
    let unit = stockgroupunit[0]['units'];
    document.getElementById('ddGroupUnit').innerHTML = '';
    document.getElementById('btnGroupUnit').innerText = stockgroupunit[0]['groupunitname'];

    for (const item of stockgroupunit) {
        var li = document.createElement('li')
        li.id = "gu" + item['groupunitid']
        document.getElementById('ddGroupUnit').appendChild(li)

        var a = document.createElement('a')
        a.className = 'dropdown-item'
        a.innerHTML = item['groupunitname']
        document.getElementById(li.id).appendChild(a)
    }
    loadDropDownUnit(JSON.stringify(unit))
}

function loadDropDownUnit(data) {
    let unit = JSON.parse(data);

    document.getElementById('ddUnit').innerHTML = ""
    document.getElementById('btnUnit').innerText = unit[0]['unitname']
    for (const item of unit) {

        var li = document.createElement('li')
        li.id = "u" + item['unitid']
        document.getElementById('ddUnit').appendChild(li)

        var a = document.createElement('a')
        a.className = 'dropdown-item'
        a.innerHTML = item['unitname']
        document.getElementById(li.id).appendChild(a)
    }
}

function loadCatgories() {
    //let categories = JSON.parse(getCategory());    
    let categories = JSON.parse(sessionStorage.getItem('data'))['categories'];
    for (const item of categories) {
        var option = document.createElement('option')
        option.innerHTML = item['CategoryName'];
        document.getElementById('list-category').appendChild(option)
    }
}

function resetField() {
    $('#inputqty').val('0')
    $('#inputcost').val('0.00')
    $('#inputbatchid').val(getBatchID());
}

function generateInventoryCostAverageDetailRow(inventoryid) {
    //let inventories = JSON.parse(sessionStorage.getItem('inventory'));
    let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
    let inventory = inventories.filter((e) => e['inventoryid'] == inventoryid);

    const sorterbyBatch = (a, b) => b['batchid'] > a['batchid'] ? 1 : -1;
    inventory[0]['icadetail'].sort(sorterbyBatch);
    //console.log(inventory[0]['icadetail'])
    paginateInventoryCostAverageDetail(inventory[0]['icadetail'])
}

//stock in table
function paginateInventoryCostAverageDetail(data) {

    const tblBody = document.getElementById('tblBodyAdjust');
    tblBody.innerHTML = '';

    let qtyin = data.reduce((accumulator, qty) => accumulator + qty['inqty'], 0);
    let qtyout = data.reduce((accumulator, qty) => accumulator + qty['outqty'], 0);
    let onhand = parseFloat(qtyin) - parseFloat(qtyout)

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

    //console.log(output)
    //$('.paginationjs').remove();
    $("#card-list").pagination({
        dataSource: output,
        //pageSize: 10,
        afterRender: function () {
            /*if ($("#card-list div.paginationjs").length == 1) {
                $("#card-list div.paginationjs").insertBefore("#card-list")
            }*/
        },
        callback: function (data, pagination) {
            $.each(data, function (key, detail) {
                const tr = document.createElement("tr");
                tr.style = "height:1vh";

                let alarmstatus = 'No';
                if (detail['expiryalarm'] == 1) {
                    alarmstatus = 'Yes';
                }
                let qoh = parseFloat(detail['inqty']) - parseFloat(detail['outqty']);
                const tdbatchid = document.createElement("td");
                tdbatchid.className = 'col-2 border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
                const batchid = document.createTextNode(detail['batchid'].toString().trim());

                const tddate = document.createElement("td");
                tddate.className = 'col-2 border-start border-end border-bottom  text-center px-1 align-content-center'
                const date = document.createTextNode(detail['stockdate'].substring(0, 10).toString().trim());

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

                const tdqtyin = document.createElement("td");
                tdqtyin.className = 'col-1 border-start border-end border-bottom  text-right px-1 py-1 align-content-center'
                const qtyin = document.createTextNode(detail['inqty'].toFixed(2));

                const tdqtyout = document.createElement("td");
                tdqtyout.className = 'col-1 border-start border-end border-bottom  text-right px-1 py-1 align-content-center'
                const qtyout = document.createTextNode(detail['outqty'].toFixed(2));

                const tdonhand = document.createElement("td");
                tdonhand.className = 'col-1 border-start border-end border-bottom  text-right px-1 py-1 align-content-center'
                const onhand = document.createTextNode(qoh.toFixed(2));

                const tdexpirydate = document.createElement("td");
                tdexpirydate.className = 'col-2 border-start border-end border-bottom text-center px-1 py-1 align-content-center'
                const expirydate = document.createTextNode(detail['expirydate'].substring(0, 10).toString().trim());

                const tdalarm = document.createElement("td");
                tdalarm.className = 'col-1 border-start border-end border-bottom  text-center px-1 py-1 align-content-center'
                //const alarm = document.createTextNode(detail['expiryalarm']);
                const alarm = document.createTextNode(alarmstatus);

                var tdsoaction = document.createElement('td')
                tdsoaction.className = 'col-2 border-end text-end border-bottom px-1 py-1 text-center'
                var soaction = document.createElement('div')
                soaction.className = 'p-0 m-0';
                soaction.id = Math.random().toString(16).substring(2, 16);

                tdbatchid.appendChild(batchid);
                tddate.appendChild(date);
                tdcost.append(cost);
                tdqtyin.append(qtyin);
                tdqtyout.append(qtyout);
                tdonhand.append(onhand);
                tdexpirydate.append(expirydate);
                tdalarm.append(alarm);
                tdsoaction.append(soaction);

                tr.appendChild(tdbatchid);
                tr.appendChild(tddate);
                tr.appendChild(tdcost);
                tr.appendChild(tdqtyin)
                tr.appendChild(tdqtyout);
                tr.appendChild(tdonhand);
                tr.appendChild(tdexpirydate);
                tr.appendChild(tdalarm);
                tr.appendChild(tdsoaction);

                tblBody.appendChild(tr);

                var stockout = document.createElement('button')
                stockout.type = 'button'

                if (qoh <= 0) {
                    stockout.className = 'btn btn-outline-danger btn-xs m-0 disabled'
                } else {
                    stockout.className = 'btn btn-outline-danger btn-xs m-0'
                }
                stockout.innerText = 'Stock Out'
                document.getElementById(soaction.id).appendChild(stockout);



            });
        },
    });
    $('.paginationjs').remove();
}

//stock detail
function inventoryDetailedView(data) {
    //let inventories = JSON.parse(sessionStorage.getItem('inventory'));
    let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
    let inventory = inventories.filter((e) => e['inventoryid'] == data[0]['inventoryid']);
    const tblBody = document.getElementById('tblBodyStockDetail');
    tblBody.innerHTML = '';

    //let qtyin = data.reduce((accumulator, qty) => accumulator + qty['inqty'], 0);
    //let qtyout = data.reduce((accumulator, qty) => accumulator + qty['outqty'], 0);       
    if ($("#chkshownegative").is(":checked") == false) {
        data = data.filter(function (e) {
            return e['batchid'] !== '';
        });
    }

    const items = data.reduce((accumulator, currentItem) => {
        const matchedItem = accumulator.find((item) => item['batchid'] === currentItem['batchid'] && item['unitcost'] === currentItem['unitcost']);
        if (!matchedItem) {
            return [...accumulator, currentItem];
        } else {
            matchedItem['inqty'] += currentItem['inqty']
            matchedItem['outqty'] += currentItem['outqty']
            return accumulator
        }

    }, []);



    $('.paginationjs').remove();
    $("#card-list").pagination({
        dataSource: items,
        //pageSize: 10,
        afterRender: function () {
            if ($("#card-list div.paginationjs").length == 1) {
                $("#card-list div.paginationjs").insertBefore("#card-list")
            }
        },
        callback: function (data, pagination) {
            $.each(data, function (key, detail) {
                let qoh = parseFloat(detail['inqty']) - parseFloat(detail['outqty']);
                let alarmstatus = 'No';

                if (detail['expiryalarm'] == 1) {
                    alarmstatus = 'Yes';
                }
                //console.log(qoh)

                if (qoh > 0 || qoh < 0) {
                    const tr = document.createElement("tr");
                    tr.style = "height:1vh";

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

                    /*const tdbarcode = document.createElement("td");
                    tdbarcode.className = 'col-2 border-start border-end border-bottom  text-left px-1 align-content-center'
                    const barcode = document.createTextNode(inventory[0]['barcode'].toString().trim());
    
                    const tdname = document.createElement("td");
                    tdname.className = 'col-2 border-start border-end border-bottom  text-left px-1 align-content-center'
                    const name = document.createTextNode(inventory[0]['name'].toString().trim());
    
                    const tddesc = document.createElement("td");
                    tddesc.className = 'col-1 border-start border-end border-bottom  text-left px-1 align-content-center'
                    const desc = document.createTextNode(inventory[0]['description'].toString().trim());*/

                    const tdcost = document.createElement("td");
                    tdcost.className = 'col-1 border-start border-end border-bottom  text-right px-1 align-content-center'
                    const cost = document.createTextNode(detail['unitcost'].toFixed(4));

                    const tdinqty = document.createElement("td");
                    tdinqty.className = 'col-1 border-start border-end border-bottom  text-right px-1 align-content-center'
                    const inqty = document.createTextNode(detail['inqty'].toFixed(2));

                    const tdoutqty = document.createElement("td");
                    tdoutqty.className = 'col-1 border-start border-end border-bottom text-right px-1 align-content-center'
                    const outqty = document.createTextNode(detail['outqty'].toFixed(2));

                    const tdonhand = document.createElement("td");
                    tdonhand.className = 'col-1 border-start border-end border-bottom  text-right px-1 align-content-center'
                    const onhand = document.createTextNode(qoh.toFixed(2));
                    //const onhand = document.createTextNode(inventory[0]['qoh'].toFixed(2));

                    const tdexpirydate = document.createElement("td");
                    tdexpirydate.className = 'col-2 border-start border-end border-bottom text-center px-1 align-content-center'
                    const expirydate = document.createTextNode(detail['expirydate'].substring(0, 10).toString().trim());

                    const tdalarm = document.createElement("td");
                    tdalarm.className = 'col-1 border-start border-end border-bottom  text-center px-1 align-content-center'
                    //const alarm = document.createTextNode(detail['expiryalarm']);
                    const alarm = document.createTextNode(alarmstatus);

                    tdbatchid.appendChild(batchid);
                    /*tdbarcode.appendChild(barcode);
                    tdname.append(name);
                    tddesc.append(desc);*/
                    tdcost.append(cost);
                    tdinqty.append(inqty);
                    tdoutqty.append(outqty);
                    tdonhand.append(onhand);
                    tdexpirydate.append(expirydate);
                    tdalarm.append(alarm);

                    tr.appendChild(tdbatchid);
                    /*tr.appendChild(tdbarcode);
                    tr.appendChild(tdname);
                    tr.appendChild(tddesc)*/
                    tr.appendChild(tdcost);
                    tr.appendChild(tdinqty);
                    tr.appendChild(tdoutqty);
                    tr.appendChild(tdonhand);
                    tr.appendChild(tdexpirydate);
                    tr.appendChild(tdalarm);
                    tblBody.appendChild(tr);
                }

            });
        },
    });
}

function generateInventoryWithQOH() {
    let sessioncategory = getCategory();
    let sessionitem = getInventory();

    let sessionica = getInventoryCostAverage();
    let sessionicadetail = getInventoryStockAdjustDetail();

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

    let setting = {
        'branch': loadDB()
    }

    arrinventory.sort((a, b) => a.barcode.localeCompare(b.barcode));
    //console.log(arrInventory)
    let data = {
        setting: setting,
        categories: category,
        stockgroupunit: generateStockAdjustUnit(),
        item: arrinventory
    }
    sessionStorage.setItem('data', JSON.stringify(data))
    //sessionStorage.setItem('inventory', JSON.stringify(arrinventory))
}

function generateStockAdjustUnit() {
    let groupunit = JSON.parse(getStockAdjustGroupUnit());
    let unit = JSON.parse(getStockAdjustUnit());
    let arrgroupunit = [];
    let arrunit = [];

    groupunit.forEach(function (groupunit) {
        arrunit = [];
        unit.forEach(function (unit) {
            if (groupunit['id'] == unit['stockgroupunitid']) {
                let unitdata = {
                    'unitid': unit['id'],
                    'unitname': unit['stockunitname'],
                    'totalqty': unit['totalqty']
                }
                arrunit.push(unitdata);
            }
        });

        let groupunitdata = {
            'groupunitid': groupunit['id'],
            'groupunitname': groupunit['stockgroupunitname'],
            'units': arrunit
        }
        arrgroupunit.push(groupunitdata)
    });
    return arrgroupunit;
    //sessionStorage.setItem('stockgroupunit', JSON.stringify(arrgroupunit))
}


//#region API's

function bearertoken() {
    let token;
    var settings = {
        "url": url + "/Users/authenticate",
        "method": "POST",
        "async": false,
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json"
        },
        "data": JSON.stringify({
            "username": "test",
            "password": "test"
        }),
    };

    $.ajax(settings).done(function (response) {
        token = response['token'];
    });
    return token;
}

function putInventoryCostAverage1(data) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/" + db + "/DFDownload/UpdateInventoryCostAverage",
        "method": "PUT",
        "async": false,
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(data),
    };

    $.ajax(settings).done(function (response, textStatus, xhr) {
        if (xhr.status == '200') {
            //getInventoryCostAverage()
            //generateInventoryWithQOH();
        }
    });
}

function putInventoryCostAverage(data) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/PUT_InventoryCostAverage",
        data: "{'jsondata':'" + JSON.stringify(data) + "'}",
        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 postInventoryCostAverageDetail1(data) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/InventoryCostAverageDetail?clientdb='" + db + "'",
        "method": "POST",
        "async": false,
        "timeout": 0,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(data),
    };

    $.ajax(settings).done(function (response, textStatus, xhr) {
        if (xhr.status == '200') {
            //let arrInventoryCostAverage = JSON.parse(sessionStorage.getItem('arrInventoryCostAverage'));
            //let itemInventoryCostAverage = arrInventoryCostAverage.filter((e) => e['InventoryID'] == data['inventoryid']);
            //let inventories = JSON.parse(sessionStorage.getItem('inventory'));
            let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
            let invetory = inventories.filter((e) => e['inventoryid'] == data['inventoryid']);

            let newpquantity = parseFloat(invetory[0]['pquantity']) + (parseFloat(data['inqty']) - parseFloat(data['outqty']));
            var putdata = {
                "inventoryid": data['inventoryid'],
                "pquantity": parseFloat(newpquantity),
                "dbname": db
            }
            putInventoryCostAverage(putdata);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown)
        console.log("error");
    }).always(function (jqXHR, textStatus, errorThrown) {

    })
}

function postInventoryCostAverageDetail(data) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/POST_InventoryCostAverageDetail",
        data: "{'jsondata':'" + JSON.stringify(data) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //console.log(errorThrown);
        },
        success: function (result) {
            //returnvalue = result.d;
            let inventories = JSON.parse(sessionStorage.getItem('data'))['item'];
            let invetory = inventories.filter((e) => e['inventoryid'] == data['inventoryid']);

            let newpquantity = parseFloat(invetory[0]['pquantity']) + (parseFloat(data['inqty']) - parseFloat(data['outqty']));
            var putdata = {
                "inventoryid": data['inventoryid'],
                "pquantity": parseFloat(newpquantity),
                "dbname": db
            }
            putInventoryCostAverage(putdata);
        }
    });
    return returnvalue;
}

function postInventoryAdjust1(data) {
    let db = loadDB();
    let token = bearertoken();
    var settings = {
        "url": url + "/api/InventoryAdjust?clientdb=" + db,
        "method": "POST",
        "timeout": 0,
        "async": true,
        "headers": {
            "Content-Type": "application/json",
            "Authorization": token
        },
        "data": JSON.stringify(data),
    };

    $.ajax(settings).done(function (response) {

    });
}

function postInventoryAdjust(data) {
    var returnvalue;
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/POST_InventoryAdjust",
        data: "{'jsondata':'" + JSON.stringify(data) + "'}",
        async: false,
        contentType: 'application/json;charset=utf8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //console.log(errorThrown);
        },
        success: function (result) {         
        }
    });
    return returnvalue;
}

//Get API's
function getInventory() {

    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getInventories",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //console.log(result.d)
            //sessionStorage.setItem('arrData', result.d);
            //generateInventoryWithQOH();
            //loadtblInventory();
        }
    });
    return response.responseJSON.d;
};

function getCategory() {
    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getCategories",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () { },
        complete: function (result) {
            // modalLoad.style.display = "none";

        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            // sessionStorage.setItem('category', result.d);
        }
    });
    return response.responseJSON.d;
}

function getInventoryCostAverage() {
    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getInventoryCostAverage",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) { console.log(errorThrown); },
        success: function (result) { }
    });
    return response.responseJSON.d;
}

function getStockAdjustGroupUnit() {
    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getStockAdjustGroupUnit",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //sessionStorage.setItem('arrGroupUnit', result.d)
        }
    });
    return response.responseJSON.d;
}

function getStockAdjustUnit() {
    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getStockAdjustUnit",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";
        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
            //sessionStorage.setItem('arrUnit', result.d)
        }
    });
    return response.responseJSON.d;
}

function getInventoryStockAdjustDetail() {
    var response = $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/getInventoryCostAverageDetail",
        async: false,
        contentType: 'application/json;charset=utf8',
        beforeSend: function () {
            //modalLoad.style.display = "block";
        },
        complete: function (result) {
            // modalLoad.style.display = "none";

        },
        dataType: 'json',
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        },
        success: function (result) {
        }
    });
    return response.responseJSON.d;
}

function getBatchID1() {
    let token = bearertoken();
    let db = loadDB();
    let batchid;
    var newbatchid;
    let batchidlength = '000000';
    var settings = {
        "url": url + "/api/" + db + "/InventoryCostAverageDetail/GetInventoryCostAverageDetail",
        "method": "GET",
        "async": false,
        "timeout": 0,
        "headers": {
            "Authorization": token
        },
    };

    $.ajax(settings).done(function (response) {
        let data = JSON.parse(response);
        data.sort(function (a, b) {
            return a['batchid'].localeCompare(b['batchid'])
        });

        //console.log(data)

        if (data.length > 0) {
            let lastbatchid = data.at(-1);
            let batchid = parseInt(lastbatchid['batchid']) + 1;

            newbatchid = batchidlength + batchid;
            newbatchid = newbatchid.substr(newbatchid.length - batchidlength.length);
        } else {
            newbatchid = batchidlength + 1;
            newbatchid = newbatchid.substr(newbatchid.length - batchidlength.length);
        }

    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("error");
    }).always(function (jqXHR, textStatus, errorThrown) {
    })

    return newbatchid;
}


function POST_StockAdjustGroup(json) {
    var db = loadDB();
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/POST_StockAdjustGroup",
        data: "{'db':'" + db + "','json':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: "application/json;charset=utf8",
        beforeSend: function () {

        }, complete: function (result) {

        },
        dataType: "json",
        error: function (jqXHR, textStatus, errorThrown) {

        }, success: function (result) {

        }
    });
}

function PUT_StockAdjustGroup_by_ID(json) {
    var db = loadDB();
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/PUT_StockAdjustGroup_By_ID",
        data: "{'json':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: "application/json;charset=utf8",
        beforeSend: function () {

        }, complete: function (result) {

        },
        dataType: "json",
        error: function (jqXHR, textStatus, errorThrown) {

        }, success: function (result) {

        }
    });
}

function POST_StockAdjustUnit(json) {
    let db = loadDB();
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/POST_StockAdjustUnit",
        data: "{'db':'" + db + "','json':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: "application/json;charset=utf8",
        beforeSend: function () {

        }, complete: function (result) {

        },
        dataType: "json",
        error: function (jqXHR, textStatus, errorThrown) {

        }, success: function (result) {

        }
    });
}

function PUT_StockAdjustUnit_by_ID(json) {
    var db = loadDB();
    $.ajax({
        type: "POST",
        url: "InventoryBatchAdjust.aspx/PUT_StockAdjustUnit_by_ID",
        data: "{'json':'" + JSON.stringify(json) + "'}",
        async: false,
        contentType: "application/json;charset=utf8",
        beforeSend: function () {

        }, complete: function (result) {

        },
        dataType: "json",
        error: function (jqXHR, textStatus, errorThrown) {

        }, success: function (result) {

        }
    });
}


//#endregion

