$(document).ready(function () {
    /*let transaction = GET_SITransactionByDateRange('2025-05-29', '2025-06-05')    

    transaction.sort(function(a, b) {
        return a['transno'] > b['transno'];
    });

    $('#table-body-SIList').on('click', 'tr #button-view', function () {
        var rowIndex = $(this).closest('tr').index();

        let selectedtransaction = transaction[rowIndex];
        
        
        sessionStorage.setItem('transactioncollection', JSON.stringify(selectedtransaction))
        window.location.href = '/SalesInvoice.aspx';
        
    });
    
    Load_SITransaction(transaction);*/

     $("#button-new-invoice").on('click', function (event) {
        sessionStorage.removeItem('transactioncollection');
        window.location.href = '/SalesInvoice.aspx';
    });

    $("#selectedsearch" ).on( "change", function() {  
        var input, filter, table, tr, td, i, txtValue;
        //input = document.getElementById("myInput");
        //filter = input.value.toUpperCase();
        filter = $("#selectedsearch option:selected" ).text().toUpperCase();
        table = document.getElementById("table-body-SIList");
        tr = table.getElementsByTagName("tr");               
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[2];
            if(filter != 'ALL'){
                if (td) {                
                    txtValue = td.textContent || td.innerText;                           
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {                        
                        tr[i].style.display = "";
                    } else {                        
                        tr[i].style.display = "none";
                    }               
                }   
            }else{
                tr[i].style.display = "";
            }   
        }      
    });   
});

function Load_SITransactionList(startdate,enddate){
    let transaction = GET_SITransactionByDateRange(startdate, enddate)    
    transaction.sort(function(a, b) {
        return a['transno'] > b['transno'];
    });

    $('#table-body-SIList').on('click', 'tr #button-view', function () {
        var rowIndex = $(this).closest('tr').index();
        let selectedtransaction = transaction[rowIndex];               
        sessionStorage.setItem('transactioncollection', JSON.stringify(selectedtransaction))
        window.location.href = '/SalesInvoice.aspx';        
    });
    
    Load_SITransaction(transaction);
}

function GET_SITransactionByDateRange(startdate, enddate) {
    var responseVal;
    $.ajax({
        type: "POST",
        url: "SalesInvoiceList.aspx/GET_SITransactionbyDateRange",
        data: "{'startdate':'" + startdate + "', 'enddate':'" + enddate + "'}",
        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_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) {
            if (JSON.parse(result.d) == null) {
                responseVal = 0;
            } else {
                responseVal = JSON.parse(result.d)['paymenttype']
            }

        }
    });
    return responseVal;
}


function Load_SITransaction(transaction) {
    let tbody = document.getElementById("table-body-SIList");    
    $.each(transaction, function (key, detail) {

        //let paymenttype = GET_SITranspayment_by_TransID
        let paymenttype = GET_SITranspayment_by_TransID(detail['transid']);
        
        if(paymenttype == 0){
            paymenttype = '';
        }
        let tr = document.createElement("tr");
        let status = "";
        let tdinvoiceno = document.createElement("td");
        tdinvoiceno.className = 'border-start border-end border-bottom  text-center px-1 py-1 align-content-center';
        let inoviceno = document.createTextNode(detail['transno'].toString().trim());

        let tdbusinessdate = document.createElement("td");
        tdbusinessdate.className = 'border-start border-end border-bottom px-1 py-1 align-content-center';
        let businessdate = document.createTextNode(DateFormat(detail['businessdate'].substring(0, 10)));

        if (detail['transstatus'].toString().trim() == "2") {
            status = "Completed"
        } else if (detail['transstatus'].toString().trim() == "3") {
            status = "Pending"
        }
        let tdtransstatus = document.createElement("td");
        tdtransstatus.className = 'border-start border-end border-bottom px-1 py-1 align-content-center';
        let transstatus = document.createTextNode(status.toString().trim());

        let tdpaymenttype = document.createElement("td");
        tdpaymenttype.className = 'border-start border-end border-bottom px-1 py-1 align-content-center';
        let payment = document.createTextNode(paymenttype);
        //let payment = document.createTextNode('');
        //let payment = document.createTextNode('');

        let tdamount = document.createElement("td");
        tdamount.className = 'border-start border-end border-bottom px-1 py-1 align-content-center';
        let amount = document.createTextNode("SGD " +  parseFloat(detail['total']).toFixed(2));     

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

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

        var iconview = document.createElement('i');
        iconview.className = 'bi bi-list';
        iconview.style = "font-size: 22px;"
        buttonview.appendChild(iconview);

        tdinvoiceno.appendChild(inoviceno);
        tdbusinessdate.appendChild(businessdate);
        tdtransstatus.appendChild(transstatus);
        tdpaymenttype.appendChild(payment);
        tdamount.appendChild(amount);
        tdaction.appendChild(buttonview)

        tr.appendChild(tdinvoiceno);
        tr.appendChild(tdbusinessdate);
        tr.appendChild(tdtransstatus);
        tr.appendChild(tdpaymenttype);
        tr.appendChild(tdamount);
        tr.appendChild(tdaction)
        tbody.appendChild(tr);
       

    });
}

function DateFormat(selecteddate) {
    const date = new Date(selecteddate); // Create a Date object

    const day = date.getDate();
    const month = date.toLocaleString('default', { month: 'short' });
    const year = date.getFullYear();

    const formattedDate = `${day}-${month}-${year}`;
    return formattedDate;
}