$( document ).ready(function() {
    report();
    slip_report();
    due_bill_report();

     $('#payment_modal').on('hidden.bs.modal', function () {
       

        $(this).find('form').trigger('reset');
       })
 
});
function report(){
    $.fn.dataTable.ext.errMode = 'none';

$('#payment-table').on('error.dt', function(e, settings, techNote, message) {
   console.log('An error has been reported by DataTables: ', message);
}).DataTable();
    var company_id=$("#company_id").val();
  
    var manageTable = $('#payment-table').DataTable();
    manageTable.destroy();
    manageTable= $("#payment-table").DataTable({
      "ajax": {
                "url": 'fetchTotalPaymentDue',
                'type': "GET",
                'data':{company_id:company_id},
               },
      lengthMenu: [
                [10, 25, 50, 100, -1],
                ['10', '25', '50', '100', 'All']],
                "responsive": false, "lengthChange": false, "autoWidth": false,
     "order": [[0, 'asc']],
       dom: "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-6'i><'col-sm-6'p>>",
            buttons: [{
                    extend: 'copy',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'csv',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'print',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))',
                    },
                    footer: true

                },
                {
                    extend: 'excel',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'pdf',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                }],

                 "footerCallback": function (row, data, start, end, display) {
                var api = this.api(), data;

                // converting to interger to find total

                var intVal = function (i) {


                    if (typeof i === 'string') {

                        i = i.replace(/[\a-zA-Z₹]/g, '') * 1;

                    }
                    // check if you got a valid number.
                    if (Number.isNaN(i)) {
                        return 0;
                    }
                    return i;
                };

                var total=api
                        .column(2, {page: 'current'})
                        .data()
                        .reduce(function (a, b) {

                            return intVal(a) + intVal(b);
                        }, 0);
            
                  $(api.column(0).footer()).html('TOTAL');
                  $(api.column(2).footer()).html(' ' + total.toFixed(2));
                  

            }
      });
}

$(document).on('click', '#pay', function (e) {
    e.preventDefault();
    var id = $(this).data('id');

         $.ajax({

            url: 'total_payment_due/'+id,
            dataType: 'json',
            success: function (response) {
              
                $("#balance_amount").empty();
                $("#balance_amount").val(response.toFixed(2));
                $("#balance_amount1").val(response.toFixed(2));
                var balance_total=$("#balance_amount1").val();
                if(balance_total <= 0){
                $('#Amount').prop('disabled', true);
                $('#pay_button').prop('disabled', true);
                }
            }
        });

      $("#payment_form").unbind('submit').on('submit', function () {
        var form = $(this);

        // remove the text-danger
        $(".text-danger").remove();

        $.ajax({
             url: 'pay_due_amount/' + id,
            type: form.attr('method'),
            data: form.serialize(), // /converting the form data into array and sending it to server
            dataType: 'json',
            success: function (response) {
                 report();
                  if (response.success = true) {
                    
                   $('#payment_modal').modal('hide');
                   $("#payment_form")[0].reset();
                      swal("Payment Successfully Done!", {
                      icon: "success",
                      });
                }
                else{
                    $('#payment_modal').modal('hide');
                    $("#payment_form")[0].reset();
                    swal("Payment faild!", {
                      icon: "error",
                      });
                }
              
            }
        });

        return false;
    });
});


function slip_report(){
    var company_id=$("#company_id").val();
     var datefrom=$("#datefrom").val();
    var dateto=$("#dateto").val();
    var manageTable = $('#paymentslip-table').DataTable();
    manageTable.destroy();
    manageTable= $("#paymentslip-table").DataTable({
      "ajax": {
                "url": 'fetchPaymentSlip',
                'type': "GET",
                'data':{company_id:company_id,datefrom:datefrom,dateto:dateto},
               },
      lengthMenu: [
                [50, 75, 120, 500, -1],
                ['50', '75', '120', '500', 'All']],
                // "responsive": false, "lengthChange": false, "autoWidth": false,
     "order": [[0, 'asc']],
       dom: "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-6'i><'col-sm-6'p>>",
            buttons: [{
                    extend: 'copy',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'csv',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'print',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))',
                    },
                    footer: true

                },
                {
                    extend: 'excel',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                },
                {
                    extend: 'pdf',
                    exportOptions: {
                        columns: ':visible:not(:eq(3))'
                    },
                    footer: true
                }],

                 "footerCallback": function (row, data, start, end, display) {
                var api = this.api(), data;

                // converting to interger to find total

                var intVal = function (i) {


                    if (typeof i === 'string') {

                        i = i.replace(/[\a-zA-Z₹]/g, '') * 1;

                    }
                    // check if you got a valid number.
                    if (Number.isNaN(i)) {
                        return 0;
                    }
                    return i;
                };

                var total=api
                        .column(9, {page: 'current'})
                        .data()
                        .reduce(function (a, b) {

                            return intVal(a) + intVal(b);
                        }, 0);
            
                  $(api.column(0).footer()).html('TOTAL');
                  $(api.column(9).footer()).html(' ' + total.toFixed(2));
                  

            }
      });
}

function pdf_report() {

    window.open('export_public_slip_pdf');


}

function due_bill_report(){
    var company_id=$("#company_id").val();
    var datefrom=$("#datefrom").val();
    var dateto=$("#dateto").val();
  
    var ledger_id=$("#ledger_id").val();
    var manageTable = $('#report-table').DataTable();
    manageTable.destroy();
    manageTable= $("#report-table").DataTable({
      "ajax": {
                "url": 'fetchDueBillrData',
                'type': "GET",
                'data':{company_id:company_id,datefrom:datefrom,dateto:dateto,ledger_id:ledger_id},
               },
               "order": [[0, 'asc']],
    //   lengthMenu: [
    //             [10, 25, 50, 100, -1],
    //             ['10', '25', '50', '100', 'All']],
                // "responsive": false, "lengthChange": false, "autoWidth": false,
     
       dom: "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-6'i><'col-sm-6'p>>",
            buttons: [{
                    extend: 'copy',
                    exportOptions: {
                        columns: ':visible:not(:eq(13))'
                    }
                },
                {
                    extend: 'csv',
                    exportOptions: {
                        columns: ':visible:not(:eq(11))'
                    }
                },
                {
                    extend: 'print',
                    exportOptions: {
                        columns: ':visible:not(:eq(13))',
                    }

                },
                {
                    extend: 'excel',
                    exportOptions: {
                        columns: ':visible:not(:eq(13))'
                    }
                },
                {
                    extend: 'pdf',
                    exportOptions: {
                        columns: ':visible:not(:eq(13))'
                    }
                }],

                 "footerCallback": function (row, data, start, end, display) {
                var api = this.api(), data;

                // converting to interger to find total

                var intVal = function (i) {


                    if (typeof i === 'string') {

                        i = i.replace(/[\a-zA-Z₹]/g, '') * 1;

                    }
                    // check if you got a valid number.
                    if (Number.isNaN(i)) {
                        return 0;
                    }
                    return i;
                };
                var qty=api
                        .column(8, {page: 'current'})
                        .data()
                        .reduce(function (a, b) {

                            return intVal(a) + intVal(b);
                        }, 0);
                var total=api
                        .column(9, {page: 'current'})
                        .data()
                        .reduce(function (a, b) {

                            return intVal(a) + intVal(b);
                        }, 0);
                 var balance=api
                        .column(10, {page: 'current'})
                        .data()
                        .reduce(function (a, b) {

                            return intVal(a) + intVal(b);
                        }, 0);
                  $(api.column(0).footer()).html('TOTAL');
                  $(api.column(8).footer()).html(' ' + qty.toFixed(2));
                  $(api.column(9).footer()).html(' ' + total.toFixed(2));
                  $(api.column(10).footer()).html(' ' + balance.toFixed(2));

            }
      });
}

function export_due_pdf() {
 var company_id=$("#company_id").val();
    var datefrom=$("#datefrom").val();
    var dateto=$("#dateto").val();
  
    var ledger_id=$("#ledger_id").val();
    window.open('export_due_pdf');


}

