<script>
<?php if($page_name=='vehicle_expenses'){?>
  $("#table_filter_vehicle").select2({
    placeholder: "Select Vehicle"
  })
  $("#table_filter_expense_type").select2({
    placeholder: "Select  Expense Head"
  })
  $("#table_filter_expense_head").select2({
    placeholder: "Select  Expense Head"
  })
  <?php } ?>
  $("#vehicle_expense_paid_date_add,#vehicle_expense_paid_date_edit,#vehicle_expense_reference_date_add,#vehicle_expense_date_add").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('change', '#vehicle_expense_payment_mode_add', function() {
      var payment_mode=$('#vehicle_expense_payment_mode_add :selected').val();
      if(payment_mode=='POST DATED CHEQUE'){
        $('#vehicle_expense_paid_date_add').datepicker('destroy');
        $("#vehicle_expense_paid_date_add").datepicker( {
          todayHighlight:!0, orientation:"bottom left", templates: {
            leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
          },
          <?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 } ?>
          })
      }else{
        $('#vehicle_expense_paid_date_add').datepicker('destroy');
        $("#vehicle_expense_paid_date_add").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 } ?>
          })
      }
    })
    function select_expense_head(select_id,type=''){
      $('#'+select_id).html('');
      if(type=='filter'){
        $("#"+select_id).append("<option value='all' selected >All Expense Heads</option>");
      }else{
        $("#"+select_id).append("<option disabled selected >Select Expense Head</option>");
      }
      $.post("<?php echo base_url() ?>accounts/select_heads_2",{account_type:11},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#"+select_id).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            i++;
          }
        }
      })
    }

    select_expense_head("table_filter_expense_head",'filter');
    select_expense_head("expense_head_add");
    select_expense_head("expense_head_edit");

    $("#expense_vehicle_add").select2({
      placeholder: "Select Vehicle",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#expense_vehicle_supplier_add").select2({
      placeholder: "Select Supplier",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#expense_head_add").select2({
      placeholder: "Select Expense Head",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#vehicle_expense_tax_percent_add").select2({
      placeholder: "Select Tax %",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#vehicle_expense_debit_acc_add").select2({
      placeholder: "Select Debit Account",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#vehicle_expense_payment_mode_add").select2({
      placeholder: "Select Debit Account",
      dropdownParent: $("#form_vehicle_expense_add")
    })
    $("#vehicle_expense_work_add").select2({
      placeholder: "Select Work",
      dropdownParent: $("#form_vehicle_expense_add"),
      templateResult: format_project_dropdown
    })

    $("#expense_vehicle_supplier_edit").select2({
      placeholder: "Select Supplier",
      dropdownParent: $("#form_vehicle_expense_edit")
    })
    $("#expense_vehicle_edit").select2({
      placeholder: "Select Vehicle",
      dropdownParent: $("#form_vehicle_expense_edit")
    })
    $("#vehicle_expense_work_edit").select2({
      placeholder: "Select Work",
      dropdownParent: $("#form_vehicle_expense_edit"),
      templateResult: format_project_dropdown
    })
    $("#vehicle_expense_tax_percent_edit").select2({
      placeholder: "Select Tax %",
      dropdownParent: $("#form_vehicle_expense_edit")
    })
    $("#vehicle_expense_debit_acc_edit").select2({
      placeholder: "Select Debit Account",
      dropdownParent: $("#form_vehicle_expense_edit")
    })
    $("#expense_head_edit").select2({
      placeholder: "Select Expense Head",
      dropdownParent: $("#form_vehicle_expense_edit")
    })

    <?php if($page_name=='work_profile'){?>
      var work_id = "<?php echo $work_data->work_id ?>";
      $("#vehicle_expense_work_add").val(work_id).trigger('change');
      $("#vehicle_expense_work_div_add").show();
      $("#vehicle_expense_work_add").attr('required',true);

      $("#vehicle_expense_work_edit").val(work_id).trigger('change');
      $("#vehicle_expense_work_div_edit").show();
      $("#vehicle_expense_work_edit").attr('required',true);
      <?php } ?>
      $('input[type=radio][name=expense_type]').change(function() {
        if (this.value == 'work') {
          $("#vehicle_expense_work_div_add").show();
          $("#vehicle_expense_work_add").attr('required',true);
        }else{
          $("#vehicle_expense_work_div_add").hide();
          $("#vehicle_expense_work_add").removeAttr('required',true);
        }
      });
      $('input[type=radio][name=expense_type_edit]').change(function() {
        if (this.value == 'work') {
          $("#vehicle_expense_work_div_edit").show();
          $("#vehicle_expense_work_edit").attr('required',true);
        }else{
          $("#vehicle_expense_work_div_edit").hide();
          $("#vehicle_expense_work_edit").removeAttr('required',true);
        }
      });
      function calculate_vehicle_expense_balance(form_type=''){
        if(form_type=='edit'){
          var tax_percent = parseFloat($('#vehicle_expense_tax_percent_edit :selected').val());
          var bill_amount = parseFloat(($("#vehicle_expense_amount_edit").val()=='') ? 0 : parseFloat($("#vehicle_expense_amount_edit").val()));
          var tax_amount = bill_amount*tax_percent/100;
          $("#vehicle_expense_tax_amount_edit").val(tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          var payable_amount = parseFloat(bill_amount+tax_amount);
          $("#vehicle_expense_payable_amount_edit").val(payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          var paid_amount = ($("#vehicle_expense_total_paid_edit").val()=='') ? 0 : parseFloat($("#vehicle_expense_total_paid_edit").val());
          $("#vehicle_expense_balance_edit").val((payable_amount-paid_amount).toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
        }else{
          var tax_percent = parseFloat($('#vehicle_expense_tax_percent_add :selected').val());
          var bill_amount = parseFloat(($("#vehicle_expense_amount_add").val()=='') ? 0 : parseFloat($("#vehicle_expense_amount_add").val()));
          var tax_amount = bill_amount*tax_percent/100;
          $("#vehicle_expense_tax_amount_add").val(tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          var payable_amount = parseFloat(bill_amount+tax_amount);
          $("#vehicle_expense_payable_amount_add").val(payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          var paid_amount = ($("#vehicle_expense_paid_amount_add").val()=='') ? 0 : parseFloat($("#vehicle_expense_paid_amount_add").val());
          $("#vehicle_expense_balance_amount_add").val((payable_amount-paid_amount).toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
        }
      }
      $('body').on('change keyup', '#vehicle_expense_paid_amount_add', function() {
        var value = $(this).val();
        // if(value=="" || value==null){
        //   $(this).val(0)
        // }
        if($(this).val()>0){
          $(".vehicle_expense_paid_amount_req_fields").attr('required',true);
        }else{
          $(".vehicle_expense_paid_amount_req_fields").removeAttr('required',true);
        }
        calculate_vehicle_expense_balance('add');
      })
      $('body').on('change keyup', '.vehicle_expense_amount_fields_add', function() {
        var value = $(this).val();
        // if(value=="" || value==null){
        //   $(this).val(0);
        // }
        calculate_vehicle_expense_balance('add');
        $("#vehicle_expense_paid_amount_add").val($('#vehicle_expense_payable_amount_add').val());
        $("#vehicle_expense_paid_amount_add").attr('max',$('#vehicle_expense_payable_amount_add').val());
        if($("#vehicle_expense_paid_amount_add").val()>0){
          $(".vehicle_expense_paid_amount_req_fields").attr('required',true);
        }else{
          $(".vehicle_expense_paid_amount_req_fields").removeAttr('required',true);
        }
      })
      $('body').on('change keyup', '#vehicle_expense_date_add', function() {
        $("#vehicle_expense_paid_date_add").datepicker("setDate",$(this).val());
      })

      $('body').on('change keyup', '.vehicle_expense_amount_fields_edit', function() {
        var value = $(this).val();
        // if(value=="" || value==null){
        //   $(this).val(0)
        // }
        calculate_vehicle_expense_balance('edit');
      })
      $('body').on('click', '#vehicle_expense_edit_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#vehicle_expense_id_edit').val(no.eq(24).text());
        $('#vehicle_expense_date_edit').datepicker("setDate", no.eq(2).text());
        $('#expense_vehicle_edit').val(no.eq(23).text()).trigger('change');
        $('#vehicle_expense_no_edit').val(no.eq(7).text());
        $('#vehicle_expense_consignee_edit').val(no.eq(8).text());
        $('#vehicle_expense_payable_amount_edit').val(no.eq(11).text());
        $('#vehicle_expense_description_edit').val(no.eq(15).text());
        $('#vehicle_expense_remarks_edit').val(no.eq(16).text());
        $('#expense_head_edit').val(no.eq(22).text()).trigger('change');
        $('#vehicle_expense_total_paid_edit').val(no.eq(12).text());
        $('#vehicle_expense_balance_edit').val(no.eq(13).text());
        $('#vehicle_expense_tax_percent_edit').val(no.eq(26).text()).trigger('change');
        $('#expense_vehicle_supplier_edit').val(no.eq(28).text()).trigger('change');
        var expense_type=no.eq(4).text();
        $("input[name=expense_type_edit][value=" + expense_type + "]").prop('checked', true);
        var tax_amount=parseFloat(no.eq(27).text());
        var payable_amount=parseFloat(no.eq(11).text());
        var bill_amount = parseFloat(payable_amount-tax_amount);
        $('#vehicle_expense_amount_edit').val(bill_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
        var file = no.eq(25).text();
        if(file!=''){
          var file_data='<tr>'+
          '<td><a style="word-break: break-all" target="_blank" href="'+file+'" style="margin-left: 5px;margin-right: 5px" >'+file+'</a></td>'+
          '<td><a style="margin-left: 5px;margin-right: 5px" id="vehicle_expense_attachment_item_delete_btn" href="javascript:;" class="btn btn-sm btn-danger m-btn m-btn--icon  m-btn--pill m-btn--air"><i class="la la-trash"></i> Change</a></td>'+
          '</tr>';
          $("#vehicle_expense_edit_file_table_body").html(file_data);
          $("#vehicle_expense_edit_file_table").show();
          $("#vehicle_expense_edit_file_upload").hide();
        }else{
          $("#vehicle_expense_edit_file_table").hide();
          $("#vehicle_expense_edit_file_upload").show();
        }
        calculate_vehicle_expense_balance('edit');
      })
      $('body').on('click', '#vehicle_expense_attachment_item_delete_btn', function() {
        $("#vehicle_expense_edit_file_table").hide();
        $("#vehicle_expense_edit_file_upload").show();
        $("#vehicle_expense_attachment_delete_status").val(1);
      })

      <?php if($page_name=='vehicle_expenses'){?>
        function GetSearchStatus(){
          return $('#table_filter_status').val();
        }
        function GetSearchexpensehead(){
          return $('#table_filter_expense_head').val();
        }
        function GetSearchexpensetype(){
          return $('#table_filter_expense_type').val();
        }
        function GetSearchDate(){
          return $('#table_filter_date_range').val();
        }
        function GetSearchVehicle(){
          return $('#table_filter_vehicle').val();
        }
        <?php } ?>
        <?php if($page_name=='user_profile'){?>
          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 vehicle_expenses_view_table = $('#vehicle_expenses_view_table').DataTable({
            "ajax":{
              url :"<?php echo base_url().'vehicles/select_vehicle_expenses/'.$page_type ?>", // json datasource
              type: "post", // type of method  , by default would be get
              data: function(d){
                <?php if($page_name=='vehicle_expenses'){?>
                  d.date = GetSearchDate();
                  d.expense_head = GetSearchexpensehead();
                  d.expense_type = GetSearchexpensetype();
                  d.vehicle_id = GetSearchVehicle();
                  <?php } ?>
                  <?php if($page_name=='data_entry_approval'){?>
                    d.start_date = GetStartDate();
                    d.end_date = GetEndDate();
                    d.work = GetSearchWork();
                    d.approval_status = GetSearchApprovalStatus();
                    d.user_id = GetSearchUser();
                    <?php } ?>
                  <?php if($page_name=='vehicle_profile') { ?>
                    d.vehicle_id = <?= $vehicle_data->id ?>;
                    <?php } ?>
                    <?php if($page_name=='supplier_profile'){?>
                      d.bill_supplier_id = "<?php echo $supplier_data->supplier_id?>";
                      <?php } ?>
                    <?php if($page_name=='reports_activity'){?>
                      d.date = GetSearchDate();
                      <?php } ?>
                      <?php if($page_name=='user_profile'){?>
                        d.user_id = "<?php echo $user_data->user_id?>";
                        d.start_date = GetStartDate();
                        d.end_date = GetEndDate();
                        <?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',exportOptions: {columns: ':visible'},title: 'Vehicle Expenses' },
                          { 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 } ?>
                        'order': false,
                        "columnDefs": [
                          {
                            "targets": [ 22,23,24,25,26,27,28,29<?php if($page_name=='work_profile'){ echo ",3,18"; }?><?php if($page_name=='work_summary'){ echo ",3,14,15,16,17,18,21"; }?><?php if($page_name=='reports_activity'){ echo ",21"; }?> <?php if($this->session->userdata('user_role')=='auditor' && $this->session->userdata('user_data_permission')['adding']!=1) { echo ",21"; } ?>],
                            className: "hidden"
                          }
                        ],
                        "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                          if(aData[29]=='0'){
                            $('td', nRow).css('background-color', '#ffcccc');
                          }else if(aData[29]=='2'){
                            $('td', nRow).css('background-color', '#ffcccc');
                          }
                        }
                      });
                      $(".table_filter").on("change", function() {
                        vehicle_expenses_view_table.ajax.reload();
                      });
                      $(".hide_column").hide();

                      <?php if($page_name=='vehicle_expenses'){?>
                        // 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'));
                          vehicle_expenses_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: {
                              paid_amount: {
                                number: !0,
                                required: !0
                              },
                              bill_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");
                                // $("#"+form_id).trigger("reset");
                                // $("#"+form_id)[0].reset();
                                // $("#"+form_id).get(0).reset();
                                $(".custom-file-label").text("Choose file");
                                $('input[type=radio]').prop('checked', false);
                                $("#vehicle_expense_work_div_add").hide();
                                $("#vehicle_expense_work_add").removeAttr('required',true);
                                if(form_id=="form_expense_head_add"){
                                  select_expense_head("expense_head_add");
                                  select_expense_head("expense_head_edit");
                                  select_expense_head("table_filter_expense_head",'filter');
                                }else{
                                  vehicle_expenses_view_table.ajax.reload();
                                }
                              } 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>
