<?php $this->view("includes/Inc_pagehead");?>
<!-- Page Styles Goes Here-->

<?php $this->view("includes/Inc_navigation");?>
<div class="m-grid__item m-grid__item--fluid m-wrapper">
  <!-- BEGIN: Subheader -->
  <div class="m-subheader">
    <div class="d-flex align-items-center">
      <div class="mr-auto">
        <h3 class="m-subheader__title m-subheader__title--separator">
          Data Entry Approval - Bulk
        </h3>
        <ul class="m-subheader__breadcrumbs m-nav m-nav--inline">
          <li class="m-nav__item m-nav__item--home">
            <a href="#" class="m-nav__link m-nav__link--icon">
              <i class="m-nav__link-icon la la-home"></i>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo base_url().'dashboard'?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Home
              </span>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo base_url().'user/data_approval_bulk' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Data Entry Approval - Bulk
              </a>
            </li>
          </ul>
        </div>
        <div>

        </div>
      </div>
    </div>
    <!-- END: Subheader -->
    <div class="m-content">
      <div class="m-portlet  m-portlet--rounded m-portlet--bordered">
        <div class="m-portlet__body" style="padding: 1rem 2.2rem;">
          <div class="m-form m-form--label-align-right m--margin-bottom-10">
            <div class="row ">
              <div class="col-md-3">
                <div class="m-form__label">
                  <label class="m-label m-label--single">
                    Date:
                  </label>
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="m-form__control">
                      <input data-date-format="dd-mm-yyyy" value="<?php echo date('d-m-Y')?>" id="table_filter_start_date" type="text"  class="form-control m-input table_filter  m-input--pill m-input--air" placeholder="Start Date" >
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="m-form__control">
                      <input data-date-format="dd-mm-yyyy" value="<?php echo date('d-m-Y')?>" id="table_filter_end_date" type="text"  class="form-control m-input table_filter  m-input--pill m-input--air" placeholder="End Date" >
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-3">
                <div class="form-group m-form__group">
                  <label>
                    Work:
                  </label>
                  <div class="m-select2 m-select2--air m-select2--pill">
                    <select style="width: 100%" class="form-control m-select2 table_filter" id="table_filter_work" >
                      <option value="all">All Works</option>
                      <?php
                      foreach($work_contracts as $row): ?>
                      <option data-work-status="<?php echo $row->work_status?>" value="<?php echo $row->work_id?>"><?php echo $row->work_name?></option>
                      <?php
                    endforeach;
                    ?>
                  </select>
                </div>
                <span class="m-form__help">(Labour Payment & Travel Allowance are Not Applicable)</span>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group m-form__group">
                <label>
                  Created User :
                </label>
                <div class="m-select2 m-select2--air m-select2--pill">
                  <select style="width: 100%" class="form-control m-select2 table_filter" id="table_filter_user"  name="" data-placeholder="Select Tool">
                    <option selected value="all">All</option>
                    <?php foreach($users as $row) { ?>
                      <option value="<?php echo $row->user_id ?>"><?php echo $row->user_alias ?></option>
                    <?php } ?>
                  </select>
                </div>
                <span class="m-form__help"></span>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group m-form__group">
                <label>
                  Approval Status :
                </label>
                <div class="m-select2 m-select2--air m-select2--pill">
                  <select style="width: 100%" class="form-control m-select2 table_filter" id="table_filter_approval_status"  name="" data-placeholder="Select Approval Type">
                    <option selected value="all">All Data</option>
                    <option value="0">Pending</option>
                    <option value="1">Approved</option>
                    <option value="2">Rejected</option>
                  </select>
                </div>
                <span class="m-form__help"></span>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group m-form__group">
                <label>
                  Debited/Credited Account :
                </label>
                <div class="m-select2 m-select2--air m-select2--pill">
                  <select style="width: 100%" class="form-control m-select2 table_filter" id="table_filter_account"  name="" data-placeholder="Select Account">
                    <option selected value="all">All Accounts</option>
                    <?php
                    foreach($this->config->item('account_heads') as $row): ?>
                    <option value="<?php echo $row->acc_head_id?>"><?php echo $row->acc_head_name?></option>
                    <?php
                  endforeach;
                  ?>
                </select>
              </div>
              <span class="m-form__help">Some Tables are Not Applicable</span>
            </div>
          </div>
          <div class="col-md-6"></div>
          <div class="col-md-3">
            <?php if($this->session->userdata('user_role')=='admin'){ ?>
              <div class="dropdown" style="float:right;margin-top:25px">
                <button class="btn btn-focus m-btn--pill m-btn--air dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  Bulk Action
                </button>
                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" x-placement="top-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(0px, -125px, 0px);">
                  <a class="dropdown-item btn_status_change" style="margin-bottom:5px;background:green;color:white" data-type='approve' href="javascript:;"><i class="fa fa-check-circle"></i> Approve</a>
                  <a class="dropdown-item btn_status_change" style="background:red;color:white" data-type='reject' href="javascript:;"><i class="fa fa-times-circle"></i> Reject</a>
                </div>
              </div>
            <?php } ?>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="m-portlet m-portlet--mobile m-portlet--info m-portlet--head-solid-bg m-portlet--bordered m-portlet--rounded">
    <div class="m-portlet__head">
      <div class="m-portlet__head-caption">
        <div class="m-portlet__head-title">
          <h3 class="m-portlet__head-text">
            List of Entries
          </h3>
        </div>
      </div>
    </div>
    <div class="m-portlet__body">
      <table width="100%" class="table m-table nowrap table-header-fixed table-striped table-bordered table-hover table-header-fixed" id="entries_view_table">
        <thead>
          <tr class="">
            <th style="padding-left: 10px"><input name="select_all" value="1" type="checkbox"></th>
            <th>Sl No</th>
            <th>Entry Type</th>
            <th>Entry ID</th>
            <th>Entry Date</th>
            <th>Entry Details</th>
            <th>Amount Details</th>
            <th>Transaction Details</th>
            <th>Project/Location</th>
            <th>Remarks</th>
            <th>Created By</th>
            <th>Created On</th>
            <th>Actions</th>
            <th>Approval</th>
          </tr>
        </thead>
        <tbody id="table_body">
        </tbody>
      </table>
    </div>
  </div>

</div>
<?php if($this->config->item('Mobile_App_enable_data_entry_approval')==1){?>
  <div class="modal fade"  tabindex="-1" id="status_edit_modal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog " role="document" >
      <form autocomplete="off" method="post" data-modal-id="status_edit_modal" id="form_status_edit" action="<?php echo base_url().'user/data_entry_approval_bulk'?>" class="form-horizontal form_submit">
        <div class="modal-content">
          <div class="alert" id="status_edit_modal_alert" role="alert" style="margin-bottom: 0px">
            <button type="button" class="close" data-dismiss="modal"></button>
            <br/>
            <h4 class="alert-heading">Warning! Please Confirm Your Action</h4>
            <br/>
            <p id="status_edit_modal_alert_text">  </p>
            <div class="m-form__content" style="background: #707070; padding: 20px; margin-bottom: 20px;">
            <div class="row">
              <div class="col-lg-6" >
                <div class="form-group m-form__group" >
                  <label for="user_name">
                    No of Entries Selected
                  </label>
                  <input disabled type="text" id="entries_count" class="form-control m-input m-input--solid m-input--pill m-input--air"  aria-describedby="basic-addon1">
                  <span class="m-form__help"></span>
                </div>
              </div>
            </div>
          </div>
          <p>
            <button class="btn btn-danger form_submit_btn"  type="submit" name="submit">Confirm & Proceed</button>
            <button type="button" class="btn btn-primary modal-dismiss" data-dismiss="modal">Cancel</button>
          </p>
          <input type="hidden"  name="entry_ids[]" id="entry_id_status_edit">
          <input type="hidden" name="redirect_url" value="<?php echo base_url(uri_string())?>" >
          <input type="hidden"  name="action_type" id="action_type_status_edit">
        </div>
      </div>
    </form>
  </div>
</div>
<div class="modal fade"  tabindex="-1" id="data_entry_approve_modal" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog " role="document" >
    <form autocomplete="off" method="post" data-modal-id="data_entry_approve_modal" id="form_data_entry_approve" action="<?php echo base_url().'user/data_entry_approval'?>" class="form-horizontal">
      <div class="modal-content">
        <div class="alert alert-info" role="alert" style="margin-bottom: 0px">
          <button type="button" class="close" data-dismiss="modal"></button>
          <br/>
          <h4 class="alert-heading">Warning! Please Confirm Your Action</h4>
          <br/>
          <div class="alert m-alert--default" role="alert" style="margin-bottom: 10px">
            <div class="form-group m-form__group" >
              <label for="user_name" style="color: black">Approval Status</label>
              <div class="m-radio-inline" style="padding-top: 10px;">
                <label class="m-radio m-radio--solid m-radio--state-success">
                  <input required type="radio" class="form_fields_radio"  name="data_entry_approval" value="1"> Approved
                  <span></span>
                </label>
                <label class="m-radio m-radio--solid m-radio--state-danger">
                  <input type="radio" class="form_fields_radio" name="data_entry_approval"  value="2"> Rejected
                  <span></span>
                </label>
              </div>
              <span class="m-form__help"></span>
            </div>
          </div>
          <p>
            <button class="btn btn-danger form_submit_btn" type="submit" name="submit">Confirm & Proceed</button>
            <button type="button" class="btn btn-primary modal-dismiss" data-dismiss="modal">Cancel</button>
          </p>
          <input type="hidden" name="data_id" id="data_id_appoval">
          <input type="hidden" name="data_type" id="data_type_appoval">
        </div>
      </div>
    </form>
  </div>
</div>
<?php } ?>

</div>
</div>
<!-- end:: Body -->
<!-- begin::Footer -->
<?php $this->view("includes/Inc_footer");?>
<!-- end::Footer -->
</div>
<!-- end:: Page -->

<?php $this->view("includes/Inc_sidebar");?>
<?php $this->view("includes/Inc_scripts");?>

<!--begin::Page Snippets -->
<script>
$("#user_data_entry_bulk_menu").addClass('m-menu__item--active m-menu__item--open');
$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");

$("#table_filter_work").select2({
  placeholder: "Select Project"
})
$("#table_filter_user").select2({
  placeholder: "Select User"
})
$("#table_filter_account").select2({
  placeholder: "Select Account"
})
$("#table_filter_approval_status").select2({
  placeholder: "Select Approval Status"
})
$("#table_filter_start_date,#table_filter_end_date").datepicker( {
  todayHighlight:!0, orientation:"bottom left", templates: {
    leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
  }
})

$('body').on('change', '#table_filter_work', function() {
  var work = $("#table_filter_work").val();
  if(work!='all'){
    $("#div_labour_wage_payments").hide();
    $("#div_travel_allowance").hide();
  }else{
    $("#div_labour_wage_payments").show();
    $("#div_travel_allowance").show();
  }
})


$('body').on('click', '#btn_data_entry_approval', function() {
  var no = $(this).closest('tr').children('td');
  $('#data_id_appoval').val($(this).data('id'));
  $('#data_type_appoval').val($(this).data('type'));
  var approval_status = $(this).data('approval-status');
  if(approval_status!=0){
    $('input[type=radio][name=data_entry_approval][value='+approval_status+']').prop('checked',true);
  }else{
    $('.form_fields_radio').prop('checked',false);
  }

})
</script>

<script>

<?php if($page_name=='data_entry_approval_bulk'){?>
  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_bulk'){
    $page_type='approval_entries';
  }
  ?>
  var rows_selected = [];

  function updateDataTableSelectAllCtrl(table){
    var $table             = table.table().node();
    var $chkbox_all        = $('tbody input[type="checkbox"]', $table);
    var $chkbox_checked    = $('tbody input[type="checkbox"]:checked', $table);
    var chkbox_select_all  = $('thead input[name="select_all"]', $table).get(0);

    // If none of the checkboxes are checked
    if($chkbox_checked.length === 0){
      chkbox_select_all.checked = false;
      if('indeterminate' in chkbox_select_all){
        chkbox_select_all.indeterminate = false;
      }

      // If all of the checkboxes are checked
    } else if ($chkbox_checked.length === $chkbox_all.length){
      chkbox_select_all.checked = true;
      if('indeterminate' in chkbox_select_all){
        chkbox_select_all.indeterminate = false;
      }

      // If some of the checkboxes are checked
    } else {
      chkbox_select_all.checked = true;
      if('indeterminate' in chkbox_select_all){
        chkbox_select_all.indeterminate = true;
      }
    }
  }
  var table = $('#entries_view_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'user/select_data_entry_approval_data/'.$page_type ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        <?php if($page_name=='data_entry_approval_bulk'){?>
          d.start_date = GetStartDate();
          d.end_date = GetEndDate();
          d.work = GetSearchWork();
          d.approval_status = GetSearchApprovalStatus();
          d.created_by = 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: 'Account Transfer Report' },
        { 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>>",
      "lengthMenu": [
        [25, 50, 100, -1],
        [25, 50, 100, "All"] // change per page values here
      ],
      // set the initial value
      "pageLength": 25,
      "columnDefs": [
        {
          'targets': 0,
          'searchable': false,
          'orderable': false,
          'width': '1%',
          'className': 'dt-body-center',
          'render': function (data, type, full, meta){
            return '<input type="checkbox">';
          }
        },
        {
          "targets": [13],
          className: "hidden"
        }
      ],
      'order': [0,'asc'],
      'rowCallback': function(row, data, dataIndex){
        if(data[13]=='0'){
          $('td', row).css('background-color', '#ffcccc');
        }else if(data[13]=='2'){
          $('td', row).css('background-color', '#ffcccc');
        }
        // Get row ID
        var rowId = data[0];

        // If row ID is in the list of selected row IDs
        if($.inArray(rowId, rows_selected) !== -1){
          $(row).find('input[type="checkbox"]').prop('checked', true);
          $(row).addClass('selected');
        }
      },
      // "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
      //
      // }
    });

    $('#entries_view_table tbody').on('click', 'input[type="checkbox"]', function(e){
      var $row = $(this).closest('tr');
      // Get row data
      var data = table.row($row).data();

      // Get row ID
      var rowId = data[0];

      // Determine whether row ID is in the list of selected row IDs
      var index = $.inArray(rowId, rows_selected);

      // If checkbox is checked and row ID is not in list of selected row IDs
      if(this.checked && index === -1){
        rows_selected.push(rowId);
        // Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
      } else if (!this.checked && index !== -1){
        rows_selected.splice(index, 1);
      }

      if(this.checked){
        $row.addClass('selected');
      } else {
        $row.removeClass('selected');
      }

      // Update state of "Select all" control
      updateDataTableSelectAllCtrl(table);

      // Prevent click event from propagating to parent
      e.stopPropagation();
    });

    // Handle click on table cells with checkboxes
    $('#entries_view_table').on('click', 'tbody td, thead th:first-child', function(e){
      $(this).parent().find('input[type="checkbox"]').trigger('click');
    });

    // Handle click on "Select all" control
    $('thead input[name="select_all"]', table.table().container()).on('click', function(e){
      if(this.checked){
        $('#entries_view_table tbody input[type="checkbox"]:not(:checked)').trigger('click');
      } else {
        $('#entries_view_table tbody input[type="checkbox"]:checked').trigger('click');
      }

      // Prevent click event from propagating to parent
      e.stopPropagation();
    });

    // Handle table draw event
    table.on('draw', function(){
      // Update state of "Select all" control
      updateDataTableSelectAllCtrl(table);
    });

    $(".table_filter").on("change", function() {
      table.ajax.reload();
    });
    $(".hide_column").hide();

    $('body').on('click', '.btn_status_change', function() {
      var arr=new Array();
      $.each(rows_selected, function(index, rowId){
        arr.push(rowId)
      });
      if(arr=="")
      {
        toastr["warning"]("Please Select Entries to Continue", "Selection Empty");
      }
      else{
        var action_type = $(this).attr('data-type');
        if(action_type=='approve'){
          $("#status_edit_modal_alert").addClass('alert-success');
          $("#status_edit_modal_alert_text").text("You Are Going to Approve Selected Bills/Transaction Entries.!");
        }else{
          $("#status_edit_modal_alert").addClass('alert-danger');
          $("#status_edit_modal_alert_text").text("You Are Going to Reject Selected Bills/Transaction Entries.!");
        }
        $("#action_type_status_edit").val(action_type);
        $("#entry_id_status_edit").val(arr);
        $("#entries_count").val(arr.length);
        $("#status_edit_modal").modal('toggle');
      }
    })

    $(".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: {
          received_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,
        beforeSend: function(){
          // Handle the beforeSend event
          // Block UI
          mApp.blockPage({
            overlayColor: "#000000",
            type: "loader",
            state: "success",
            message: "Please wait..."
          });

          mApp.block(".modal-content", {
            overlayColor: "#000000",
            type: "loader",
            state: "success",
            message: "Please wait..."
          });
        },

        success: function (e, t, r, s) {
          // UnBlock UI

          var modal_id = l.attr('data-modal-id');
          var form_type = l.attr('data-form-type');
          $("#" + form_id + "_msg").addClass("m--hide");


          var obj = $.parseJSON(e);
          if (obj.status == 1) {
            a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
            $("#"+modal_id).modal('toggle');
            $("."+form_id+"_fields").val('');
            $("."+form_id+"_select").val('').trigger("change");
            $(".custom-file-label").text('');
            toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
            table.ajax.reload();
            $('#entries_view_table tbody input[type="checkbox"]:checked').trigger('click');
            location.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");
        },ajaxComplete : function(){
          mApp.unblockPage();
          mApp.unblock(".modal-content");
        },complete  : function(){
          mApp.unblockPage();
          mApp.unblock(".modal-content");
        },
      })
    )
  });
  $('#entries_view_table').DataTable().clear().draw();

</script>
