<script>
function GetSearchProvider(){
  return $('#table_filter_loan_provider').val();
}
function GetSearchPurpose(){
  return $('#table_filter_loan_purpose').val();
}
function GetSearchClient(){
  return $('#clients').val();
}
function GetSearchDate(){
  return $('#date_range').val();
}
function GetSearchwork(){
  return $('#work').val();
}
<?php if($page_name=='data_entry_approval' || $page_name=='data_entry_approval_2_level'){?>
  function GetStartDate(){
    return $('#table_filter_start_date').val();
  }
  function GetEndDate(){
    return $('#table_filter_end_date').val();
  }
  function GetSearchWork(){
    return $('#table_filter_work').val();
  }
  function GetSearchUser(){
    return $('#table_filter_user').val();
  }
  function GetSearchApprovalStatus(){
    return $('#table_filter_approval_status').val();
  }
  function GetSearchAccount() {
    return $('#table_filter_account').val();
  }
  <?php } ?>
  <?php
  $page_type='';
  if($page_name=='data_entry_approval'){
    $page_type='approval_entries';
  }elseif($page_name=='data_entry_approval_2_level'){
    $page_type='approval_entries_2_level';
  }
  ?>
  <?php if($page_name=='loans_receivable'){
    $loan_type='receivable';
  }elseif($page_name=='loans_payable'){
    $loan_type='payable';
  }else{
    $loan_type='';
  } ?>
  var loans_view_table = $('#loans_view_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'loans/select_loans/'.$page_type ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        d.loan_purpose = GetSearchPurpose();
        d.loan_provider = GetSearchProvider();
        d.loan_type = "<?php echo $loan_type ?>";
        <?php if($page_name=='provider_profile'){?>
          d.loan_provider = "<?php echo $provider_data->loan_provider_id?>";
          <?php } ?>
          <?php if($page_name=='data_entry_approval' || $page_name=='data_entry_approval_2_level'){?>
            d.start_date = GetStartDate();
            d.end_date = GetEndDate();
            d.work = GetSearchWork();
            d.approval_status = GetSearchApprovalStatus();
            d.user_id = GetSearchUser();
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX" : true,
        buttons: [
          { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Loans' },
          { extend: 'csv', className: 'btn purple btn-outline ' },
          { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
        ],
        dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
        "lengthMenu": [
          [25, 50, 100, -1],
          [25, 50, 100, "All"] // change per page values here
        ],
        "columnDefs": [
          {
            "targets": [ 1,8,15,16,17,18,19<?php if($this->session->userdata('user_role')=='auditor' && $this->session->userdata('user_data_permission')['adding']!=1) { echo ",14"; } ?><?php if($page_name=='loans_receivable'){ echo ",12"; } ?> ],
            className: "hidden"
          },
          {
            render: function (data, type, full, meta) {
              return "<div class='text-wrap width-400'>" + data + "</div>";
            },
            targets: 3
          },
        ],
        "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
          if(aData[18]=='0'){
            $('td', nRow).css('background-color', '#ffcccc');
          }else if(aData[18]=='2'){
            $('td', nRow).css('background-color', '#ffcccc');
          }
          if(aData[18]=='1'){
            if(aData[19]=='0'){
              $('td', nRow).css('background-color', '#F0FAB3');
            }else if(aData[19]=='2'){
              $('td', nRow).css('background-color', '#ffcccc');
            }
          }
        },
        'order': false
      });
      var loan_payments_view_table = $('#loan_payments_view_table').DataTable({
        "ajax":{
          url :"<?php echo base_url().'accounts/select_account_transactions/loan/'.$page_type ?>", // json datasource
          type: "post", // type of method  , by default would be get
          data: function(d){
            d.date = GetSearchDate();
            d.loan_purpose = GetSearchPurpose();
            d.loan_provider = GetSearchProvider();
            d.loan_type = "<?php echo $loan_type ?>";
            <?php if($page_name=='provider_profile'){?>
              d.loan_provider = "<?php echo $provider_data->loan_provider_id?>";
              <?php } ?>
              <?php if($page_name=='data_entry_approval' || $page_name=='data_entry_approval_2_level'){?>
                d.start_date = GetStartDate();
                d.end_date = GetEndDate();
                d.work = GetSearchWork();
                d.approval_status = GetSearchApprovalStatus();
                d.user_id = GetSearchUser();
                d.acc_head_id = GetSearchAccount();
                <?php } ?>
              }
            },
            "bProcessing": true,
            "deferRender": true,
            "bDeferRender": true,
            "scrollX" : true,
            buttons: [
              { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Loan Payments' },
              { extend: 'csv', className: 'btn purple btn-outline ' },
              { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
            ],
            dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
            "lengthMenu": [
              [25, 50, 100, -1],
              [25, 50, 100, "All"] // change per page values here
            ],
            "columnDefs": [
              {
                "targets": [3,6,7,8,9,19<?php if($page_name=='reports_activity'){ echo ",18"; }?><?php if($this->session->userdata('user_role')=='auditor') { echo ",18"; } ?>],
                className: "hidden"
              }
            ],
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
              if(aData[23]=='0'){
                $('td', nRow).css('background-color', '#ffcccc');
              }else if(aData[23]=='2'){
                $('td', nRow).css('background-color', '#ffcccc');
              }
              if(aData[23]=='1'){
                if(aData[24]=='0'){
                  $('td', nRow).css('background-color', '#F0FAB3');
                }else if(aData[24]=='2'){
                  $('td', nRow).css('background-color', '#ffcccc');
                }
              }
            },
            'order': false
          });
          $(".table_filter").on("change", function() {
            loan_payments_view_table.ajax.reload();
            loans_view_table.ajax.reload();
          });
          $('body').on('click', '#btn_edit_loan_receipt', function() {
            var no = $(this).closest('tr').children('td');
            var bill_type = $(this).attr('data-bill-type');
            var bill_id = $(this).attr('data-bill-id');
            var tr_id_column_no = $(this).attr('data-id-column');
            var tr_display_type = $(this).attr('data-tr-display-type');
            if(bill_type=='user_payment_return'){
              $('#label_paid_amount_old_edit_bill_payment').text("Received Amount");
              $('#label_paid_date_edit_bill_payment').text("Received Date");
              $('#label_debit_acc_edit_bill_payment').text("Received To Account");
            }else{
              $('#label_paid_amount_old_edit_bill_payment').text("Paid Amount");
              $('#label_paid_date_edit_bill_payment').text("Paid Date");
              $('#label_debit_acc_edit_bill_payment').text("Paid From Account");
            }
            $(".edit_bill_payment_fields").hide();
            var tr_id = no.eq(tr_id_column_no).text();
            $.post("<?php echo base_url() ?>bills/get_details",{bill_id:bill_id,bill_type:bill_type},function(data) {
              var obj = $.parseJSON(data);
              if(obj.count==1){
                $('#loan_title_edit_loan_receipt').val(obj.loan_title);
                $('#loan_provider_edit_loan_receipt').val(obj.provider);
                $('#tr_id_edit_loan_receipt').val(tr_id);
                $('#loan_receipt_received_date_edit').datepicker("setDate",no.eq(2).text());
                var paid_amount = parseFloat(no.eq(10).text());
                $('#debit_acc_edit_bill_payment').val(no.eq(20).text()).trigger('change');
                $('#loan_receipt_received_amount_edit').val(paid_amount);
                $('#tr_type_edit_bill_payment').val(bill_type+"_transaction");
                $('#reference_type_edit_bill_payment').val(bill_type);
                $('#reference_id_edit_bill_payment').val(bill_id);
                $('#loan_receipt_remarks_edit').val(no.eq(15).text());
              }
            })
          })
          $("#loan_receipt_acc_add").select2({
            placeholder: "Select Credit Account",
            dropdownParent: $("#form_loan_receipt_add")
          })
          $("#loan_receipt_received_date_add,#loan_receipt_received_date_edit").datepicker( {
            todayHighlight:!0, orientation:"bottom left", templates: {
              leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
            },
            endDate: '+0d',
            <?php if($this->session->userdata('user_role')!='admin' && $this->config->item('User_calendar_date_restriction_enabled')==1){ ?>
              startDate: '<?php echo $this->config->item('User_calendar_date_restriction_start_days');?>d'
              <?php } ?>
            })
            $("#loan_receipt_acc_edit").select2({
              placeholder: "Select Credit Account",
              dropdownParent: $("#form_loan_receipt_edit")
            })
            <?php if($page_name=='loans_receivable' || $page_name=='loans_payable'){ ?>

              $("#table_filter_loan_purpose,#table_filter_loan_provider").select2({
                placeholder: "Select Option"
              })
              $("#loan_received_acc_add").select2({
                placeholder: "Select Credit Account",
                dropdownParent: $("#form_loan_add")
              })
              $("#work_id_loan_add").select2({
                placeholder: "Select Loan Purpose",
                dropdownParent: $("#form_loan_add")
              })

              $("#loan_received_acc_edit").select2({
                placeholder: "Select Credit Account",
                dropdownParent: $("#form_loan_edit")
              })
              $("#work_id_loan_edit").select2({
                placeholder: "Select Loan Purpose",
                dropdownParent: $("#form_loan_edit")
              })

              $("#provider_add").select2({
                dropdownParent: $("#form_loan_add"),
                placeholder: "Select Provider"
              })
              $("#provider_edit").select2({
                dropdownParent: $("#form_loan_edit"),
                placeholder: "Select Provider"
              })

              function select_provider(select_id,selected_value='',type=''){
                $('#'+select_id).html('');
                <?php if($page_name=='loans_receivable'){ ?>
                  if(type=='filter'){
                    $('#'+select_id).append("<option value='all' selected >All Borrower</option>");
                  }else{
                    $('#'+select_id).append("<option disabled selected >Select Borrower</option>");
                  }
                  <?php }else{?>
                    if(type=='filter'){
                      $('#'+select_id).append("<option value='all' selected >All Providers</option>");
                    }else{
                      $('#'+select_id).append("<option disabled selected >Select Provider</option>");
                    }
                    <?php } ?>
                    $.post("<?php echo base_url() ?>loans/select_provider",{},function(data) {
                      var obj = $.parseJSON(data);
                      var i=0;
                      if(obj.count>0) {
                        while (i < obj.data.length) {
                          $('#'+select_id).append("<option value=" + obj.data[i]['loan_provider_id'] + ">" +obj.data[i]['loan_provider_name'] + "</option>");
                          i++;
                        }
                        if(selected_value!=''){
                          $('#'+select_id).val(selected_value).trigger("change");
                        }
                      }
                    })
                  }
                  select_provider('provider_add');
                  select_provider('provider_edit');
                  select_provider('table_filter_loan_provider','','filter');

                  $("#loan_date_add,#loan_date_edit").datepicker( {
                    todayHighlight:!0, orientation:"bottom left", templates: {
                      leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
                    },
                    endDate: '+0d',
                    <?php if($this->session->userdata('user_role')!='admin' && $this->config->item('User_calendar_date_restriction_enabled')==1){ ?>
                      startDate: '<?php echo $this->config->item('User_calendar_date_restriction_start_days');?>d'
                      <?php } ?>
                    })
                    $('body').on('click', '#loan_edit_btn', function() {
                      var no = $(this).closest('tr').children('td');
                      $('#loan_id_edit').val(no.eq(1).text());
                      $('#title_edit').val(no.eq(2).text());
                      $('#loan_amount_edit').val(no.eq(6).text());
                      $('#op_balance_edit').val(no.eq(7).text());
                      $('#description_edit').val(no.eq(3).text());
                      $('#payable_balance_edit').val(no.eq(8).text());
                      $("#loan_received_acc_edit").val(no.eq(15).text()).trigger('change');
                      $("#work_id_loan_edit").val(no.eq(16).text()).trigger('change');
                      $('#loan_date_edit').datepicker("setDate", no.eq(4).text());
                      select_provider('provider_edit',no.eq(17).text());
                      var loan_amount = parseFloat(no.eq(6).text());
                      var op_balance = parseFloat(no.eq(7).text());
                      var total_amount = loan_amount+op_balance;
                      $("#total_balance_edit").val(total_amount);
                    })
                    $('body').on('click', '#loan_delete_btn', function() {
                      var no = $(this).closest('tr').children('td');
                      $('#loan_id_delete').val(no.eq(1).text());
                    })
                    $('body').on('click', '#btn_add_loan_receipt', function() {
                      var no = $(this).closest('tr').children('td');
                      $('#reference_id_add_loan_receipt').val(no.eq(1).text());
                      $('#loan_title_add_receipt').val(no.eq(2).text());
                      $('#loan_provider_add_receipt').val(no.eq(5).text());
                    })
                    $('body').on('change keyup', '#loan_amount_add,#op_balance_add', function() {
                      var loan_amount = parseFloat($("#loan_amount_add").val());
                      var op_balance = parseFloat($("#op_balance_add").val());
                      if(isNaN(loan_amount)) {
                        var loan_amount = 0;
                      }
                      if(isNaN(op_balance)) {
                        var op_balance = 0;
                      }
                      var total_amount = loan_amount+op_balance;
                      $("#total_balance_add").val(total_amount);
                    })
                    $('body').on('change keyup', '#loan_amount_edit,#op_balance_edit', function() {
                      var loan_amount = parseFloat($("#loan_amount_edit").val());
                      var op_balance = parseFloat($("#op_balance_edit").val());
                      if(isNaN(loan_amount)) {
                        var loan_amount = 0;
                      }
                      if(isNaN(op_balance)) {
                        var op_balance = 0;
                      }
                      var total_amount = loan_amount+op_balance;
                      $("#total_balance_edit").val(total_amount);
                    })

                    var loan_providers_view_table = $('#loan_providers_view_table').DataTable({
                      "ajax":{
                        url :"<?php echo base_url().'loans/select_loan_providers' ?>", // json datasource
                        type: "post", // type of method  , by default would be get
                        data: function(d){
                          d.loan_type = "<?php echo $loan_type ?>";
                        }
                      },
                      "bProcessing": true,
                      "deferRender": true,
                      "bDeferRender": true,
                      "scrollX" : true,
                      buttons: [
                        { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Loan Providers' },
                        { extend: 'csv', className: 'btn purple btn-outline ' },
                        { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
                      ],
                      dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
                      "lengthMenu": [
                        [25, 50, 100, -1],
                        [25, 50, 100, "All"] // change per page values here
                      ],
                      "columnDefs": [
                        {
                          "targets": [ 4 ],
                          className: "hidden"
                        },
                      ],
                      'order': false
                    });
                    $(".table_filter").on("change", function() {
                      loan_providers_view_table.ajax.reload();
                    });
                    $(".hide_column").hide();
                    // Date Range Picker
                    var start = moment();
                    var end = moment();

                    function cb(start, end) {
                      $('#date_range').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                      loan_payments_view_table.ajax.reload();
                      loans_view_table.ajax.reload();
                      loan_providers_view_table.ajax.reload();
                    }

                    $('#date_range').daterangepicker({
                      buttonClasses: "m-btn btn",
                      applyClass: "btn-primary",
                      cancelClass: "btn-secondary",
                      startDate: start,
                      endDate: end,
                      locale: {
                        format: 'MMMM D, YYYY'
                      },
                      ranges: {
                        'Today': [moment(), moment()],
                        'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                        'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                        'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                        'This Month': [moment().startOf('month'), moment().endOf('month')],
                        'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                        'All time': [moment('1970-01-01'), moment().add(9999, 'days')],
                      }
                    }, cb);

                    cb(start, end);


                    $(".form_submit_btn").click(function (e) {
                      e.preventDefault();
                      var a = $(this),
                      l = $(this).closest("form"),
                      action = l.attr('action');
                      var form_id = l.attr('id');
                      l.validate({
                        rules: {
                          payable_balance: {
                            number: !0,
                            required: !0
                          },
                          paid_amount: {
                            number: !0,
                            required: !0
                          },
                          expense_amount: {
                            number: !0,
                            required: !0
                          },
                          received_amount: {
                            number: !0,
                            required: !0
                          },
                          budget: {
                            number: !0,
                            required: !0
                          },
                          edit_paid_amount: {
                            number: !0,
                            required: !0
                          }
                        }, invalidHandler: function (e, r) {
                          var i = $("#" + form_id + "_msg");
                          i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
                        }, submitHandler: function (e) {
                        }
                      }), l.valid() && (a.addClass("m-loader m-loader--right m-loader--light").attr("disabled", !0),
                      l.ajaxSubmit({
                        url: action,
                        success: function (e, t, r, s) {
                          var modal_id = l.attr('data-modal-id');
                          var form_type = l.attr('data-form-type');
                          $("#" + form_id + "_msg").addClass("m--hide");
                          // Block UI
                          mApp.blockPage({
                            overlayColor: "#000000",
                            type: "loader",
                            state: "success",
                            message: "Please wait..."
                          }), setTimeout(function () {
                            mApp.unblockPage()
                          }, 2e3);
                          var obj = $.parseJSON(e);
                          if (obj.status == 1) {
                            a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                            toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                            $("#"+modal_id).modal('toggle');
                            $("."+form_id+"_fields").val('');
                            $("."+form_id+"_select").val('').trigger("change");
                            loan_payments_view_table.ajax.reload();
                            loans_view_table.ajax.reload();
                            loan_providers_view_table.ajax.reload();
                            select_provider('provider_add');
                            select_provider('provider_edit');
                            select_provider('table_filter_loan_provider');
                          } else {
                            a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                            toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                          }
                          if (obj == null) {
                            setTimeout(function () {
                              a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                              toastr["warning"]("Your Attempt is Timed Out. Please Try Again.", "Timed Out");
                            }, 2e4)
                          }
                        },error: function() {
                          a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                          toastr["error"]("Sorry. There Has Been Some Error Occurred. Please Try Again.", "Error");
                        }
                      })
                    )
                  });
                  <?php } ?>
                  </script>
