<script>
<?php if ($page_name == 'invoices_view' || $page_name == 'invoices_payable') { ?>

  $("#table_filter_user").select2({
    placeholder: "Select  User"
  })
  $("#table_filter_invoice_work").select2({
    placeholder: "Select  Work",
    templateResult: format_project_dropdown
  })

  function GetSearchInvoicework() {
    return $('#table_filter_invoice_work').val();
  }

  function GetSearchStartDate() {
    return $('#table_filter_invoice_start_date').val();
  }
  function GetSearchEndDate() {
    return $('#table_filter_invoice_end_date').val();
  }
  function get_branch_id() {
    return $('#company_branch :selected').val();
  }
  function getworkstatus() {
    return $('#table_filter_work_status :selected').val();
  }
  function getpaymentstatus() {
    return $('#table_filter_payment_status :selected').val();
  }
  <?php } ?>
  <?php if ($page_name == 'work_summary') { ?>
    function GetStartDate() {
      return $('#table_filter_start_date').val();
    }
    function GetEndDate() {
      return $('#table_filter_end_date').val();
    }
    <?php } ?>
    <?php if ($page_name == 'data_entry_approval') { ?>

      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();
      }
      <?php } ?>
      <?php
      $page_type = '';
      if ($page_name == 'data_entry_approval') {
        $page_type = 'approval_entries';
      }
      ?>
      var invoices_view_table = $('#invoices_view_table').DataTable({
        "ajax": {
          url: "<?php echo base_url() . 'invoices/select_invoices/view/' . $page_type ?>", // json datasource
          type: "post", // type of method  , by default would be get
          data: function(d) {
            <?php if ($page_name == 'invoices_view') { ?>
              d.start_date = GetSearchStartDate();
              d.end_date = GetSearchEndDate();
              d.work_status = getworkstatus();
              d.payment_status = getpaymentstatus();
              d.project = GetSearchInvoicework();
              d.invoice_type = "<?php echo $invoice_type ?>"
              <?php if (!empty($this->config->item('company_branches'))) { ?>
                d.branch_id = get_branch_id();
                <?php } ?>
                <?php } elseif ($page_name == 'work_profile' || $page_name == 'projects_profile' || $page_name == 'work_summary') { ?>
                  d.project = "<?php echo $work_data->work_id ?>";
                  <?php }elseif($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
                      d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
                      <?php } ?>
                  <?php if ($page_name == 'stage_profile' || $page_name == 'stage_summary') { ?>
                    d.stage_id = "<?php echo $stage_data->stage_id ?>";
                    <?php } ?>
                    <?php if ($page_name == 'work_summary') { ?>
                      d.start_date = GetStartDate();
                      d.end_date = GetEndDate();
                      <?php } ?>
                      <?php if ($page_name == 'invoices_payable') { ?>
                        d.project = GetSearchInvoicework();
                        d.type = 'payable';
                        <?php } ?>
                        <?php if ($page_name == 'data_entry_approval') { ?>
                          d.start_date = GetStartDate();
                          d.end_date = GetEndDate();
                          d.project = GetSearchWork();
                          d.approval_status = GetSearchApprovalStatus();
                          d.created_by = GetSearchUser();
                          <?php } ?>
                        }
                      },
                      "bProcessing": true,
                      "deferRender": true,
                      "bDeferRender": true,
                      <?php if ($page_name == 'work_summary') { ?> "scrollX": false,
                      bFilter: false,
                      "bLengthChange": false,
                      "bPaginate": false,
                      "bInfo": false,
                      buttons: [{
                        extend: 'colvis',
                        className: 'btn dark btn-outline',
                        text: 'Columns'
                      }],
                      "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
                      <?php } else { ?>
                        "scrollX": true,
                        buttons: [{
                          extend: 'print',
                          className: 'btn dark btn-outline',
                          title: 'Client Invoices'
                        },
                        {
                          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
                      ],
                      <?php } ?>
                      "columnDefs": [{
                        "targets": [2,23,24,25,26 <?php if ($page_name == 'work_summary') {
                          echo ",1,4,5,22";
                        } ?><?php if ($this->config->item('Tax_tax_splitting') == 0) {
                          echo ",10,11,12,13,14,15";
                        } ?><?php if ($this->session->userdata('user_role') == 'auditor' && $this->session->userdata('user_data_permission')['adding'] != 1) {
                          echo ",22";
                        } ?><?php if (empty($this->config->item('company_branches'))) { echo ",1"; }?><?php if (isset($invoice_type) && $invoice_type=='other_income') { echo ",5"; }?>
                      <?php if($this->config->item('Client_Payment_client_payment_invoice_template')==3 || $this->config->item('Client_Payment_client_payment_invoice_template')==5 || $this->config->item('Client_Payment_client_payment_invoice_template')==6  || $this->config->item('Client_Payment_client_payment_invoice_template')==7){ echo ",8,10,11,12,13,14,15";}?>],
                        className: "hidden"
                      }],
                      'order': false,
                      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                        if (aData[24] == '0') {
                          $('td', nRow).css('background-color', '#ffcccc');
                        } else if (aData[24] == '2') {
                          $('td', nRow).css('background-color', '#ffcccc');
                        }
                      }
                    });

                    $(".hide_column").hide();

                    $("[data-switch=true]").bootstrapSwitch()


                    $('body').on('click', '#invoice_delete_btn', function() {
                      var no = $(this).closest('tr').children('td');
                      $('#invoice_id_delete').val(no.eq(23).text());
                    });
                    $("#work_id").select2({
                      placeholder: "Select Work",
                      dropdownParent: $("#form_document_add"),
                      templateResult: format_project_dropdown
                    })
                    $("#work_id_edit_invoice").select2({
                      placeholder: "Select Work",
                      dropdownParent: $("#form_document_edit"),
                      templateResult: format_project_dropdown
                    })

                    $("#client_payment_work_edit_invoice").select2({
                      placeholder: "Select Work",
                      dropdownParent: $("#form_client_payment_edit_invoice"),
                      templateResult: format_project_dropdown
                    })

                    $("#client_payment_acc_edit_invoice").select2({
                      placeholder: "Select Credit Account",
                      dropdownParent: $("#form_client_payment_edit_invoice")
                    })

                    $("#client_payment_received_date_add,#client_payment_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>'
                      }
                    })

                    function GetSearchInvoicework() {
                      return $('#table_filter_invoice_work').val();
                    }

                    function GetSearchDate() {
                      return $('#table_filter_date_range').val();
                    }


                    <?php if ($page_name == 'invoices_view') { ?>
                      // Date Range Picker
                      var start = moment();
                      var end = moment();

                      function cb(start, end) {
                        $('#table_filter_date_range').val(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
                        invoices_view_table.ajax.reload();
                        // invoice_payments_view_table.ajax.reload();
                      }

                      $('#table_filter_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: {

                          },
                          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");
                              invoice_payments_view_table.ajax.reload();
                              invoices_view_table.ajax.reload();

                              // $("#"+modal_id).modal('toggle');
                            } 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 } ?>
                    $(".table_filter").on("change", function() {
                      invoices_view_table.ajax.reload();
                    });
                    $(".hide_column").hide();
                    </script>
