let currentdate;
let nDiscflag = false;
let NNFDforTotal = false;
let TTaxType;
let sTaxTypeIdentifier = 0;
let NNFDforDiscI = false;

//let timerInterval;
//Swal.fire({
//    title: "Auto close alert!",
//    html: "I will close in <b></b> milliseconds.",
//    timer: 2000,
//    timerProgressBar: true,
//    didOpen: () => {
//        Swal.showLoading();
//        const timer = Swal.getPopup().querySelector("b");
//        timerInterval = setInterval(() => {
//            timer.textContent = `${Swal.getTimerLeft()}`;
//        }, 100);
//    },
//    willClose: () => {
//        clearInterval(timerInterval);
//    }
//}).then((result) => {
//    /* Read more about handling dismissals below */
//    if (result.dismiss === Swal.DismissReason.timer) {
//        console.log("I was closed by the timer");
//    }
//});


$(document).ready(function () {
    currentdate = getDateTime();

    let itemlist = JSON.parse(GET_AllInventory());
    let sessionselecteditems = JSON.parse(sessionStorage.getItem('transactioncollection'));
    Load_PaymentType();

    if (sessionselecteditems != null) {
        $('#input-invoiceno').val(sessionselecteditems['transno']);

        P_CalculateAmountProc()
    } else {
        $('#input-invoiceno').val(generateInvoiceNumber())
    }

    $("#input-scan").on("keypress", function (e) {
        if (e.key === "Enter") {
            e.preventDefault();
            let scanneditem = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == $('#input-scan').val().toLowerCase().trim());
            if (scanneditem.length == 0) {
                Swal.fire({
                    icon: "warning",
                    text: "Item Not Found",
                    timer: 1500
                }).then(function () {
                    $('#input-scan').val('')
                });
                return;
            }

            let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

            if (storedtransactioncollection != null) {
                let trans = storedtransactioncollection;
                sessionStorage.setItem('currentsession', JSON.stringify(trans));
            }

            let product = scanneditem[0];
            let item = {
                "barcode": product["Barcode"].trim(),
                "name": product["InventoryName"].trim(),
                "inventorydesc": product["Description"].trim(),
                "stockcode": "",
                "price": product['Price'],
                "price2": product['Price2'],
                "price3": product['Price3'],
                "price4": product['Price4'],
                "nopriceshift": 0,
                "categorynumber": parseInt(product["CategoryID"]),
                "group1": product['Group1'],
                "group2": product['Group2'],
                "group3": product['Group3'],
                "group4": product['Group4'],
                "group5": product['Group5'],
                "itemclass": 0,
                "qty": 1,
                "unit": "PCS",
                "disctype": 0,
                "discvalue": 0,
                "manualdisc": 0,
            }
            AddItemProc(item)
        }
        sessionStorage.removeItem('currentsession');
    });

    $('#table-selecteditems').on('keyup', 'td[contenteditable]', function (event) {
        if (event.which != 8 && isNaN(String.fromCharCode(event.which))) {
            $(this).closest("tr").find('td:eq(3)').find("input").val(1);
            event.preventDefault();
        } else {
            //let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
            //if (storedtransactioncollection != null) {


            var rowIndex = $(this).closest('tr').index();

            let itemprice = $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(4)').text();
            let qty = $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(3)').find("input").val();
            let currentdiscamount = $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(6)').find("input").val();

            itemprice = parseFloat(itemprice) * parseFloat(qty);

            if (itemprice < currentdiscamount) {
                Swal.fire({
                    position: "center",
                    icon: "info",
                    text: "Item discount exceed the item amount",
                    showConfirmButton: true,
                    //timer: 1500
                }).then((result) => {
                    $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(6)').find("input").val('0.00');
                    $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(9)').text('0.00');
                });
            }


            //sessionStorage.clear();
            let disctype = 1;
            let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

            if (storedtransactioncollection != null) {
                let trans = storedtransactioncollection;
                sessionStorage.setItem('currentsession', JSON.stringify(trans));
            }

            sessionStorage.removeItem('transactioncollection');
            $('#table-selecteditems tbody tr').each(function () {
                let qty = $(this).closest("tr").find('td:eq(3)').find("input").val();
                let barcode = $(this).closest("tr").find('td:eq(0)').text();
                let amount = $(this).closest("tr").find('td:eq(4)').text();
                let discpercentage = $(this).closest("tr").find('td:eq(5)').find("input").val();
                let discamount = $(this).closest("tr").find('td:eq(6)').find("input").val();
                let product = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == barcode.toLowerCase().toString().trim());

                disctype = 0;
                discvalue = 0;
                manualdisc = 0;
                if (parseFloat(discpercentage) > 0) {
                    disctype = 1;
                    discvalue = parseFloat(discpercentage) / 100;
                    amount = parseFloat(amount) * parseInt(qty);
                    manualdisc = amount * discvalue;
                }

                if (parseFloat(discamount) > 0) {
                    disctype = 0;
                    discvalue = 0;
                    manualdisc = discamount;

                    if (itemprice < discamount) {
                        manualdisc = 0
                    }
                }

                product = product[0];
                let item = {
                    "barcode": product["Barcode"].trim(),
                    "name": product["InventoryName"].trim(),
                    "inventorydesc": product["Description"].trim(),
                    "stockcode": "",
                    "price": product['Price'],
                    "price2": product['Price2'],
                    "price3": product['Price3'],
                    "price4": product['Price4'],
                    "nopriceshift": 0,
                    "categorynumber": parseInt(product["CategoryID"]),
                    "group1": product['Group1'],
                    "group2": product['Group2'],
                    "group3": product['Group3'],
                    "group4": product['Group4'],
                    "group5": product['Group5'],
                    "itemclass": 0,
                    "qty": qty,
                    "unit": "PCS",
                    "disctype": disctype,
                    "discvalue": discvalue,
                    "manualdisc": manualdisc,
                }
                AddItemProc(item);
            });


            //}
        }
        sessionStorage.removeItem('currentsession');
    });

    $(document).on('click', 'button', function () {
        let disctype = 0;
        if ($(this)[0].children.length > 0) {
            Swal.fire({
                text: "Are you sure you want to delete this item?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes"
            }).then((result) => {
                //sessionStorage.clear();
                $(this).closest("tr").remove();
                //sessionStorage.clear();
                let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

                if (storedtransactioncollection != null) {
                    let trans = storedtransactioncollection;
                    sessionStorage.setItem('currentsession', JSON.stringify(trans));
                }
                sessionStorage.removeItem('transactioncollection');

                $('#table-selecteditems tbody tr').each(function () {
                    let qty = $(this).closest("tr").find('td:eq(3)').find("input").val();
                    let barcode = $(this).closest("tr").find('td:eq(0)').text();
                    let amount = $(this).closest("tr").find('td:eq(4)').text();
                    let discpercentage = $(this).closest("tr").find('td:eq(5)').find("input").val();
                    let discamount = $(this).closest("tr").find('td:eq(6)').find("input").val();
                    let product = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == barcode.toLowerCase().toString().trim());
                    let discvalue = 0;
                    let manualdisc = 0;
                    if (parseFloat(discpercentage) > 0) {
                        disctype = 1;
                        discvalue = parseFloat(discpercentage) / 100;
                        manualdisc = amount * discvalue;
                    }

                    if (parseFloat(discamount) > 0) {
                        disctype = 0;
                        discvalue = 0;
                        manualdisc = discamount;
                    }

                    product = product[0];

                    let item = {
                        "barcode": product["Barcode"].trim(),
                        "name": product["InventoryName"].trim(),
                        "inventorydesc": product["Description"].trim(),
                        "stockcode": "",
                        "price": product['Price'],
                        "price2": product['Price2'],
                        "price3": product['Price3'],
                        "price4": product['Price4'],
                        "nopriceshift": 0,
                        "categorynumber": parseInt(product["CategoryID"]),
                        "group1": product['Group1'],
                        "group2": product['Group2'],
                        "group3": product['Group3'],
                        "group4": product['Group4'],
                        "group5": product['Group5'],
                        "itemclass": 0,
                        "qty": qty,
                        "unit": "PCS",
                        "disctype": disctype,
                        "discvalue": discvalue,
                        "manualdisc": manualdisc,
                    }
                    AddItemProc(item);
                });
                sessionStorage.removeItem('currentsession');
                if ($('#table-selecteditems tbody tr').length == 0) {
                    P_DisplayDetailProc();
                }
            });
        }
    })

    $('#table-selecteditems tbody').on('change', 'tr #input-disc', function () {
        let disctype = 1;
        let manualdisc = 0;

        //sessionStorage.clear();
        let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

        if (storedtransactioncollection != null) {
            let trans = storedtransactioncollection;
            sessionStorage.setItem('currentsession', JSON.stringify(trans));
        }

        sessionStorage.removeItem('transactioncollection');


        if (storedtransactioncollection == null) {
            transid = 0;
            transno = 0
            customernumber = '';
        } else {
            if (parseInt(storedtransactioncollection['transid']) > 0) {
                transid = parseInt(storedtransactioncollection['transid']);
                transno = storedtransactioncollection['transno']
            }
            customernumber = storedtransactioncollection['customernumber'];
        }

        $('#table-selecteditems tbody tr').each(function () {
            let discvalue = 0;
            let barcode = $(this).closest("tr").find('td:eq(0)').text();
            let qty = $(this).closest("tr").find('td:eq(3)').find("input").val();
            let amount = $(this).closest("tr").find('td:eq(4)').text();
            let discpercentage = $(this).closest("tr").find('td:eq(5)').find("input").val();
            let discamount = $(this).closest("tr").find('td:eq(6)').find("input").val();
            let product = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == barcode.toLowerCase().toString().trim());

            disctype = 0;
            discvalue = 0;
            manualdisc = 0;
            if (parseFloat(discpercentage) > 0) {
                disctype = 1;
                discvalue = parseFloat(discpercentage) / 100;
                amount = parseFloat(amount) * parseInt(qty);
                manualdisc = amount * discvalue;

            }

            if (parseFloat(discamount) > 0) {
                disctype = 0;
                discvalue = 0;
                manualdisc = discamount;
            }


            product = product[0];
            let item = {
                "barcode": product["Barcode"].trim(),
                "name": product["InventoryName"].trim(),
                "inventorydesc": product["Description"].trim(),
                "stockcode": "",
                "price": product['Price'],
                "price2": product['Price2'],
                "price3": product['Price3'],
                "price4": product['Price4'],
                "nopriceshift": 0,
                "categorynumber": parseInt(product["CategoryID"]),
                "group1": product['Group1'],
                "group2": product['Group2'],
                "group3": product['Group3'],
                "group4": product['Group4'],
                "group5": product['Group5'],
                "itemclass": 0,
                "qty": qty,
                "unit": "PCS",
                "disctype": disctype,
                "discvalue": discvalue,
                "manualdisc": manualdisc,
            }
            AddItemProc(item);

        });
        sessionStorage.removeItem('currentsession');
        //$('#modal-add-discount').modal('show')
    });

    $('#table-selecteditems tbody').on('change', 'tr #input-discamount', function (e) {
        var rowIndex = $(this).closest('tr').index();
        var inputamount = $(this).val();
        let currentamount = $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(10)').text();


        e.preventDefault();
        if (parseFloat(inputamount) > parseFloat(currentamount)) {

            Swal.fire({
                position: "center",
                icon: "info",
                text: "Item discount exceed the item amount",
                showConfirmButton: true,
                //timer: 1500

            }).then((result) => {
                $('#table-selecteditems tbody tr').eq(parseInt(rowIndex)).find('td:eq(6)').find("input").val('0.00');
                return;
            });
            return;
        }

        if (parseFloat(inputamount) < parseFloat(currentamount)) {
            let disctype = 0;
            let manualdisc = 0;
            //sessionStorage.clear();
            let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

            if (storedtransactioncollection != null) {
                let trans = storedtransactioncollection;
                sessionStorage.setItem('currentsession', JSON.stringify(trans));
            }

            sessionStorage.removeItem('transactioncollection');


            if (storedtransactioncollection == null) {
                transid = 0;
                transno = 0
                customernumber = '';
            } else {
                if (parseInt(storedtransactioncollection['transid']) > 0) {
                    transid = parseInt(storedtransactioncollection['transid']);
                    transno = storedtransactioncollection['transno']
                }
                customernumber = storedtransactioncollection['customernumber'];
            }

            $('#table-selecteditems tbody tr').each(function () {
                let discvalue = 0;
                let barcode = $(this).closest("tr").find('td:eq(0)').text();
                let qty = $(this).closest("tr").find('td:eq(3)').find("input").val();
                let amount = $(this).closest("tr").find('td:eq(4)').text();
                let discpercentage = $(this).closest("tr").find('td:eq(5)').find("input").val();
                let discamount = $(this).closest("tr").find('td:eq(6)').find("input").val();
                let product = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == barcode.toLowerCase().toString().trim());

                disctype = 0;
                discvalue = 0;
                manualdisc = 0;
                if (parseFloat(discpercentage) > 0) {
                    disctype = 1;
                    discvalue = parseFloat(discpercentage) / 100;
                    manualdisc = amount * discvalue;
                }

                if (parseFloat(discamount) > 0) {
                    disctype = 0;
                    discvalue = 0;
                    manualdisc = discamount;
                }

                product = product[0];
                let item = {
                    "barcode": product["Barcode"].trim(),
                    "name": product["InventoryName"].trim(),
                    "inventorydesc": product["Description"].trim(),
                    "stockcode": "",
                    "price": product['Price'],
                    "price2": product['Price2'],
                    "price3": product['Price3'],
                    "price4": product['Price4'],
                    "nopriceshift": 0,
                    "categorynumber": parseInt(product["CategoryID"]),
                    "group1": product['Group1'],
                    "group2": product['Group2'],
                    "group3": product['Group3'],
                    "group4": product['Group4'],
                    "group5": product['Group5'],
                    "itemclass": 0,
                    "qty": qty,
                    "unit": "PCS",
                    "disctype": disctype,
                    "discvalue": discvalue,
                    "manualdisc": manualdisc,
                }
                AddItemProc(item);
            });
            //$('#modal-add-discount').modal('show')
        }
        sessionStorage.removeItem('currentsession');

    });

    $("#button-apply-discount").on('click', function (event) {
        let row = $('#label-rowindex').text();

        let inputvalue = $('#input-value').val();
        let disctype = 0;
        let discvalue = 0;
        let manualdisc = 0;
        let unitprice = $('#table-selecteditems tbody tr').eq(parseInt(row)).find('td:eq(4)').text();
        let qty = $('#table-selecteditems tbody tr').eq(parseInt(row)).find('td:eq(3)').find("input").val();
        let barcode = $('#table-selecteditems tbody tr').eq(parseInt(row)).find('td:eq(0)').text();
        let product = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == barcode.toLowerCase().toString().trim());
        if (document.getElementById('button-discount-type').innerHTML.toLowerCase().trim() == 'percent(%)') {
            disctype = 1;
            manualdisc = parseFloat(unitprice) - ((parseFloat(unitprice) / 100) * (parseFloat(inputvalue)))
            manualdisc = parseFloat(unitprice) - parseFloat(manualdisc);
            discvalue = parseFloat(inputvalue) / 100
        }
        product = product[0];

        let item = {
            "barcode": product["Barcode"].trim(),
            "name": product["InventoryName"].trim(),
            "inventorydesc": product["Description"].trim(),
            "stockcode": "",
            "price": product['Price'],
            "price2": product['Price2'],
            "price3": product['Price3'],
            "price4": product['Price4'],
            "nopriceshift": 0,
            "categorynumber": parseInt(product["CategoryID"]),
            "group1": product['Group1'],
            "group2": product['Group2'],
            "group3": product['Group3'],
            "group4": product['Group4'],
            "group5": product['Group5'],
            "itemclass": 0,
            "qty": qty,
            "unit": "PCS",
            "disctype": disctype,
            "discvalue": discvalue,
            "manualdisc": manualdisc,
        }
        AddItemProc(item);
        $('#table-selecteditems tbody tr').eq(parseInt(row)).find('td:eq(5)').find("input").val(manualdisc);
        $('#modal-add-discount').modal('hide')
    });

    $("#button-search-customer").on('click', function (event) {
        //console.log(InventoryWithCostDetail());
        let customers = GET_AllCustomer();
        Load_Customers(customers);
        $('#modal-add-customer').modal('show')
    });

    $('#input-searchcustomer').on("keyup", function () {
        var value = $(this).val().toLowerCase();
        $("#table-body-customer tr").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

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

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

        $("input.sev_check:checked").each(function () {
            let customername = $(this).closest('tr').find('td:eq(2)').text();
            let cid = $(this).closest('tr').find('td:eq(1)').text();
            let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
            if (storedtransactioncollection == null) {
                //console.log(storedtransactioncollection)
                //storedtransactioncollection['customernumber'] = cid;
                let trans = {
                    "SITransdetailList": [],
                    //"SITranspayment": {
                    //    "paymentid": 0,
                    //    "transid": 0,
                    //    "paydate": currentdate,
                    //    "isdeposit": 0,
                    //    "paymenttype": "",
                    //    "paymentamount": 0,
                    //    "paycurrency": "",
                    //    "rate": 0,
                    //    "realpayment": 0,
                    //    "changes": 0,
                    //    "checkout": 0,
                    //    "paytime": 0,
                    //    "paid": 0,
                    //    "businessdate": currentdate,
                    //    "termid": 0,
                    //    "cardnumber": "",
                    //    "cardname": "",
                    //    "merchantid": "",
                    //    "terminalid": "",
                    //    "refnumber": "",
                    //    "netscardno": "",
                    //    "netstransno": "",
                    //    "cashcardbalance": 0,
                    //    "netsbatchno": "",
                    //    "changecurrency": "",
                    //    "signature": "",
                    //    "paymentcaption": ""
                    //},
                    "transid": 0,
                    "transno": 0,
                    "termid": 0,
                    "transdate": currentdate,
                    "lastdate": currentdate,
                    "transtime": currentdate,
                    "customernumber": cid,
                    "cashierid": 0,
                    "cashiername": "",
                    "salespersonid": 0,
                    "salespersonname": "",
                    "hassalesman": 0,
                    "subtotal": 0,
                    "taxamount1": 0,
                    "taxamount2": 0,
                    "taxamount3": 0,
                    "taxamount4": 0,
                    "taxamount5": 0,
                    "taxamount6": 0,
                    "total": 0,
                    "disctype": 0,
                    "discamount": 0,
                    "discvalue": 0,
                    "points": 0,
                    "transstatus": 0,
                    "manualkey": "",
                    "checkout": 0,
                    "round": 0,
                    "memberdiscamount": 0,
                    "memberdiscvalue": 0,
                    "birthdaydiscamount": 0,
                    "birthdaydiscvalue": 0,
                    "scdiscamount": 0,
                    "scdiscvalue": 0,
                    "sccovers": 0,
                    "screttaxamount": 0,
                    "asdiscamount": 0,
                    "asdiscvalue": 0,
                    "printed": 0,
                    "covers": 0,
                    "notes": "",
                    "paidtotal": 0,
                    "timestampid": 0,
                    "businessdate": currentdate,
                    "vouchertotal": 0,
                    "rdpointstotal": 0,
                    "rdflag": 0,
                    "rdpointsamount": 0,
                    "rdpointvalue": 0,
                    "tablemenuid": "",
                    "delivercustno": "",
                    "pddiscamount": 0,
                    "pddiscvalue": 0,
                    "pdcovers": 0,
                    "gerettaxamount": 0,
                    "gecovers": 0,
                    "managerid": 0,
                    "managername": "",
                    "sendflag": 0,
                    "edittransid": 0,
                    "orderid": 0,
                    "kioskorderno": "",
                    "splitbill": 0,
                    "duedays": 0,
                    "duetype": "",
                    "previouspoints": 0,
                    "kdsorderstatus": 0,
                    "kdspriority": 0,
                    "kdscmpttime": currentdate,
                    "pdrettaxamount": 0,
                    "doaddress": "",
                    "printhold": 0,
                    "advcustomerid": "",
                    "advcountrycode": "",
                    "advsvbal": 0,
                    "advvbal": 0,
                    "advlpoints": 0,
                    "advllpoints": 0,
                    "advlpid": "",
                    "advlprid": "",
                    "advskurid": "",
                    "advcashback": 0,
                    "advlcashback": 0,
                    "advcbid": "",
                    "advcbrid": "",
                    "stbcpprev": 0,
                    "stbcpbal": 0,
                    "kiosktakeaway": 0,
                    "advvourid": "",
                    "kdsprinttimes": 0,
                    "stbcporderno": "",
                    "depprevbal": 0,
                    "depbal": 0,
                    "webtransid": "",
                    "issync": 0,
                    "navsync": 0,
                    "rsgid": "",
                    "rsgvoucher": "",
                    "rsgvalue": 0,
                    "rsgforfeit": 0,
                    "rsgstatus": 0
                }
                sessionStorage.setItem('transactioncollection', JSON.stringify(trans));
            } else {
                storedtransactioncollection['customernumber'] = cid;
                sessionStorage.setItem('transactioncollection', JSON.stringify(storedtransactioncollection));
            }


            $('#input-customer').val(customername);
            $('#modal-add-customer').modal('hide')
        });
    });

    $('#button-preview').click(function () {
        Preview();
    });

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

});

function GET_AllTax() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_AllTax",
        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) {
            responseVal = JSON.parse(result.d);
        }
    });
    return responseVal;
}

function GET_AllCategory() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.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) {
            responseVal = result.d;
            // sessionStorage.setItem('category', result.d);
        }
    });
    return responseVal;
}

function GET_AllInventory() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.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) {
            responseVal = result.d;
        }
    });
    return responseVal;
};

function GET_AllPaymentType() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_AllPaymentType",
        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) {
            responseVal = JSON.parse(result.d);
        }
    });
    return responseVal;
}

//1
function AddItemProc(item) {

    let transid = 0;
    let transno = 0;
    let transstatus = 4;
    let customernumber;
    let transdate;
    let transtime;
    let businessdate;

    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('currentsession'))
    //console.log(storedtransactioncollection)
    if (storedtransactioncollection == null) {
        transid = 0;
        transno = 0
        customernumber = '';
        transdate = currentdate;
        transtime = currentdate;
        businessdate = currentdate;
    } else {
        //if (parseInt(storedtransactioncollection['transid']) > 0) {
            console.log(storedtransactioncollection)
            transid = parseInt(storedtransactioncollection['transid']);
            transno = storedtransactioncollection['transno']
            transdate = storedtransactioncollection['transdate'];
            transtime = storedtransactioncollection['transtime'];
            businessdate = storedtransactioncollection['businessdate'];
       // }
        customernumber = storedtransactioncollection['customernumber'];
    }

    let trans = {
        "SITransdetailList": itemCollection(item),
        //"SITranspayment": {
        //    "paymentid": 0, 
        //    "transid": transid,
        //    "paydate": currentdate,
        //    "isdeposit": 0,
        //    "paymenttype": "",
        //    "paymentamount": 0,
        //    "paycurrency": "",
        //    "rate": 0,
        //    "realpayment": 0,
        //    "changes": 0,
        //    "checkout": 0,
        //    "paytime": 0,
        //    "paid": 0,
        //    "businessdate": currentdate,
        //    "termid": 0,
        //    "cardnumber": "",
        //    "cardname": "",
        //    "merchantid": "",
        //    "terminalid": "",
        //    "refnumber": "",
        //    "netscardno": "",
        //    "netstransno": "",
        //    "cashcardbalance": 0,
        //    "netsbatchno": "",
        //    "changecurrency": "",
        //    "signature": "",
        //    "paymentcaption": ""
        //},
        "transid": transid,
        "transno": transno,
        "termid": 0,
        "transdate": transdate,
        "lastdate": currentdate,
        "transtime": transtime,
        "customernumber": customernumber,
        "cashierid": 0,
        "cashiername": "",
        "salespersonid": 0,
        "salespersonname": "",
        "hassalesman": 0,
        "subtotal": 0,
        "taxamount1": 0,
        "taxamount2": 0,
        "taxamount3": 0,
        "taxamount4": 0,
        "taxamount5": 0,
        "taxamount6": 0,
        "total": 0,
        "disctype": 0,
        "discamount": 0,
        "discvalue": 0,
        "points": 0,
        "transstatus": transstatus,
        "manualkey": "",
        "checkout": 0,
        "round": 0,
        "memberdiscamount": 0,
        "memberdiscvalue": 0,
        "birthdaydiscamount": 0,
        "birthdaydiscvalue": 0,
        "scdiscamount": 0,
        "scdiscvalue": 0,
        "sccovers": 0,
        "screttaxamount": 0,
        "asdiscamount": 0,
        "asdiscvalue": 0,
        "printed": 0,
        "covers": 0,
        "notes": "",
        "paidtotal": 0,
        "timestampid": 0,
        "businessdate": businessdate,
        "vouchertotal": 0,
        "rdpointstotal": 0,
        "rdflag": 0,
        "rdpointsamount": 0,
        "rdpointvalue": 0,
        "tablemenuid": "",
        "delivercustno": "",
        "pddiscamount": 0,
        "pddiscvalue": 0,
        "pdcovers": 0,
        "gerettaxamount": 0,
        "gecovers": 0,
        "managerid": 0,
        "managername": "",
        "sendflag": 0,
        "edittransid": 0,
        "orderid": 0,
        "kioskorderno": "",
        "splitbill": 0,
        "duedays": 0,
        "duetype": "",
        "previouspoints": 0,
        "kdsorderstatus": 0,
        "kdspriority": 0,
        "kdscmpttime": currentdate,
        "pdrettaxamount": 0,
        "doaddress": "",
        "printhold": 0,
        "advcustomerid": "",
        "advcountrycode": "",
        "advsvbal": 0,
        "advvbal": 0,
        "advlpoints": 0,
        "advllpoints": 0,
        "advlpid": "",
        "advlprid": "",
        "advskurid": "",
        "advcashback": 0,
        "advlcashback": 0,
        "advcbid": "",
        "advcbrid": "",
        "stbcpprev": 0,
        "stbcpbal": 0,
        "kiosktakeaway": 0,
        "advvourid": "",
        "kdsprinttimes": 0,
        "stbcporderno": "",
        "depprevbal": 0,
        "depbal": 0,
        "webtransid": "",
        "issync": 0,
        "navsync": 0,
        "rsgid": "",
        "rsgvoucher": "",
        "rsgvalue": 0,
        "rsgforfeit": 0,
        "rsgstatus": 0
    }

    console.log(trans)
    sessionStorage.setItem('transactioncollection', JSON.stringify(trans));
    P_CalculateAmountProc();
}

//2
function P_CalculateAmountProc() {
    ProcessTotalProc()
    P_DisplayDetailProc();
}

function P_DisplayDetailProc() {
    let customer = GET_AllCustomer();

    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    if (storedtransactioncollection != null) {
        let trans = storedtransactioncollection;
        let transdetail = storedtransactioncollection['SITransdetailList']
        //let transpayment = storedtransactioncollection['SITranspayment']
        let tbody = document.getElementById("tbody-item");
        tbody.innerHTML = "";
        //load data in row and col
        $.each(transdetail, function (key, detail) {

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

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

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

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

            let tdqty = document.createElement("td");
            tdqty.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center ';
            tdqty.setAttribute('contenteditable', 'true');

            //let qty = document.createTextNode("1");
            let inputqty = document.createElement("input");
            inputqty.id = "input-qty";
            inputqty.className = "form-control text-right font-14";
            inputqty.type = "text";
            inputqty.setAttribute('required', 'true');
            inputqty.value = detail['qty'];
            if (detail['qty'] == undefined) {
                inputqty.value = "1";
            }

            let tdunitprice = document.createElement("td");
            tdunitprice.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
            let unitprice = document.createTextNode(parseFloat(detail['price']).toFixed(2))

            let tddisc = document.createElement("td");
            tddisc.classname = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';

            let inputdisc = document.createElement("input");
            inputdisc.id = "input-disc";
            inputdisc.className = "form-control text-right font-14";
            inputdisc.type = "text";


            let tddiscamount = document.createElement("td");
            tddiscamount.classname = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';

            let inputdiscamount = document.createElement("input");
            inputdiscamount.id = "input-discamount";
            inputdiscamount.className = "form-control text-right font-14";
            inputdiscamount.type = "text";


            //inputdisc.setAttribute('required','true');    
            if (detail['disctype'] == 1) {
                if (parseFloat(detail['discvalue'].toFixed(2)) > 0) {
                    inputdisc.value = parseFloat(detail['discvalue'].toFixed(2) * 100);
                    inputdiscamount.value = "0.00";
                    inputdiscamount.readOnly = true
                } else {
                    inputdisc.value = "0.00";
                }
            } else {
                inputdisc.value = "0.00";
                inputdiscamount.readOnly = false
            }

            //inputdisc.setAttribute('required','true');    
            if (parseInt(detail['disctype']) == 0) {
                if (detail['manualdisc'] > 0) {
                    inputdiscamount.value = detail['manualdisc'].toFixed(2);
                    inputdisc.value = "0.00";
                    inputdisc.readOnly = true;
                } else {
                    inputdiscamount.value = "0.00";
                    inputdisc.readOnly = false;
                }
            }


            let buttondisc = document.createElement('button');
            buttondisc.className = 'btn btn-primary btn-sm';
            buttondisc.id = 'button-disc';

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

            let tddisctype = document.createElement("td");
            tddisctype.classname = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
            let disctype = document.createTextNode(parseInt(detail['disctype'].toFixed(2)));

            let tdmanualdisc = document.createElement("td");
            tdmanualdisc.classname = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
            tdmanualdisc.style = 'text-align:right';
            let manualdisc = document.createTextNode(parseFloat(detail['manualdisc']).toFixed(2));


            let tdamount = document.createElement("td");
            tdamount.className = 'border-start border-end border-bottom  text-right px-1 py-1 align-content-center';
            //let amount = document.createTextNode(detail['Amount'])
            //let inputamount = document.createElement("input");
            //inputamount.className = "form-control border-0 text-right font-14";
            //inputamount.type = "text";
            //inputamount.value = (parseFloat(detail['amount']).toFixed(2) - parseFloat(detail['manualdisc']).toFixed(2)).toFixed(2);
            let inputamount = document.createTextNode((parseFloat(detail['amount']).toFixed(2) - parseFloat(detail['manualdisc']).toFixed(2)).toFixed(2));




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

            let buttondelete = document.createElement('button');
            buttondelete.className = 'btn p-1';
            buttondelete.type = 'button'
            buttondelete.id = 'button-remove';

            var icondelete = document.createElement('i');
            icondelete.className = 'bi bi-x';
            icondelete.style = "font-size: 22px;"
            buttondelete.appendChild(icondelete);

            tdbarcode.appendChild(barcode);
            tdname.appendChild(name);
            tddesc.appendChild(desc);
            tdqty.appendChild(inputqty);
            tdunitprice.appendChild(unitprice);
            tddisc.appendChild(inputdisc);
            tddiscamount.appendChild(inputdiscamount)
            tddiscvalue.appendChild(discvalue)
            tddisctype.appendChild(disctype)
            tdmanualdisc.appendChild(manualdisc);
            //tddisc.appendChild(buttondisc);
            tdamount.appendChild(inputamount);
            tddelete.appendChild(buttondelete);

            tr.appendChild(tdbarcode);
            tr.appendChild(tdname);
            tr.appendChild(tddesc);
            tr.appendChild(tdqty);
            tr.appendChild(tdunitprice);
            tr.appendChild(tddisc)
            tr.appendChild(tddiscamount)
            tr.appendChild(tddiscvalue)
            tr.appendChild(tddisctype)
            tr.appendChild(tdmanualdisc)
            tr.appendChild(tdamount);
            tr.appendChild(tddelete)
            tbody.appendChild(tr);
        })


        $('td:nth-child(8),th:nth-child(8)').hide();
        $('td:nth-child(9),th:nth-child(9)').hide();
        $('#input-invoiceno').attr('readonly', true);
        if (trans['transstatus'] == 2) {
            let transpayment = GET_SITranspayment_by_TransID(parseInt(trans['transid']));
            $('#button-confirm').prop('disabled', true);
            $('#button-paymenttype').prop('disabled', true);
            $('#button-additem').prop('disabled', true);
            $('#button-search-customer').prop('disabled', true);
            $('#button-save').prop('disabled', true);
            $('#button-confirm').prop('disabled', true);
            document.getElementById('button-paymenttype').innerText = transpayment['paymenttype'];
            $('#tbody-item tr td input').attr('readonly', true); // Makes all inputs read-only
            $('#tbody-item tr td button').attr('disabled', true); // Makes all inputs read-only
            $('#input-referenceno').attr('readonly', true); // Makes all inputs read-only

        } else {
            $('#button-confirm').prop('disabled', false);
            $('#button-paymenttype').prop('disabled', false);
            $('#button-additem').prop('disabled', false);
            $('#button-search-customer').prop('disabled', false);
            $('#button-save').prop('disabled', false);

            //document.getElementById('button-paymenttype').innerText = transpayment['paymenttype'];
        }
        //  console.log(DecryptValue(trans['customernumber']))
        customer = customer.filter(e => e['CID'].toLowerCase() == trans['customernumber'].toLowerCase());
        
        if (customer.length > 0) {
            $('#input-customer').val(DecryptValue(customer[0]['CustomerName']))
        }

        $("#label-subtotal").text(trans['subtotal'].toFixed(2));
        $("#label-gst").text(trans['taxamount2'].toFixed(2));
        $("#label-total").text(trans['total'].toFixed(2));
        $('#input-scan').val('');
    } else {
        $("#label-subtotal").text('0.00');
        $("#label-gst").text('0.00');
        $("#label-total").text('0.00');
        $('#input-scan').val('');
    }
}

function itemCollection(item) {

    let transdetailArr = [];
    let AllTax = GET_AllTax();

    let categorylist = JSON.parse(GET_AllCategory())
    let itemlist = JSON.parse(GET_AllInventory());
    let inventory = itemlist.filter((e) => e['Barcode'].toLowerCase().trim() == item['barcode'].toLowerCase().trim());
    inventory = inventory[0]
    let category = categorylist.filter((e) => e['CategoryID'] == inventory["CategoryID"])

    let x = 1;
    //console.log(category)
    let taxflag = category[0]['Flag1'].substring(2, category[0]['Flag1'].length)
    for (i = 0; i < 6; i++) {
        //console.log(taxflag.charAt(i))
    }

    let taxinfo = "";
    AllTax.forEach(function (x) {
        let addon = x['addon'];
        let taxontax = x['taxontax'];
        let tax = x['tax'];
        taxinfo = taxinfo + addon + "," + taxontax + "," + tax + ":";
    })


    let transid = 0;
    let transno = 0;
    let transstatus = 4;

    let qty = item['qty'];
    let unitprice = item['price'];
    let actualprice = item['price']
    let taxableamount = 0;

    let amount = parseInt(qty) * parseFloat(unitprice);

    let storeditemcollection = JSON.parse(sessionStorage.getItem('transactioncollection'))

    if (storeditemcollection != null) {

    }

    if (storeditemcollection != null) {
        let trans = storeditemcollection;

        if (parseInt(trans['transid']) > 0) {
            transid = trans['transid'];
        }
        let itemid = 1;
        storeditemcollection['SITransdetailList'].forEach((inventory) => {
            let transdetail = {
                "transid": transid,
                "itemid": itemid,
                "barcode": inventory["barcode"].trim(),
                "name": inventory["name"].trim(),
                "inventorydesc": inventory["inventorydesc"].trim(),
                "stockcode": "",
                "nopriceshift": 0,
                "categorynumber": item['categorynumber'],
                "group1": "",
                "group2": "",
                "group3": "",
                "group4": "",
                "group5": "",
                "itemclass": 0,
                "qty": parseInt(inventory['qty']),
                "unit": "PCS",
                "pricetype": 0,
                "price": parseFloat(inventory['price']),
                "actualprice": parseFloat(inventory['actualprice']),
                "amount": parseFloat(inventory['amount']),
                "shiftmixedflag": 0,
                "quantityshifttype": 0,
                "shiftvalue": 0,
                "odddisc": 0,
                "realprice": 0,
                "quantityfrom": 0,
                "description": "",
                "discqty": 0,
                "psdiscamount": 0,
                "psdiscvalue": 0,
                "actualpsdiscamount": 0,
                "qtyremain": 0,
                "totalsoldqty": 0,
                "totaldiscqty": 0,
                "disctype": parseInt(inventory['disctype']),
                "discvalue": parseFloat(inventory['discvalue']),
                "manualdisc": parseFloat(inventory['manualdisc']),
                "points": 0,
                "checkout": 0,
                "takeaway": 0,
                "memberdisc": 0,
                "salesman": 0,
                "ordertime": 0,
                "printed": 0,
                "bufferprinted": 0,
                "priceid": 0,
                "condimented": 0,
                "kitchenprint": 0,
                "kitchenprintflag": inventory['kitchenflag'],
                "taxamount1": 0,
                "taxamount2": 0,
                "taxamount3": 0,
                "taxamount4": 0,
                "taxamount5": 0,
                "taxamount6": 0,
                "itemstatus": 0,
                "taxableamount": parseFloat(inventory['taxableamount']),
                "taxflag": inventory['taxflag'],
                "taxinfo": inventory['taxinfo'],
                "parentid": 0,
                "printedvoid": 0,
                "voiddate": currentdate,
                "allowdecimalvalue": 0,
                "totaldisc": 0,
                "totalmemberdisc": 0,
                "totalpsdisc": 0,
                "rdpoints": 0,
                "itemscdiscamount": 0,
                "itemscdiscvalue": 0,
                "itemsccovers": 0,
                "itemscrettaxamount": 0,
                "warranty": 0,
                "unitcost": 0,
                "managerid": 0,
                "managername": "",
                "kitchenstatus": 0,
                "firequantity": 0,
                "commission": 0,
                "commissionvalue": 0,
                "kdsitemstatus": 0,
                "kdsdoneqty": 0,
                "kdsitempriority": 0,
                "kdsitemcmpttime": "",
                "mparentid": 0,
                "mchildid": 0,
                "marginrate": 0,
                "siTransdetailCondimentList": []
            }

            transdetailArr.push(transdetail);
            itemid = parseInt(itemid) + 1
        })


        ////new added item
        let transdetail = {
            "transid": transid,
            "itemid": (parseInt(transdetailArr.length) + 1),
            "barcode": inventory["Barcode"].trim(),
            "name": inventory["InventoryName"].trim(),
            "inventorydesc": inventory["Description"].trim(),
            "stockcode": "",
            "nopriceshift": 0,
            "categorynumber": item['categorynumber'],
            "group1": "",
            "group2": "",
            "group3": "",
            "group4": "",
            "group5": "",
            "itemclass": 0,
            "qty": parseInt(qty),
            "unit": "PCS",
            "pricetype": 0,
            "price": parseFloat(unitprice),
            "actualprice": parseFloat(unitprice),
            "amount": parseFloat(amount),
            "shiftmixedflag": 0,
            "quantityshifttype": 0,
            "shiftvalue": 0,
            "odddisc": 0,
            "realprice": 0,
            "quantityfrom": 0,
            "description": "",
            "discqty": 0,
            "psdiscamount": 0,
            "psdiscvalue": 0,
            "actualpsdiscamount": 0,
            "qtyremain": 0,
            "totalsoldqty": 0,
            "totaldiscqty": 0,
            "disctype": parseInt(item['disctype']),
            "discvalue": parseFloat(item['discvalue']),
            "manualdisc": parseFloat(item['manualdisc']),
            "points": 0,
            "checkout": 0,
            "takeaway": 0,
            "memberdisc": 0,
            "salesman": 0,
            "ordertime": 0,
            "printed": 0,
            "bufferprinted": 0,
            "priceid": 0,
            "condimented": 0,
            "kitchenprint": 0,
            "kitchenprintflag": category[0]['Flag2'],
            "taxamount1": 0,
            "taxamount2": 0,
            "taxamount3": 0,
            "taxamount4": 0,
            "taxamount5": 0,
            "taxamount6": 0,
            "itemstatus": 0,
            "taxableamount": parseFloat(taxableamount),
            "taxflag": taxflag,
            "taxinfo": taxinfo,
            "parentid": 0,
            "printedvoid": 0,
            "voiddate": currentdate,
            "allowdecimalvalue": 0,
            "totaldisc": 0,
            "totalmemberdisc": 0,
            "totalpsdisc": 0,
            "rdpoints": 0,
            "itemscdiscamount": 0,
            "itemscdiscvalue": 0,
            "itemsccovers": 0,
            "itemscrettaxamount": 0,
            "warranty": 0,
            "unitcost": 0,
            "managerid": 0,
            "managername": "",
            "kitchenstatus": 0,
            "firequantity": 0,
            "commission": 0,
            "commissionvalue": 0,
            "kdsitemstatus": 0,
            "kdsdoneqty": 0,
            "kdsitempriority": 0,
            "kdsitemcmpttime": "",
            "mparentid": 0,
            "mchildid": 0,
            "marginrate": 0,
            "siTransdetailCondimentList": []
        }

        transdetailArr.push(transdetail);
    } else {

        let transdetail = {
            "transid": transid,
            "itemid": 1,
            "barcode": inventory["Barcode"].trim(),
            "name": inventory["InventoryName"].trim(),
            "inventorydesc": inventory["Description"].trim(),
            "stockcode": "",
            "nopriceshift": 0,
            "categorynumber": item['categorynumber'],
            "group1": "",
            "group2": "",
            "group3": "",
            "group4": "",
            "group5": "",
            "itemclass": 0,
            "qty": parseInt(qty),
            "unit": "PCS",
            "pricetype": 0,
            "price": parseFloat(unitprice).toFixed(4),
            "actualprice": parseFloat(actualprice).toFixed(4),
            "amount": parseFloat(amount).toFixed(4),
            "shiftmixedflag": 0,
            "quantityshifttype": 0,
            "shiftvalue": 0,
            "odddisc": 0,
            "realprice": 0,
            "quantityfrom": 0,
            "description": "",
            "discqty": 0,
            "psdiscamount": 0,
            "psdiscvalue": 0,
            "actualpsdiscamount": 0,
            "qtyremain": 0,
            "totalsoldqty": 0,
            "totaldiscqty": 0,
            "disctype": parseInt(item['disctype']),
            "discvalue": parseFloat(item['discvalue']),
            "manualdisc": parseFloat(item['manualdisc']),
            "points": 0,
            "checkout": 0,
            "takeaway": 0,
            "memberdisc": 0,
            "salesman": 0,
            "ordertime": 0,
            "printed": 0,
            "bufferprinted": 0,
            "priceid": 0,
            "condimented": 0,
            "kitchenprint": 0,
            "kitchenprintflag": category[0]['Flag2'],
            "taxamount1": 0,
            "taxamount2": 0,
            "taxamount3": 0,
            "taxamount4": 0,
            "taxamount5": 0,
            "taxamount6": 0,
            "itemstatus": 0,
            "taxableamount": 0,
            "taxflag": taxflag,
            "taxinfo": taxinfo,
            "parentid": 0,
            "printedvoid": 0,
            "voiddate": currentdate,
            "allowdecimalvalue": 0,
            "totaldisc": 0,
            "totalmemberdisc": 0,
            "totalpsdisc": 0,
            "rdpoints": 0,
            "itemscdiscamount": 0,
            "itemscdiscvalue": 0,
            "itemsccovers": 0,
            "itemscrettaxamount": 0,
            "warranty": 0,
            "unitcost": 0,
            "managerid": 0,
            "managername": "",
            "kitchenstatus": 0,
            "firequantity": 0,
            "commission": 0,
            "commissionvalue": 0,
            "kdsitemstatus": 0,
            "kdsdoneqty": 0,
            "kdsitempriority": 0,
            "kdsitemcmpttime": "",
            "mparentid": 0,
            "mchildid": 0,
            "marginrate": 0,
            "siTransdetailCondimentList": []
        }

        transdetailArr.push(transdetail);
    }

    return transdetailArr;
}

//3
function ProcessTotalProc() {
    let cAmount = 0;
    let cTaxAmount = 0;
    let dAmount = 0;

    let TempAmt1 = 0;
    let TempAmt2 = 0;
    let AccurateTotalAmount = 0;

    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    let trans = storedtransactioncollection;
    //let transpayment = storedtransactioncollection['SITranspayment']
    //let transdetail = storedtransactioncollection['siTransdetailList']
    let transdetail = storedtransactioncollection['SITransdetailList']
    let transid = 0;
    let transno;
    let transstatus = 0;
    let transdate;
    let transtime;
    let businessdate;

    if (parseInt(trans['transid']) > 0) {
        transid = trans['transid'];
        transno = trans['transno'];
        transstatus = trans['transstatus'];
        transdate = trans['transdate'];
        transtime = trans['transtime'];
        businessdate = trans['businessdate'];
    }

    for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
        if (taxCtr == 0) {
            trans['taxamount1'] = 0;
        } else if (taxCtr == 1) {
            trans['taxamount2'] = 0;
        } else if (taxCtr == 2) {
            //dict.oTransList[0].taxAmount3 = 0;
            trans['taxamount3'] = 0;
        } else if (taxCtr == 3) {
            //dict.oTransList[0].taxAmount4 = 0;
            trans['taxamount4'] = 0;
        } else if (taxCtr == 4) {
            //dict.oTransList[0].taxAmount5 = 0;
            trans['taxamount5'] = 0;
        } else if (taxCtr == 5) {
            //dict.oTransList[0].taxAmount6 = 0;
            trans['taxamount6'] = 0;
        }
    }

    if (trans['disctype'] == 1) {
        nDiscflag = true;
    }

    let itemdetail = [];
    trans['subtotal'] = 0;


    transdetail.forEach(function (item) {
        item['transid'] = transid;
        item['memberdisc'] = 0;
        item['totalmemberdisc'] = 0;
        item['psdvalue'] = 0;
        //item['discvalue'] = 0;
        //item['manualdisc'] = 0;
        item['totalamount'] = 0;
        item['totaldisc'] = 0;

        //let item =

        //normal item
        //dAmount = parseFloat(item['amount'])

        //trans['subtotal'] = parseFloat(trans['subtotal']) + parseFloat(dAmount);
        //item tax calculation
        if (item['itemstatus'] != 3) {

            itemdetail.push(CalcItemTax(item))
        } else {
            item['taxableamount'] = item['amount'];
        }

        //0 = normal
        //1 = void
        //2 = return
        //3 = itemtrans
        //4 = exchange

        switch (item['itemstatus']) {
            case 0:
                cAmount = parseFloat(item['amount']) - (parseFloat(item['manualdisc']) + parseFloat(item['memberdisc']) + parseFloat(item['psdiscamount']) + parseFloat(item['itemscdiscamount']) + parseFloat(item['itemscrettaxamount']));
                break;
            case 1:
                cAmount = 0;
            case 2:
                cAmount = Math.abs(parseFloat(item['amount'])) - (Math.abs(parseFloat(item['manualdisc'])) + Math.abs(parseFloat(item['memberdisc'])) + Math.abs(parseFloat(item['psdiscamount'])) + Math.abs(parseFloat(item['itemscdiscamount'])) + Math.abs(parseFloat(item['itemscrettaxamount'])));
                if (item['itemclass'] == 5) {
                    cAmount = cAmount;
                } else {
                    cAmount = -1 * parseFloat(cAmount);
                    item['manualdisc'] = -1 * (Math.abs(item['manualdisc']))
                    item['totalmemberdisc'] = -1 * (Math.abs(item['totalmemberdisc']))
                    item['totaldisc'] = -1 * (Math.abs(item['totaldisc']))
                    item['actualpsdiscamount'] = -1 * (Math.abs(item['actualpsdiscamount']))
                    item['itemscdiscamount'] = -1 * (Math.abs(item['itemscdiscamount']))
                    item['itemscrettaxamount'] = -1 * (Math.abs(item['itemscrettaxamount']))
                }
                break;
            case 3:
                cAmount = parseFloat(item['amount'])
                break;
            case 4:
                cAmount = cAmount = Math.abs(parseFloat(item['amount'])) - (Math.abs(parseFloat(item['manualdisc'])) + Math.abs(parseFloat(item['memberdisc'])) + Math.abs(parseFloat(item['psdiscamount'])) + Math.abs(parseFloat(item['itemscdiscamount'])) + Math.abs(parseFloat(item['itemscrettaxamount'])));
                if (item['itemclass'] == 5) {
                    cAmount = cAmount;
                } else {
                    cAmount = -1 * parseFloat(cAmount)
                }
                break;
            default:
                cAmount = 0;
        }

        //console.log(cAmount)
        trans['subtotal'] = parseFloat(trans['subtotal']) + Math.abs(parseFloat(cAmount));

        if (item['itemclass'] == 5) {
            trans['vouchertotal'] = parseFloat(trans['vouchertotal']) + Math.abs(parseFloat(cAmount));
        }
    })


    let tax1 = 0;
    let tax2 = 0;
    let tax3 = 0;
    let tax4 = 0;
    let tax5 = 0;
    let tax6 = 0;
    let taxableamount = 0;

    itemdetail.forEach((item) => {
        //console.log(item)
        tax1 = parseFloat(tax1) + parseFloat(item['taxamount1']);
        tax2 = parseFloat(tax2) + parseFloat(item['taxamount2']);
        tax3 = parseFloat(tax3) + parseFloat(item['taxamount3']);
        tax4 = parseFloat(tax4) + parseFloat(item['taxamount4']);
        tax5 = parseFloat(tax5) + parseFloat(item['taxamount5']);
        tax6 = parseFloat(tax6) + parseFloat(item['taxamount6']);


    });


    //Discount's
    let discountableamount = 0;
    discountableamount = GetDiscountableAmount();

    switch (trans['disctype']) {
        case 0:
            if (parseFloat(trans['discamount']) > Math.abs(parseFloat(discountableamount))) {

            } else if (parseFloat(trans['discamount'] < 0)) {
                trans['discvalue'] = Math.abs(parseFloat(trans['discamount']) / parseFloat(discountableamount));
            } else if (parseFloat(trans['discamount'] > 0 && parseFloat(discountableamount) < 0)) {
                trans['discvalue'] = Math.abs(parseFloat(trans['discamount']) / parseFloat(discountableamount));
                trans['discamount'] = -1 * parseFloat(trans['discamount']);
            } else if (parseFloat(discountableamount) > 0) {
                trans['discvalue'] = parseFloat(trans['discamount']) / parseFloat(discountableamount);
            } else {
                trans['discvalue'] = 0;
                trans['discamount'] = 0;
            }
            break;
        case 1:
            break;
        default:
    }



    discountableamount = parseFloat(discountableamount) - trans['discamount'];


    trans['total'] = 0;
    for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
        if (taxCtr == 0) {
            trans['taxamount1'] = 0;
        } else if (taxCtr == 1) {
            trans['taxamount2'] = 0;
        } else if (taxCtr == 2) {
            //dict.oTransList[0].taxAmount3 = 0;
            trans['taxamount3'] = 0;
        } else if (taxCtr == 3) {
            //dict.oTransList[0].taxAmount4 = 0;
            trans['taxamount4'] = 0;
        } else if (taxCtr == 4) {
            //dict.oTransList[0].taxAmount5 = 0;
            trans['taxamount5'] = 0;
        } else if (taxCtr == 5) {
            //dict.oTransList[0].taxAmount6 = 0;
            trans['taxamount6'] = 0;
        }
    }

    let TotalDiscDiff = 0;
    let TotalMemberDiscDiff = 0;
    let TotalPSDiscDiff = 0;
    let ItemTaxableAmt = 0;
    let TotalTaxableAmt = 0;
    let ItemTaxAmt1 = 0;
    let ItemTaxAmt2 = 0;
    let ItemTaxAmt3 = 0;
    let ItemTaxAmt4 = 0;
    let ItemTaxAmt5 = 0;
    let ItemTaxAmt6 = 0;

    //trans
    let subtotal = 0;
    let total = 0;

    //transdetail
    let itemtaxamount1 = 0;
    let itemtaxamount2 = 0;
    let itemtaxamount3 = 0;
    let itemtaxamount4 = 0;
    let itemtaxamount5 = 0;
    let itemtaxamount6 = 0;

    transdetail.forEach(function (item) {
        if (item['itemclass'] != 5) {
            // no discount 
            let tempdiscount = 0
            tempdiscount = GetDiscountableAmount(item);

            //item['totaldisc'] = parseFloat(tempdiscount) * 
            for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                if (TTaxType == "0" || TTaxType == "2" || TTaxType == "4") {
                    if (NNFDforTotal == true && nDiscFlag == true) {
                        if (Math.abs(parseFloat(item['actualpsdiscamount']) > 0)) {
                            if (taxCtr == 0) {
                                item['taxamount1'] = item['taxamount1'];
                            } else if (taxCtr == 1) {
                                item['taxamount2'] = item['taxamount2'];
                            } else if (taxCtr == 2) {
                                item['taxamount3'] = item['taxamount3'];
                            } else if (taxCtr == 3) {
                                item['taxamount4'] = item['taxamount4'];
                            } else if (taxCtr == 4) {
                                item['taxamount5'] = item['taxamount5'];
                            } else if (taxCtr == 5) {
                                item['taxamount6'] = item['taxamount6'];
                            }
                        } else {
                            if (taxCtr == 0) {
                                item['taxamount1'] = parseFloat(item['taxamount1']) * (1 - parseFloat(trans['discvalue']));
                            } else if (taxCtr == 1) {
                                item['taxamount2'] = parseFloat(item['taxamount2']) * (1 - parseFloat(trans['discvalue']));;
                            } else if (taxCtr == 2) {
                                item['taxamount3'] = parseFloat(item['taxamount3']) * (1 - parseFloat(trans['discvalue']));;
                            } else if (taxCtr == 3) {
                                item['taxamount4'] = parseFloat(item['taxamount4']) * (1 - parseFloat(trans['discvalue']));;
                            } else if (taxCtr == 4) {
                                item['taxamount5'] = parseFloat(item['taxamount5']) * (1 - parseFloat(trans['discvalue']));;
                            } else if (taxCtr == 5) {
                                item['taxamount6'] = parseFloat(item['taxamount6']) * (1 - parseFloat(trans['discvalue']));;
                            }
                        }
                    } else {
                        if (NNFDforDiscI == true) {

                        } else {
                            if (taxCtr == 0) {
                                item['taxamount1'] = parseFloat(item['taxamount1']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            } else if (taxCtr == 1) {
                                item['taxamount2'] = parseFloat(item['taxamount2']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            } else if (taxCtr == 2) {
                                item['taxamount3'] = parseFloat(item['taxamount3']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            } else if (taxCtr == 3) {
                                item['taxamount4'] = parseFloat(item['taxamount4']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            } else if (taxCtr == 4) {
                                item['taxamount5'] = parseFloat(item['taxamount5']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            } else if (taxCtr == 5) {
                                item['taxamount6'] = parseFloat(item['taxamount6']) * (1 - parseFloat(trans['discvalue'])) * (1 - parseFloat(trans['memeberdiscvalue'])) * (1 - parseFloat(trans['asdiscvalue'])) * (1 - parseFloat(trans['birthdaydiscvalue']));
                            }
                        }

                        if (taxCtr == 0) {

                        }

                        if (taxCtr == 1) {

                        }

                        if (TTaxType == "2") {
                            if (taxCtr == 0) {

                            }
                        }
                    }
                }
            }


            trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxableamount']);
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(item['taxableamount']);


            for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                if (taxCtr == 0) {
                    trans['taxamount1'] = parseFloat(trans['taxamount1']) + parseFloat(item['taxamount1']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount1']);
                } else if (taxCtr == 1) {
                    trans['taxamount2'] = parseFloat(trans['taxamount2']) + parseFloat(item['taxamount2']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount2']);
                } else if (taxCtr == 2) {
                    trans['taxamount3'] = parseFloat(trans['taxamount3']) + parseFloat(item['taxamount3']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount3']);
                } else if (taxCtr == 3) {
                    trans['taxamount4'] = parseFloat(trans['taxamount4']) + parseFloat(item['taxamount4']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount4']);
                } else if (taxCtr == 4) {
                    trans['taxamount5'] = parseFloat(trans['taxamount5']) + parseFloat(item['taxamount5']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount5']);
                } else if (taxCtr == 5) {
                    trans['taxamount6'] = parseFloat(trans['taxamount6']) + parseFloat(item['taxamount6']);
                    trans['total'] = parseFloat(trans['total']) + parseFloat(item['taxamount6']);
                }
            }

            TempAmt1 = parseFloat(item['taxableamount']);
            for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                if (taxCtr == 0) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount1']);
                } else if (taxCtr == 1) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount2']);
                } else if (taxCtr == 2) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount3']);
                } else if (taxCtr == 3) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount4']);
                } else if (taxCtr == 4) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount5']);
                } else if (taxCtr == 5) {
                    TempAmt1 = parseFloat(TempAmt1) + parseFloat(item['taxamount16']);
                }
            }

            item['taxablemaount'] = parseFloat(item['taxableamount'].toFixed(4))

            TempAmt2 = parseFloat(item['taxablemaount']);
            for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                if (taxCtr == 0) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount1']);
                } else if (taxCtr == 1) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount2']);
                } else if (taxCtr == 2) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount3']);
                } else if (taxCtr == 3) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount4']);
                } else if (taxCtr == 4) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount5']);
                } else if (taxCtr == 5) {
                    TempAmt2 = parseFloat(TempAmt2) + parseFloat(item['taxamount16']);
                }
            }

            if ((parseFloat(TempAmt1) - parseFloat(TempAmt2)) != 0) {
                for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                    if (parseFloat(item['taxamount1']) > (parseFloat(TempAmt2) - parseFloat(TempAmt1))) {
                        item['taxamount1'] = parseFloat(item['taxamount1']) + (parseFloat(TempAmt1) - parseFloat(TempAmt2));
                        return;
                    }
                }
            }

            for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
                if (taxCtr == 0) {
                    ItemTaxAmt1 = parseFloat(ItemTaxAmt1) + parseFloat(item['taxamount1']);
                } else if (taxCtr == 1) {
                    ItemTaxAmt2 = parseFloat(ItemTaxAmt2) + parseFloat(item['taxamount2']);
                } else if (taxCtr == 2) {
                    ItemTaxAmt3 = parseFloat(ItemTaxAmt3) + parseFloat(item['taxamount3']);
                } else if (taxCtr == 3) {
                    ItemTaxAmt4 = parseFloat(ItemTaxAmt4) + parseFloat(item['taxamount4']);
                } else if (taxCtr == 4) {
                    ItemTaxAmt5 = parseFloat(ItemTaxAmt5) + parseFloat(item['taxamount5']);
                } else if (taxCtr == 5) {
                    ItemTaxAmt6 = parseFloat(ItemTaxAmt6) + parseFloat(item['taxamount6']);
                }
            }

            ItemTaxableAmt = parseFloat(ItemTaxableAmt) + parseFloat(item['taxableamount'])
        }
    })

    for (let taxCtr = 0; taxCtr < 6; taxCtr++) {
        if (taxCtr == 0) {

            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount1']);
        } else if (taxCtr == 1) {
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount2']);
        } else if (taxCtr == 2) {
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount3']);
        } else if (taxCtr == 3) {
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount4']);
        } else if (taxCtr == 4) {
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount5']);
        } else if (taxCtr == 5) {
            TotalTaxableAmt = parseFloat(TotalTaxableAmt) + parseFloat(trans['taxamount6']);
        }

    }

    AccurateTotalAmount = parseFloat(trans['total']);
    trans['total'] = TotalTaxableAmt;

    //let trans = trans['transid']
    //if(trans == )

    let transaction = {
        "SITransdetailList": itemdetail,
        //"SITranspayment": {
        //    "paymentid": transpayment['paymentid'],
        //    "transid": transid,
        //    "paydate": transpayment['paydate'],
        //    "isdeposit": 0,
        //    "paymenttype": transpayment['paymenttype'],
        //    "paymentamount": transpayment['paymentamount'],
        //    "paycurrency": "",
        //    "rate": 0,
        //    "realpayment": 0,
        //    "changes": 0,
        //    "checkout": 0,
        //    "paytime": 0,
        //    "paid": 0,
        //    "businessdate": currentdate,
        //    "termid": 0,
        //    "cardnumber": "",
        //    "cardname": "",
        //    "merchantid": "",
        //    "terminalid": "",
        //    "refnumber": "",
        //    "netscardno": "",
        //    "netstransno": "",
        //    "cashcardbalance": 0,
        //    "netsbatchno": "",
        //    "changecurrency": "",
        //    "signature": "",
        //    "paymentcaption": ""
        //},
        "transid": transid,
        "transno": transno,
        "termid": 0,
        "transdate": transdate,
        "lastdate": currentdate,
        "transtime": transtime,
        "customernumber": trans['customernumber'],
        "cashierid": 0,
        "cashiername": "",
        "salespersonid": 0,
        "salespersonname": "",
        "hassalesman": 0,
        "subtotal": trans['subtotal'],
        "taxamount1": trans['taxamount1'],
        "taxamount2": trans['taxamount2'],
        "taxamount3": trans['taxamount3'],
        "taxamount4": trans['taxamount4'],
        "taxamount5": trans['taxamount5'],
        "taxamount6": trans['taxamount6'],
        "total": trans['total'],
        "disctype": 0,
        "discamount": 0,
        "discvalue": 0,
        "points": 0,
        "transstatus": transstatus,
        "manualkey": "",
        "checkout": 0,
        "round": 0,
        "memberdiscamount": 0,
        "memberdiscvalue": 0,
        "birthdaydiscamount": 0,
        "birthdaydiscvalue": 0,
        "scdiscamount": 0,
        "scdiscvalue": 0,
        "sccovers": 0,
        "screttaxamount": 0,
        "asdiscamount": 0,
        "asdiscvalue": 0,
        "printed": 0,
        "covers": 0,
        "notes": "",
        "paidtotal": 0,
        "timestampid": 0,
        "businessdate": businessdate,
        "vouchertotal": 0,
        "rdpointstotal": 0,
        "rdflag": 0,
        "rdpointsamount": 0,
        "rdpointvalue": 0,
        "tablemenuid": "",
        "delivercustno": "",
        "pddiscamount": 0,
        "pddiscvalue": 0,
        "pdcovers": 0,
        "gerettaxamount": 0,
        "gecovers": 0,
        "managerid": 0,
        "managername": "",
        "sendflag": 0,
        "edittransid": 0,
        "orderid": 0,
        "kioskorderno": "",
        "splitbill": 0,
        "duedays": 0,
        "duetype": "",
        "previouspoints": 0,
        "kdsorderstatus": 0,
        "kdspriority": 0,
        "kdscmpttime": currentdate,
        "pdrettaxamount": 0,
        "doaddress": "",
        "printhold": 0,
        "advcustomerid": "",
        "advcountrycode": "",
        "advsvbal": 0,
        "advvbal": 0,
        "advlpoints": 0,
        "advllpoints": 0,
        "advlpid": "",
        "advlprid": "",
        "advskurid": "",
        "advcashback": 0,
        "advlcashback": 0,
        "advcbid": "",
        "advcbrid": "",
        "stbcpprev": 0,
        "stbcpbal": 0,
        "kiosktakeaway": 0,
        "advvourid": "",
        "kdsprinttimes": 0,
        "stbcporderno": "",
        "depprevbal": 0,
        "depbal": 0,
        "webtransid": "",
        "issync": 0,
        "navsync": 0,
        "rsgid": "",
        "rsgvoucher": "",
        "rsgvalue": 0,
        "rsgforfeit": 0,
        "rsgstatus": 0
    }
    //console.log(JSON.parse(transaction))
    sessionStorage.setItem('transactioncollection', JSON.stringify(transaction));
}

function CalcItemTax(item) {

    let AllTax = GET_AllTax();
    let totalTax = 0;
    let totalIncTax = 0;
    let cTaxableAmount = 0;
    let cAmount = 0;
    let tmpAmount = 0;

    let dTax = [];
    let staxflag = [];
    let tTaxType = "0";
    let iStart = 0;



    for (let iCtr = 0; iCtr < 6; iCtr++) {
        iStart = 6 - (iCtr + 1)
        staxflag.push(item['taxflag'].substring(iStart, iStart + 1))
    }

    if (item['itemstatus'] != 2 && item['itemstatus'] != 4) {
        tmpAmount = parseFloat(item['amount']);
        cAmount = parseFloat(item['amount']) - (parseFloat(item['manualdisc']) + parseFloat(item['memberdisc']) + parseFloat(item['actualpsdiscamount']));

    } else {
        if (item['itemstatus'] != 5) {
            tmpAmount = -1 * parseFloat(item['amount']);
            cAmount = parseFloat(item['amount']) - (parseFloat(item['manualdisc']) + parseFloat(item['memberdisc']) + parseFloat(item['actualpsdiscamount']));
            cAmount = -1 * cAmount;
        } else {
            tmpAmount = parseFloat(item['amount'])
            cAmount = parseFloat(item['amount']) - (parseFloat(item['manualdisc']) + parseFloat(item['memberdisc']) + parseFloat(item['actualpsdiscamount']));
            cAmount = cAmount;
        }
    }

    totalTax = 0;
    totalIncTax = 0;
    //console.log(AllTax)
    for (let ictr = 0; ictr < 6; ictr++) {
        let oTax = AllTax[ictr]
        if (staxflag[ictr] == "1") {
            if (ictr == 0) {
                dTax.push(oTax['tax'].toString());
            } else {
                //console.log(oTax['tax'].toString())
                if (oTax['taxontax'] == 1) {
                    dTax.push((1 + totTax) * parseFloat(oTax['tax'].trim()));
                } else {
                    // console.log(oTax['tax'].toString())
                    dTax.push(oTax['tax'].toString());
                }
            }
            totalTax = parseFloat(totalTax) + parseFloat(dTax[ictr]);

            if (oTax['addon'] == 0) {
                totalIncTax = totalIncTax + parseFloat(dTax[ictr])
            }
        } else {
            dTax.push(oTax['tax']);
        }
    }

    cTaxableAmount = cAmount / (1 + totalIncTax);

    item['taxableamount'] = cTaxableAmount;

    for (let ictr = 0; ictr < 6; ictr++) {
        let oTax = AllTax[ictr]

        if (staxflag[ictr] == "1") {

            if (tTaxType == "0" || tTaxType == "2") {

                if (ictr == 0) {

                    item['taxamount1'] = parseFloat(cTaxableAmount) * parseFloat(dTax[ictr])

                } else if (ictr == 1) {

                    item['taxamount2'] = parseFloat(cTaxableAmount) * parseFloat(dTax[ictr])

                } else if (ictr == 2) {
                    item['taxamount3'] = cTaxableAmount * parseFloat(dTax[ictr])
                } else if (ictr == 3) {
                    item['taxamount4'] = cTaxableAmount * parseFloat(dTax[ictr])
                } else if (ictr == 4) {
                    item['taxamount5'] = cTaxableAmount * parseFloat(dTax[ictr])
                } else if (ictr == 5) {
                    item['taxamount6'] = cTaxableAmount * parseFloat(dTax[ictr])
                }
            } else if (tTaxType == "1") {
                if (ictr == 0) {
                    item['taxamount1'] = tmpAmount * parseFloat(dTax[ictr])
                } else if (ictr == 1) {
                    item['taxamount2'] = tmpAmount * parseFloat(dTax[ictr])
                } else if (ictr == 2) {
                    item['taxamount3'] = tmpAmount * parseFloat(dTax[ictr])
                } else if (ictr == 3) {
                    item['taxamount4'] = tmpAmount * parseFloat(dTax[ictr])
                } else if (ictr == 4) {
                    item['taxamount5'] = tmpAmount * parseFloat(dTax[ictr])
                } else if (ictr == 5) {
                    item['taxamount6'] = tmpAmount * parseFloat(dTax[ictr])
                }
            } else {
                if (ictr == 0) {
                    item['taxamount1'] = 0;
                } else if (ictr == 1) {
                    item['taxamount1'] = 0;
                } else if (ictr == 2) {
                    item['taxamount1'] = 0;
                } else if (ictr == 3) {
                    item['taxamount1'] = 0;
                } else if (ictr == 4) {
                    item['taxamount1'] = 0;
                } else if (ictr == 5) {
                    item['taxamount1'] = 0;
                }
            }
        }
    }

    //console.log(item['taxamount2'].toFixed(4))

    let transdetail = {
        "transid": item['transid'],
        "itemid": item['itemid'],
        "barcode": item['barcode'],
        "name": item['name'],
        "inventorydesc": item['inventorydesc'],
        "stockcode": "",
        "nopriceshift": 0,
        "categorynumber": item['categorynumber'],
        "group1": "",
        "group2": "",
        "group3": "",
        "group4": "",
        "group5": "",
        "itemclass": 0,
        "qty": item['qty'],
        "unit": "PCS",
        "pricetype": 0,
        "price": item['price'],
        "actualprice": item['actualprice'],
        "amount": item['amount'],
        "shiftmixedflag": 0,
        "quantityshifttype": 0,
        "shiftvalue": 0,
        "odddisc": 0,
        "realprice": 0,
        "quantityfrom": 0,
        "description": "",
        "discqty": 0,
        "psdiscamount": 0,
        "psdiscvalue": 0,
        "actualpsdiscamount": 0,
        "qtyremain": 0,
        "totalsoldqty": 0,
        "totaldiscqty": 0,
        "disctype": item['disctype'],
        "discvalue": item['discvalue'],
        "manualdisc": item['manualdisc'],
        "points": 0,
        "checkout": 0,
        "takeaway": 0,
        "memberdisc": 0,
        "salesman": 0,
        "ordertime": 0,
        "printed": 0,
        "bufferprinted": 0,
        "priceid": 0,
        "condimented": 0,
        "kitchenprint": 0,
        "kitchenprintflag": item['Flag2'],
        "taxamount1": parseFloat(item['taxamount1'].toFixed(4)),
        "taxamount2": parseFloat(item['taxamount2'].toFixed(4)),
        "taxamount3": parseFloat(item['taxamount3'].toFixed(4)),
        "taxamount4": parseFloat(item['taxamount4'].toFixed(4)),
        "taxamount5": parseFloat(item['taxamount5'].toFixed(4)),
        "taxamount6": parseFloat(item['taxamount6'].toFixed(4)),
        "itemstatus": parseInt(item['itemstatus']),
        "taxableamount": parseFloat(item['taxableamount'].toFixed(4)),
        "taxflag": item['taxflag'],
        "taxinfo": item['taxinfo'],
        "parentid": 0,
        "printedvoid": 0,
        "voiddate": item['voiddate'],
        "allowdecimalvalue": 0,
        "totaldisc": 0,
        "totalmemberdisc": 0,
        "totalpsdisc": 0,
        "rdpoints": 0,
        "itemscdiscamount": 0,
        "itemscdiscvalue": 0,
        "itemsccovers": 0,
        "itemscrettaxamount": 0,
        "warranty": 0,
        "unitcost": 0,
        "managerid": 0,
        "managername": "",
        "kitchenstatus": 0,
        "firequantity": 0,
        "commission": 0,
        "commissionvalue": 0,
        "kdsitemstatus": 0,
        "kdsdoneqty": 0,
        "kdsitempriority": 0,
        "kdsitemcmpttime": "",
        "mparentid": 0,
        "mchildid": 0,
        "marginrate": 0,
        "siTransdetailCondimentList": []
    }

    return transdetail;

}

function POST_DATA(transstatus) {
    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    let transid = 0;
    let transno;
    let paymentid = 0;
    let result;
    if (parseInt(storedtransactioncollection['transid']) == 0) {
        transid = parseInt(GET_LASTSITrans()) + 1;
        //paymentid = parseInt(GET_LASTSITranspaymentID()) + 1;
    } else {
        DELETE_SITransbyTransID(parseInt(storedtransactioncollection['transid']));
        DELETE_SITransdetailbyTransID(parseInt(storedtransactioncollection['transid']));
        //DELETE_SITranspaymentbyTransID(parseInt(storedtransactioncollection['transid']))

        transid = parseInt(storedtransactioncollection['transid']);
        //transno = storedtransactioncollection['transno']
        //paymentid = parseInt(storedtransactioncollection['transid']);
    }

    switch (transstatus) {
        case 2:
            //sitranspayment
            //storedtransactioncollection['SITranspayment']['paymentid'] = paymentid;
            //storedtransactioncollection['SITranspayment']['transid'] = transid;
            //storedtransactioncollection['SITranspayment']['paymenttype'] = document.getElementById('button-paymenttype').innerText.trim();            
            paymentid = parseInt(GET_LASTSITranspaymentID()) + 1

            let paymenttype = document.getElementById('button-paymenttype').innerText.trim();
            let currentdatetime = getDateTime();
            let paymentamount = storedtransactioncollection['total'];
            let sitranspayment = {
                "paymentid": paymentid,
                "transid": transid,
                "paydate": currentdatetime,
                "isdeposit": 0,
                "paymenttype": paymenttype,
                "paymentamount": paymentamount,
                "paycurrency": "SGD",
                "rate": 0,
                "realpayment": paymentamount,
                "changes": 0,
                "checkout": 0,
                "paytime": 0,
                "paid": 0,
                "businessdate": currentdatetime,
                "termid": 0,
                "cardnumber": "",
                "cardname": "",
                "merchantid": "",
                "terminalid": "",
                "refnumber": "",
                "netscardno": "",
                "netstransno": "",
                "cashcardbalance": 0,
                "netsbatchno": "",
                "changecurrency": "",
                "signature": "",
                "paymentcaption": ""
            }

            if (POST_SITranspayment(sitranspayment) == false) {
                console.log("error")
                return;
            };
            break;
        case 3:

            break;
        default:
    }

    storedtransactioncollection['SITransdetailList'].forEach((item) => {
        item['transid'] = transid;

    })


    //assign transid trans
    storedtransactioncollection['transno'] = transno;
    storedtransactioncollection['transid'] = transid;
    storedtransactioncollection['transno'] = $('#input-invoiceno').val().trim();
    storedtransactioncollection['transstatus'] = transstatus;

    //transpayment
    //storedtransactioncollection['SITranspayment']['paymentid'] = paymentid;
    //storedtransactioncollection['SITranspayment']['transid'] = transid;


    //storedtransactioncollection['SITranspayment']['paymentamount'] = storedtransactioncollection['total']

    //console.log(storedtransactioncollection)
    result = POST_SITransaction(storedtransactioncollection);

    return result;
}

function PUT_DATA() {
    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    let trans = storedtransactioncollection;
    let data = {
        "transid": trans['transid'],
        "transno": trans['transno'],
        "termid": 0,
        "transdate": trans['transdate'],
        "lastdate": trans['lastdate'],
        "transtime": trans['transtime'],
        "customernumber": trans['customernumber'],
        "cashierid": 0,
        "cashiername": "",
        "salespersonid": 0,
        "salespersonname": "",
        "hassalesman": 0,
        "subtotal": trans['subtotal'],
        "taxamount1": trans['taxamount1'],
        "taxamount2": trans['taxamount2'],
        "taxamount3": trans['taxamount3'],
        "taxamount4": trans['taxamount4'],
        "taxamount5": trans['taxamount5'],
        "taxamount6": trans['taxamount6'],
        "total": trans['total'],
        "disctype": trans['disctype'],
        "discamount": trans['discamount'],
        "discvalue": trans['discvalue'],
        "points": 0,
        "transstatus": trans['transstatus'],
        "manualkey": "",
        "checkout": 0,
        "round": 0,
        "memberdiscamount": 0,
        "memberdiscvalue": 0,
        "birthdaydiscamount": 0,
        "birthdaydiscvalue": 0,
        "scdiscamount": 0,
        "scdiscvalue": 0,
        "sccovers": 0,
        "screttaxamount": 0,
        "asdiscamount": 0,
        "asdiscvalue": 0,
        "printed": 0,
        "covers": 0,
        "notes": "",
        "paidtotal": 0,
        "timestampid": 0,
        "businessdate": trans['businessdate'],
        "vouchertotal": 0,
        "rdpointstotal": 0,
        "rdflag": 0,
        "rdpointsamount": 0,
        "rdpointvalue": 0,
        "tablemenuid": "",
        "delivercustno": "",
        "pddiscamount": 0,
        "pddiscvalue": 0,
        "pdcovers": 0,
        "gerettaxamount": 0,
        "gecovers": 0,
        "managerid": 0,
        "managername": "",
        "sendflag": 0,
        "edittransid": 0,
        "orderid": 0,
        "kioskorderno": "",
        "splitbill": 0,
        "duedays": 0,
        "duetype": "",
        "previouspoints": 0,
        "kdsorderstatus": 0,
        "kdspriority": 0,
        "kdscmpttime": trans['kdscmpttime'],
        "pdrettaxamount": 0,
        "doaddress": "",
        "printhold": 0,
        "advcustomerid": "",
        "advcountrycode": "",
        "advsvbal": 0,
        "advvbal": 0,
        "advlpoints": 0,
        "advllpoints": 0,
        "advlpid": "",
        "advlprid": "",
        "advskurid": "",
        "advcashback": 0,
        "advlcashback": 0,
        "advcbid": "",
        "advcbrid": "",
        "stbcpprev": 0,
        "stbcpbal": 0,
        "kiosktakeaway": 0,
        "advvourid": "",
        "kdsprinttimes": 0,
        "stbcporderno": "",
        "depprevbal": 0,
        "depbal": 0,
        "webtransid": "",
        "issync": 0,
        "navsync": 0,
        "rsgid": "",
        "rsgvoucher": "",
        "rsgvalue": 0,
        "rsgforfeit": 0,
        "rsgstatus": 0
    }

    return PUT_SITrans( data);
}

function GetDiscountableAmount() {
    let discountableamount = 0;
    let ctmpAmt = 0;
    let iCtr = 0;
    let taxCtr = 0;
    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    let trans = storedtransactioncollection;
    let transdetail = storedtransactioncollection['SITransdetailList'];

    //console.log(transdetail)

    //0 = normal
    //1 = void
    //2 = return
    //3 = itemtrans
    //4 = exchange
    sTaxTypeIdentifier = 2;
    transdetail.forEach(function (item) {
        if (item['itemclass'] == 3) {
            return;
        }

        if (item['itemclass'] != 5 && item['nopriceshift'] == 0 && item['itemstatus'] != 1) {
            if (nDiscflag == true && NNFDforTotal == true) {

            } else {

                //membercart is nothing
                if (trans['disctype'] == 0) {
                    switch (sTaxTypeIdentifier) {
                        case 0:
                            ctmpAmt = Math.abs(parseFloat(item['taxableamount'])) + Math.abs(parseFloat(item['taxamount1'])) + Math.abs(parseFloat(item['taxamount2'])) + Math.abs(parseFloat(item['taxamount3'])) + Math.abs(parseFloat(item['taxamount4'])) + Math.abs(parseFloat(item['taxamount5'])) + Math.abs(parseFloat(item['taxamount6']));
                            break;
                        case 1:
                            ctmpAmt = Math.abs(parseFloat(item['taxableamount'])) + Math.abs(parseFloat(item['taxamount1']))
                            break;
                        case 2:
                        case 4:
                            ctmpAmt = Math.abs(parseFloat(item['taxableamount']))
                            break;
                        case 3:
                            ctmpAmt = Math.abs(parseFloat(item['taxableamount'])) + Math.abs(item['taxamount2'])
                            break;
                        default:
                            ctmpAmt = Math.abs(parseFloat(item['taxableamount'])) + Math.abs(parseFloat(item['taxamount1'])) + Math.abs(parseFloat(item['taxamount2'])) + Math.abs(parseFloat(item['taxamount3'])) + Math.abs(parseFloat(item['taxamount4'])) + Math.abs(parseFloat(item['taxamount5'])) + Math.abs(parseFloat(item['taxamount6']));
                    }

                    if (item['itemstatus'] == 2 || item['itemstatus'] == 4) {
                        ctmpAmt = -1 * parseFloat(ctmpAmt);
                    }

                } else {
                    // ctmpAmt = Math.abs(parseFloat(item['amount'])) - (Math.abs(parseFloat(item['manualdisc'])) + Math.abs(parseFloat(item['memberdisc'])) + Math.parseFloat(item['actualpsdiscamount']))
                }

            }
            discountableamount = parseFloat(discountableamount) + ctmpAmt;
        }

    });
    return discountableamount;
}

function POST_SITransaction(json) {

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

    return returnvalue;
}

function POST_SITranspayment(json) {

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

    return returnvalue;
}

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

    return returnvalue;
}

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

    return returnvalue;
}

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

    return returnvalue;
}

function GET_AllCustomer() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_AllCustomer",
        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) {
            responseVal = JSON.parse(result.d);
        }
    });
    return responseVal;
}

function Load_Customers(customers) {
    let tbody = document.getElementById('table-body-customer');
    $.each(customers, function (key, detail) {
        let tr = document.createElement('tr');

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

        let divchkcustomer = document.createElement('div');
        divchkcustomer.className = 'checkbox text-center';

        let labelchkcustomer = document.createElement('label')
        labelchkcustomer.className = 'form-checkbox form-icon';
        labelchkcustomer.setAttribute('for', 's_facs')

        let inputchkcustomer = document.createElement('input');
        inputchkcustomer.id = 's_facs';
        inputchkcustomer.className = 'sev_check';
        inputchkcustomer.type = 'checkbox';

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

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

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

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

        tdchkcustomer.appendChild(divchkcustomer);
        divchkcustomer.appendChild(labelchkcustomer);
        labelchkcustomer.appendChild(inputchkcustomer);

        tdid.appendChild(id);
        tdcustomername.appendChild(customername);
        tdaddress.appendChild(address);
        tdcontact.append(contact);

        tr.appendChild(tdchkcustomer);
        tr.appendChild(tdid);
        tr.appendChild(tdcustomername);
        tr.appendChild(tdaddress);
        tr.appendChild(tdcontact);

        tbody.appendChild(tr);


    });
}

function GET_LASTSITrans() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_LASTSITrans",
        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) {
            if (JSON.parse(result.d) == null) {
                responseVal = 0;
            } else {
                responseVal = JSON.parse(result.d)['transid']
            }

        }
    });
    return responseVal;
}

function GET_LASTSITransNo() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_LASTSITrans",
        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) {
            if (JSON.parse(result.d) == null) {
                responseVal = 0;
            } else {
                responseVal = JSON.parse(result.d)['transno']
            }

        }
    });
    return responseVal;
}

function GET_LASTSITranspaymentID() {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/GET_LASTSITranspayment",
        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) {
            if (JSON.parse(result.d) == null) {
                responseVal = 0;
            } else {
                responseVal = JSON.parse(result.d)['paymentid']
            }

        }
    });
    return responseVal;
}

function GET_SITranspayment_by_TransID(transid) {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoiceList.aspx/GET_SITranspayment_by_TranID",
        async: false,
        data: "{'transid':" + transid + "}",
        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) {
            responseVal = JSON.parse(result.d);

            //if (JSON.parse(result.d) == null) {
            //    responseVal = 0;
            //} else {
            //    //responseVal = JSON.parse(result.d)['paymenttype']
            //    responseVal = JSON.parse(result.d);
            //}

        }
    });
    return responseVal;
}

function DELETE_SITransbyTransID(transid) {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/DELETE_SITransbyTransid",
        async: false,
        data: "{'transid':" + transid + "}",
        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 responseVal;
}

function DELETE_SITransdetailbyTransID(transid) {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/DELETE_SITransdetailbyTransid",
        async: false,
        data: "{'transid':" + transid + "}",
        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 responseVal;
}

function DELETE_SITranspaymentbyTransID(transid) {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoice.aspx/DELETE_SITranspaymentbyTransid",
        async: false,
        data: "{'transid':" + transid + "}",
        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 responseVal;
}

function generateInvoiceNumber() {
    let transno = GET_LASTSITransNo();
    let transnolength = '000000';
    let newtransno;
    if (transno.length > 0) {
        transferno = parseInt(transno) + 1;

        newtransno = transnolength + transferno;
        newtransno = newtransno.substring(newtransno.length - transnolength.length);
    } else {
        newtransno = "000001"
    }

    return newtransno;
}

function Load_PaymentType() {
    //let stockgroupunit = JSON.parse(sessionStorage.getItem('stockgroupunit'));
    let paymenttype = GET_AllPaymentType();

    document.getElementById('ddpaymenttype').innerHTML = '';
    //document.getElementById('button-paymenttype').innerText = paymenttype[0]['paymenttype'];
    document.getElementById('button-paymenttype').innerText = "SELECT PAYMENT"

    for (const item of paymenttype) {
        var li = document.createElement('li')
        li.id = "gu" + item['paymenttypeid']
        document.getElementById('ddpaymenttype').appendChild(li)

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

}

function Preview() {
    let lineY = 30;
    let lineX = 15;

    let storedtransactioncollection = JSON.parse(sessionStorage.getItem('transactioncollection'))
    let trans = storedtransactioncollection;
    let transdetail = storedtransactioncollection['SITransdetailList']
    let transpayment = GET_SITranspayment_by_TransID(trans['transid']);

    let customers = GET_AllCustomer();

    let totaltax = parseFloat(trans['taxamount1']) + parseFloat(trans['taxamount2']) + parseFloat(trans['taxamount3']) + parseFloat(trans['taxamount4']) + parseFloat(trans['taxamount5']) + parseFloat(trans['taxamount6'])
    const doc = new jsPDF();

    customers = customers.filter((e) => e['CID'].toLowerCase().trim() == trans['customernumber'].toLowerCase().trim());
    let customer;
    if (customers.length > 0) {
        customer = customers[0];
    }

    //const pageSize = doc.internal.pageSize;
    //const pageWidth = pageSize.width ? pageSize.width : pageSize.getWidth();
    //const pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();
    //const header = 'Report 2014';
   // const footer = `Page ${i} of ${pageCount}`;


    // Invoice Header
    doc.setFontSize(12);
    //doc.text("SUNTOYO TECHNOLOGY PTE LTD", lineX, 20);
    //doc.text("4012 Ang Mo Kio Ave 10, Singapore 569628", lineX, 25);
    //doc.text("(569628) 06-05", lineX, 30);
    //doc.text("+(65) 6553 3855", lineX, 35); 
    //doc.text("suntoyo@suntoyo.com.sg", lineX, 40);

    //left
    doc.setFontSize(22);
    doc.text("INVOICE", lineX, 24);
    
    //left
    doc.setFontSize(12);
    if (customers.length > 0) {
        doc.text(DecryptValue(customer['CustomerName']), lineX, 35);
    }

    //right
    doc.setFontSize(10);
    doc.text("Invoice Date", lineX + 100, 20);
    doc.setFontSize(10);
    doc.text(trans['transdate'], lineX + 100, 25);

    doc.text("Invoice Number", lineX + 100, 35);
    doc.text(trans['transno'], lineX + 100, 40);


    // Invoice Table
    let arritem = [];
    let i = 1;
    $.each(transdetail, function (key, detail) {

        let item = detail;
        //item = [item['barcode'], item['name'], item['inventorydesc'], item['qty'], detail['price'].toFixed(2), detail['manualdisc'].toFixed(2), detail['amount'].toFixed(2)]
        item = [item['name'], item['inventorydesc'], parseInt(item['qty']), detail['actualprice'].toFixed(2), detail['manualdisc'].toFixed(2), detail['amount'].toFixed(2)]
        arritem.push(item)
        i = i + 1
    })

    doc.autoTable({
        startY: 50,
        margin: {
            bottom: 15,
        },
        //head: ['Name', 'Description', 'Quantity', 'Unit Price', 'Discount', 'Amount'],
        head: [[
                { content: 'Name', styles: { halign: 'left' } },
                { content: 'Description', styles: { halign: 'left' } },
                { content: 'Quantity', styles: { halign: 'right' } },
                { content: 'Unit Price', styles: { halign: 'right' } },
                { content: 'Discount', styles: { halign: 'right' } },
                { content: 'Amount', styles: { halign: 'right' } },
            ]],
        body: arritem,
        columnStyles: { 0: { halign: 'left' }, 1: { halign: 'left' }, 2: { halign: 'right' }, 3: { halign: 'right' }, 4: { halign: 'right' }, 5: { halign: 'right' } },
        bodyStyles: {
            fillColor: [245, 245, 245], // light gray
        },
        alternateRowStyles: {
            fillColor: [255, 255, 255], // white
        },
    });

 
  

    let finalY = doc.autoTable.previous.finalY; // Get Y position after the table
    const pageSize = doc.internal.pageSize;
    const pageWidth = pageSize.width ? pageSize.width : pageSize.getWidth();
    const pageHeight = pageSize.height ? pageSize.height : pageSize.getHeight();

    let addpagecount = 0;
    if (finalY > (pageHeight - 30)) {
        doc.addPage();
        finalY = 20;
    //    addpagecount = 1;

    
    }

    let pageCount = doc.internal.getNumberOfPages() + addpagecount;
    

    for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);


        const footer = `Page ${i} of ${pageCount}`;

        // Header
        // doc.text(header, 40, 15, { baseline: 'top' });

        // Footer
        doc.text(footer, pageWidth / 2 - (doc.getTextWidth(footer) / 2), pageHeight - 10, { baseline: 'bottom' });
    }



    doc.text('Subtotal', lineX + 125, finalY + 10);
    doc.text(trans['total'].toFixed(2), lineX + 172, finalY + 10);

    doc.text('GST', lineX + 125, finalY + 20);
    doc.text(" " + totaltax.toFixed(2), lineX + 172, finalY + 20);

    doc.line(lineX + 125, finalY + 23, lineX + 180, finalY + 23);

    doc.text('Total', lineX + 125, finalY + 30);
    doc.text(trans['total'].toFixed(2), lineX + 172, finalY + 30);

    doc.text('Amount Paid[' + transpayment['paymenttype'] + ']', lineX + 125, finalY + 35);
    doc.text(trans['total'].toFixed(2), lineX + 172, finalY + 35);

    doc.line(lineX + 125, finalY + 38, lineX + 180, finalY + 38);

    doc.text('Amount Due', lineX + 125, finalY + 45);
    //doc.text(trans['total'].toFixed(2), lineX + 172, finalY + 45);
    doc.text(trans['total'].toFixed(2), lineX + 172, finalY + 45);

    doc.setFontSize(12);
    doc.text('Due Date:', lineX, finalY + 50);

    //doc.text('Printed Date', pageWidth / 2 - (doc.getTextWidth('Printed Date') / 2), pageHeight - 15, { baseline: 'bottom' });

    doc.save(trans['transno'] + '.pdf');
    

}

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

    if (day.toString().length == 1) {
        day = '0' + day;
    }

    if (hour.toString().length == 1) {
        hour = '0' + hour;
    }

    if (minute.toString().length == 1) {
        minute = '0' + minute;
    }

    if (second.toString().length == 1) {
        second = '0' + second;
    }

    var dateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    return dateTime;
}

function DecryptValue(cipertext) {
    var ret;
    if (cipertext.trim() != '' && cipertext.trim() != null) {

        $.ajax({
            type: "POST",
            url: "SalesInvoice.aspx/GetDecryptedValues",
            async: false,
            data: "{'cipertext':'" + cipertext + "'}",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            success: function (result) {
                if (result) {
                    var data = JSON.parse(result.d);
                    if (data) {
                        ret = data.decryptedText;
                    }
                }
                else {
                    ret = "";
                }
            }
        });
    } else {
        ret = '';
    }
    return ret;
}

