$(document).ready(function() {

    $('#table_journal').DataTable({
        "aaSorting": [],
        "pagingType": "full_numbers",
        "lengthMenu": [
            [20, 50, 100, 250, 500],
            [20, 50, 100, 250, 500]
        ],
        ajax: "/get-journal",
        columns: [
            {
                data: 'checkbox'
            },
            {
                data: 'id'
            },
            {
                data: 'journal_paydate'
            },
            {
                data: 'name'
            },

            {
                data: 'supplier_name'
            },
            {
                data: 'journal_reference_number'
            },
            {
                data: 'voucher'
            },
            {
                data: 'voucher_ref'
            },
            {
                data: 'account_code'
            },
            {
                data: 'journal_invoice'
            },
            {
                data: 'journal_des'
            },
            {
                data: 'journal_debit'
            },
            {
                data: 'journal_credit'
            },
            {  data: 'action'}
        ],
        "initComplete": function(settings, json) {
        },
        "fnDrawCallback": function ( row, data, start, end, display ) {
            let tr = $('#tbody tr');
            let total_debit_usd = 0;
            let total_debit_baht = 0;
            let total_credit_usd = 0;
            let total_credit_baht = 0;
            $.each(tr,function (ii,vv) {
                let amount_debit = $(this).find('td:nth-child(12) span').data('amount');
                let amount_credit = $(this).find('td:nth-child(13) span').data('amount');
                let cur_id = $(this).find('td:nth-child(12) span').data('curr');
                amount_debit = amount_debit?parseFloat(amount_debit):0;
                amount_credit = amount_credit?parseFloat(amount_credit):0;
                if(cur_id===2){
                    total_debit_usd+=amount_debit;
                    total_credit_usd+=amount_credit;
                }

                if(cur_id===3){
                    total_debit_baht+=amount_debit;
                    total_credit_baht+=amount_credit;
                }
            });
            tdu = total_debit_usd?('$'+total_debit_usd.toFixed(2)):'';
            tdb = total_debit_baht?('฿'+total_debit_baht.toFixed(2)):'';
            tcu = total_credit_usd?('$'+total_credit_usd.toFixed(2)):'';
            tcb = total_credit_baht?('฿'+total_credit_baht.toFixed(2)):'';
            $('#tfoot tr:first-child ').find('.total_debit').html((tdu?(tdu+'<br>'):'')+tdb);
            $('#tfoot tr:first-child ').find('.total_credit').html((tcu?(tcu+'<br>'):'')+tcb);
          },
    });
});
