$(document).ready(function () {
    $(".accordion-toggle").click(function () {

        //var clickedValue = $(this).find('td:first').next()
        var clickedValue = $(this).closest('tr').children('td:first').text()
       
        if (clickedValue == '+') {
        
            $(this).closest('tr').children('td:first').text('-')
        }

        if (clickedValue == '-') {
   
            $(this).closest('tr').children('td:first').text('+')
        }


    });

});

function loadData(fromdate, todate,tdcjson) {

    let icad = getICAD();
    let categories = getCategories();
    let inventories = getInventories();
    let tdc = JSON.parse(tdcjson);
         
    icad = icad.filter(e => e['stockdate'].substring(0, 10) >= fromdate && e['stockdate'].substring(0, 10) <= todate);
    tdc = tdc.filter(e=> e['businessdate'].substring(0,10) >= fromdate && e['businessdate'].substring(0, 10) <= todate);
    
    categories = categories.filter((e) => e['CategoryName'].toLowerCase() != 'round')
    inventories = inventories.filter((e) => e['Class'] == 0 && e['Barcode'].toLowerCase() != 'round');

    let itemwithbatch = [];
    let data = [];
    inventories.forEach(function (inventory) {
        let batch = icad.filter((e) => e['inventoryid'] == inventory['InventoryID'])
        if (batch.length > 0) {
            let totalin = 0;
            let totalout = 0;
            batch.forEach(function (e) {
                totalin += e['inqty']
                totalout += e['outqty']
            })
            // console.log(totalin)
            let objitem = {
                'inventoryid': inventory['InventoryID'],
                'barcode': inventory['Barcode'].trim(),
                'name': inventory['InventoryName'].trim(),
                'description': inventory['Description'].trim(),
                'categoryid': inventory['CategoryID'],
                'totalinqty': totalin,
                'totaloutqty': totalout,
                'batches': batch,
            }
            itemwithbatch.push(objitem)
        }
    })

    categories.forEach(function (category) {
        let itemdetail = itemwithbatch.filter((e) => e['categoryid'] == category['CategoryID'])
        let totalin = 0;
        let totalout = 0;

        itemdetail.forEach(function (detail) {
            if (category['CategoryID'] == detail['categoryid']) {
                totalin += detail['totalinqty']
                totalout += detail['totaloutqty']
            }
        });

        if (itemdetail.length > 0) {
            let objcat = {
                'categoryid': category['CategoryID'],
                'categoryname': category['CategoryName'],
                'categorydescription': category['Description'],
                'totalinqty': totalin,
                'totaloutqty': totalout,
                'items': itemdetail
            }
            data.push(objcat)
        }
    })

    $.each(data, function (key, item) {
        const tblbody = document.getElementById('tblbody')
        var tr = document.createElement('tr')
        tr.className = 'accordion-toggle '

        tr.setAttribute('data-toggle', 'collapse')
        tr.setAttribute('data-target', '#' + item['categoryname'].toLowerCase().trim().split(" ").join(""))

        //var tdimg = document.createElement('td')

        //var buttonimg = document.createElement('button')
        //buttonimg.className = 'btn btn-default btn-xs'

        //var spanimg = document.createElement('span')
        //spanimg.className = 'bi bi-arrows-collapse'
        ////<i class="bi bi-arrows-collapse">
        //var tdcategoryid = document.createElement('td')
        //var categoryid = document.createElement('text')
        //categoryid.innerHTML = item['categoryid']
        var tdcategorycollapseicon = document.createElement('td')
        tdcategorycollapseicon.style='font-size:20px;font-weight:bold'
        var iicon = document.createElement('text')
        iicon.innerHTML = '+'

        var tdcategory = document.createElement('td')
        var category = document.createElement('text')
        category.innerHTML = item['categoryname'].trim();

        var tdcategory1 = document.createElement('td')
        var category1 = document.createElement('text')
        category1.innerHTML = '';

        var tdcategory2 = document.createElement('td')
        var category2 = document.createElement('text')
        category2.innerHTML = '';

        var tdcattotalinqty = document.createElement('td')
        var cattotalinqty = document.createElement('text')
        cattotalinqty.innerHTML = item['totalinqty'].toFixed(2)

        var tdcaltotaloutqty = document.createElement('td')
        var cattotaloutqty = document.createElement('text')
        cattotaloutqty.innerHTML = item['totaloutqty'].toFixed(2)

        //tr.appendChild(tdimg)
        //tdimg.appendChild(buttonimg)
        //buttonimg.appendChild(spanimg)

        //tr.appendChild(tdcategoryid)
        //tdcategoryid.appendChild(categoryid)

        tr.appendChild(tdcategorycollapseicon)
        tr.appendChild(tdcategory)
        tr.appendChild(tdcategory1)
        tr.appendChild(tdcategory2)
        tr.appendChild(tdcattotalinqty)
        tr.appendChild(tdcaltotaloutqty)


        tdcategorycollapseicon.appendChild(iicon)
        tdcategory.appendChild(category)
        tdcattotalinqty.appendChild(cattotalinqty)
        tdcaltotaloutqty.appendChild(cattotaloutqty)


        //inventory table
        var trheadinventory = document.createElement('tr')

        var tdheadinventory = document.createElement('td')
        tdheadinventory.colSpan = '12'
        tdheadinventory.className = 'hiddenRow'

        var divchildinventory = document.createElement('div')
        divchildinventory.className = 'accordian-body collapse'
        divchildinventory.id = item['categoryname'].toLowerCase().trim().split(" ").join("")


        var tablechildinventory = document.createElement('table')
        //tablechildinventory.className = 'table table-striped ml-3'
        tablechildinventory.className = 'table'

        var theadchildinventory = document.createElement('thead')


        var trchildheaderinventory = document.createElement('tr')
        trchildheaderinventory.className = 'bg-light'

        //var thinventoryspace = document.createElement('th')
        //var thspace = document.createElement('text')
        //thspace.innerHTML = ''

        //var thinventoryid = document.createElement('th')
        //var thid = document.createElement('text')
        //thid.innerHTML = 'INVENTORY ID'
        var thinventoryicon = document.createElement('th')
        thinventoryicon.style = 'width:50px'

        var thinventorybarcode = document.createElement('th')
        thinventorybarcode.className = 'col-1'
        var thbarcode = document.createElement('text')
        thbarcode.innerHTML = 'BARCODE'


        var thinventoryname = document.createElement('th')
        thinventoryname.className = 'col-2'
        var thname = document.createElement('text')
        thname.innerHTML = 'NAME'
        //thbarcode.className ='col-2 p-0'

        var thinventorydesc = document.createElement('th')
        thinventorydesc.className = 'col-3'
        var thdesc = document.createElement('text')
        thdesc.innerHTML = "DESCRIPTION"
        //thdesc.className = 'col-2  p-0'

        var thinventoryinqty = document.createElement('th')
        var thinqty = document.createElement('text')
        thinqty.innerHTML = "STOCK IN"

        var thinventoryoutqty = document.createElement('th')
        var thoutqty = document.createElement('text')
        thoutqty.innerHTML = "STOCK OUT"

        trheadinventory.appendChild(tdheadinventory)
        tdheadinventory.appendChild(divchildinventory)
        divchildinventory.appendChild(tablechildinventory)
        tablechildinventory.appendChild(theadchildinventory)
        theadchildinventory.appendChild(trchildheaderinventory)

        //trchildheaderinventory.appendChild(thinventoryspace)
        //thinventoryspace.appendChild(thspace)

        //trchildheaderinventory.appendChild(thinventoryid)
        //thinventoryid.appendChild(thid)

        trchildheaderinventory.appendChild(thinventoryicon)
        trchildheaderinventory.appendChild(thinventorybarcode)
        thinventorybarcode.appendChild(thbarcode)

        trchildheaderinventory.appendChild(thinventoryname)
        thinventoryname.appendChild(thname)

        trchildheaderinventory.appendChild(thinventorydesc)
        thinventorydesc.appendChild(thdesc)

        trchildheaderinventory.appendChild(thinventoryinqty)
        thinventoryinqty.appendChild(thinqty)

        trchildheaderinventory.appendChild(thinventoryoutqty)
        thinventoryoutqty.appendChild(thoutqty)

        var tbodychildinventory = document.createElement('tbody')

        tablechildinventory.appendChild(tbodychildinventory)


        //inventory data
        $.each(item['items'], function (key, item) {

            var trchildinventorydata = document.createElement('tr')
            trchildinventorydata.className = 'accordion-toggle'
            //trchildinventorydata.setAttribute('data-toggle', 'collapse')

            trchildinventorydata.setAttribute('data-toggle', 'collapse')
            trchildinventorydata.setAttribute('data-target', '#' + item['barcode'].toLowerCase().trim())

            tbodychildinventory.appendChild(trchildinventorydata)

            //var tdchildinventoryspace = document.createElement('td')
            //var tdinventoryspace = document.createElement('text')
            //tdinventoryspace.innerHTML = ''

            //var tdchildinventoryid = document.createElement('td')
            //var tdinventoryid = document.createElement('text')
            //tdinventoryid.innerHTML = item['inventoryid']

            var tdinventorycollapseicon = document.createElement('td')
            tdinventorycollapseicon.className = 'text-center'
            tdinventorycollapseicon.style = 'font-size:20px;font-weight:bold'
            var iicon = document.createElement('text')
            iicon.innerHTML = '+'


            var tdchildbarcode = document.createElement('td')
            var tdbarcode = document.createElement('text')
            tdbarcode.innerHTML = item['barcode']

            var tdchildname = document.createElement('td')
            var tdname = document.createElement('text')
            tdname.innerHTML = item['name']

            var tdchilddesc = document.createElement('td')
            var tddesc = document.createElement('text')
            tddesc.innerHTML = item['description']

            var tdchildtotalinqty = document.createElement('td')
            var tdtotalinqty = document.createElement('text')
            tdtotalinqty.innerHTML = item['totalinqty'].toFixed(2)

            var tdchildtotaloutqty = document.createElement('td')
            var tdtotaloutqty = document.createElement('text')
            tdtotaloutqty.innerHTML = item['totaloutqty'].toFixed(2)

            //tdchildinventoryspace.appendChild(tdinventoryspace)
            //tdchildinventoryid.appendChild(tdinventoryid)  
            tdinventorycollapseicon.appendChild(iicon)
            tdchildbarcode.appendChild(tdbarcode)
            tdchildname.appendChild(tdname)
            tdchilddesc.appendChild(tddesc)
            tdchildtotalinqty.append(tdtotalinqty)
            tdchildtotaloutqty.append(tdtotaloutqty)

            //trchildinventorydata.appendChild(tdinventoryspace)
            //trchildinventorydata.appendChild(tdchildinventoryid)
            trchildinventorydata.appendChild(tdinventorycollapseicon)
            trchildinventorydata.appendChild(tdchildbarcode)
            trchildinventorydata.appendChild(tdchildname)
            trchildinventorydata.appendChild(tdchilddesc)
            trchildinventorydata.appendChild(tdchildtotalinqty)
            trchildinventorydata.appendChild(tdchildtotaloutqty)


            //batch 
            var trheadbatch = document.createElement('tr')
            trheadbatch.className = 'bg-light'

            var tdheadbatch = document.createElement('td')
            tdheadbatch.colSpan = '12'
            tdheadbatch.className = 'hiddenRow'

            var divchildbatch = document.createElement('div')
            divchildbatch.className = 'accordian-body collapse'
            divchildbatch.id = item['barcode'].toLowerCase().trim()

            var tablechildbatch = document.createElement('table')
            tablechildbatch.className = 'table table-striped'

            var theadchildbatch = document.createElement('thead')

            var trchildheaderbatch = document.createElement('tr')
            trchildheaderbatch.className = 'bg-light'

            var thbatchicon = document.createElement('th')
            thbatchicon.style = 'width:50px'

            var thbatchid = document.createElement('th')
            thbatchid.className = 'col-1'
            var thid = document.createElement('text')
            thid.innerHTML = 'BATCH #'

            var thbatchnotes = document.createElement('th')
            thbatchnotes.className = 'col-2'
            var thnotes = document.createElement('text')
            thnotes.innerHTML = 'REF/NOTES'

            var thbatchdate = document.createElement('th')
            thbatchdate.className = 'col-2'
            var thdate = document.createElement('text')
            thdate.innerHTML = 'DATE'
            
            var thbatchunitcost = document.createElement('th')
            thbatchunitcost.className = 'col-1'
            var thunitcost = document.createElement('text')
            thunitcost.innerHTML = 'UNIT COST'

            var thbatchinqty = document.createElement('th')
            var thinqty = document.createElement('text')
            thinqty.innerHTML = 'STOCK IN'

            var thbatchoutqty = document.createElement('th')
            var thoutqty = document.createElement('text')
            thoutqty.innerHTML = 'STOCK OUT'

            trheadbatch.appendChild(tdheadbatch)
            tdheadbatch.appendChild(divchildbatch)
            divchildbatch.appendChild(tablechildbatch)
            tablechildbatch.appendChild(theadchildbatch)
            theadchildbatch.appendChild(trchildheaderbatch)

            trchildheaderbatch.appendChild(thbatchicon)
            trchildheaderbatch.appendChild(thbatchid)
            trchildheaderbatch.appendChild(thbatchnotes)
            trchildheaderbatch.appendChild(thbatchdate)
            trchildheaderbatch.appendChild(thbatchunitcost)
            trchildheaderbatch.appendChild(thbatchinqty)
            trchildheaderbatch.appendChild(thbatchoutqty)

            thbatchid.appendChild(thid)
            thbatchnotes.appendChild(thnotes)
            thbatchdate.appendChild(thdate)
            thbatchunitcost.appendChild(thunitcost)
            thbatchinqty.appendChild(thinqty)
            thbatchoutqty.appendChild(thoutqty)

            var tbodychildbatch = document.createElement('tbody')
            tablechildbatch.appendChild(tbodychildbatch)
            
            let tdcCtr = 0
       
            $.each(item['batches'], function (key, item) {
                let transid = '';   
                
                if(item['notes'].toLowerCase() == 'rs' || item['notes'].toLowerCase() == 'rsr' ){       
                                        
                    let transids = tdc.filter((e) => e['inventoryid'] == item['inventoryid'])                
                    transid = '(' +  transids[tdcCtr]['transid'] + ')'
                    tdcCtr = tdcCtr + 1
                }
                            
                var trchildbatchdata = document.createElement('tr')
                trchildbatchdata.className = 'accordion-toggle'
                //trchildinventorydata.setAttribute('data-toggle', 'collapse')
                
                var tdbatchcollapseicon = document.createElement('td')
                tdbatchcollapseicon.className = 'text-center'
                var iicon = document.createElement('text')
                iicon.innerHTML = ''

                var tdchildbatch = document.createElement('td')
                var childbatch = document.createElement('text')
                childbatch.innerHTML = item['batchid'] + transid

              
                var tdchildnotes = document.createElement('td')
                var childnotes = document.createElement('text')
                if(item['notes'].toLowerCase() == 'rs'){
                    childnotes.innerHTML = 'Retail Sales'
                }

                if(item['notes'].toLowerCase() == 'adj in' || item['notes'].toLowerCase() == 'adj out'){
                    childnotes.innerHTML = 'Inventory Adjustment' + ' (' + item['notes'].toLowerCase() + ')'
                }

                if(item['notes'].toLowerCase() == 'rsr'){
                    childnotes.innerHTML = '(Refund/Return)' 
                }
                

                var tdchilddate = document.createElement('td')
                var childdate = document.createElement('text')
                childdate.innerHTML = item['stockdate'].substring(0, 10)

                var tdchildcost = document.createElement('td')
                var childcost = document.createElement('text')
                childcost.innerHTML = item['unitcost'].toFixed(2)

                var tdchildinqty = document.createElement('td')
                var childqty = document.createElement('text')
                childqty.innerHTML = item['inqty'].toFixed(2)

                var tdchildoutqty = document.createElement('td')
                var childoutqty = document.createElement('text')
                childoutqty.innerHTML = item['outqty'].toFixed(2)

                tdbatchcollapseicon.appendChild(iicon)
                tdchildbatch.appendChild(childbatch)
                tdchildnotes.appendChild(childnotes)
                tdchilddate.appendChild(childdate)
                tdchildcost.appendChild(childcost)
                tdchildinqty.appendChild(childqty)
                tdchildoutqty.appendChild(childoutqty)

                trchildbatchdata.appendChild(tdbatchcollapseicon)
                trchildbatchdata.appendChild(tdchildbatch)
                trchildbatchdata.appendChild(tdchildnotes)
                trchildbatchdata.appendChild(tdchilddate)
                trchildbatchdata.appendChild(tdchildcost)
                trchildbatchdata.appendChild(tdchildinqty)
                trchildbatchdata.appendChild(tdchildoutqty)

                tablechildbatch.appendChild(trchildbatchdata)
            });

            tbodychildinventory.append(trheadbatch)

        });

        /*
        //child
        var trchild = document.createElement('tr')

        var tdchild = document.createElement('td')
        tdchild.colSpan = '12'
        tdchild.className = 'hiddenRow'

        var divchild = document.createElement('div')
        divchild.className = 'accordian-body collapse'
        divchild.id = 'demo1'

        var tablechild = document.createElement('table')
        tablechild.className = 'table table-striped'

        var theadchild = document.createElement('thead')

        var trchildtableheader = document.createElement('tr')
        trchildtableheader.className = 'info'

        var thchildbatch = document.createElement('th')
        var thbatch = document.createElement('text')
        thbatch.innerHTML = 'BATCH'

        var thchildref = document.createElement('th')
        var thref = document.createElement('text')
        thref.innerHTML = 'REF'

        var thchildcost = document.createElement('th')
        var thcost = document.createElement('text')
        thcost.innerHTML = 'COST'

        var thchildinqty = document.createElement('th')
        var thinqty = document.createElement('text')
        thinqty.innerHTML = 'IN QTY'

        var thchildoutqty = document.createElement('th')
        var thoutqty = document.createElement('text')
        thoutqty.innerHTML = 'OUT QTY'
            
        trchild.appendChild(tdchild)
        tdchild.appendChild(divchild)
        divchild.appendChild(tablechild)
        tablechild.appendChild(theadchild)

        theadchild.appendChild(trchildtableheader)

        trchildtableheader.appendChild(thchildbatch)
        thchildbatch.appendChild(thbatch)

        trchildtableheader.appendChild(thchildref)
        thchildref.appendChild(thref)

        trchildtableheader.appendChild(thchildcost)
        thchildcost.appendChild(thcost)

        trchildtableheader.appendChild(thchildinqty)
        thchildinqty.appendChild(thinqty)

        trchildtableheader.appendChild(thchildoutqty)
        thchildoutqty.appendChild(thoutqty)

        var tbodychild = document.createElement('tbody')

        tablechild.appendChild(tbodychild)


      

     
        //batches
        $.each(item['batches'], function (key, item) {

            var trchilddata = document.createElement('tr')
            //trchilddata.className = 'accordion-toggle'
            //trchilddata.setAttribute('data-toggle', 'collapse')

            tbodychild.appendChild(trchilddata) 

            var tdchildbatch = document.createElement('td')
            var childbatch = document.createElement('text')
            childbatch.innerHTML = item['batchid']

            var tdchildnotes = document.createElement('td')
            var childnotes = document.createElement('text')
            childnotes.innerHTML = item['notes']

            var tdchildcost = document.createElement('td')
            var childcost = document.createElement('text')
            childcost.innerHTML = item['unitcost']

            var tdchildinqty = document.createElement('td')
            var childqty = document.createElement('text')
            childqty.innerHTML = item['inqty']

            var tdchildoutqty = document.createElement('td')
            var childoutqty = document.createElement('text')
            childoutqty.innerHTML = item['outqty']

            tdchildbatch.appendChild(childbatch)           
            tdchildnotes.appendChild(childnotes)
            tdchildcost.appendChild(childcost)
            tdchildinqty.appendChild(childqty)
            tdchildoutqty.appendChild(childoutqty)

            trchilddata.appendChild(tdchildbatch)
            trchilddata.appendChild(tdchildnotes)
            trchilddata.appendChild(tdchildcost)
            trchilddata.appendChild(tdchildinqty)
            trchilddata.appendChild(tdchildoutqty)

        })*/




        tblbody.appendChild(tr)
        tblbody.appendChild(trheadinventory)

    })
}