<script type="text/javascript">
$("#table_filter_beneficiary_work").select2({
  placeholder: "Select  Project",
  templateResult: format_project_dropdown
})
$("#table_filter_beneficiary_subcontract").select2({
  placeholder: "Select Subcontract",
  // dropdownParent: $("#form_vehicle_work_slip_add")
})
$("#table_filter_beneficiary_supervisor").select2({
  placeholder: "Select Supervisor",
  // dropdownParent: $("#form_vehicle_work_slip_add")
})
$("#meter_make_add").select2({
  placeholder: "Select Sale Price",
  dropdownParent: $("#form_beneficiary_add")
})
$("#meter_make_edit").select2({
  placeholder: "Select Sale Price",
  dropdownParent: $("#form_beneficiary_edit")
})
$('body').on('change', '#table_filter_beneficiary_work', function() {
  var work_id = $("#table_filter_beneficiary_work option:selected").val();
  select_subcontracts("table_filter_beneficiary_subcontract",'',work_id);
  select_users('table_filter_beneficiary_supervisor','','supervisor',work_id);
})


$("#project_add_beneficiary").select2({
  dropdownParent: $("#form_beneficiary_add"),
  placeholder: "Select Project",
  templateResult: format_project_dropdown
})
$("#subcontract_add_beneficiary").select2({
  placeholder: "Select Subcontract",
  dropdownParent: $("#form_beneficiary_add")
})
$("#supervisor_add_beneficiary").select2({
  placeholder: "Select Supervisor",
  dropdownParent: $("#form_beneficiary_add")
})
$("#project_edit_beneficiary").select2({
  dropdownParent: $("#form_beneficiary_edit"),
  placeholder: "Select Project",
  templateResult: format_project_dropdown
})
$("#subcontract_edit_beneficiary").select2({
  placeholder: "Select Subcontract",
  dropdownParent: $("#form_beneficiary_edit")
})
$("#supervisor_edit_beneficiary").select2({
  placeholder: "Select Supervisor",
  dropdownParent: $("#form_beneficiary_edit")
})
function select_subcontracts(select_id,selected_value='',project,select_type=''){
  $('#'+select_id).html('');
  if(select_type=='filter'){
    $('#'+select_id).append("<option value='all' selected >All Subcontracts</option>");
  }else{
    $('#'+select_id).append("<option disabled selected >Select Subcontract</option>");
  }
  if(project!='' && project!=null && project!='Select Project'){
    $.post("<?php echo base_url() ?>subcontracts/select_subcontracts_list",{work:project},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]['contract_id'] + ">" + obj.data[i]['sub_work_name'] + " [" + obj.data[i]['contractor_name'] + " - " + obj.data[i]['contractor_phone'] + "]</option>");
          i++;
        }
        if(selected_value!=''){
          $("#"+select_id).val(selected_value).trigger("change");
        }
      }
    })
  }
}

<?php if($page_name=='project_beneficiary_accounts'){?>
$('body').on('change', '#project_add_beneficiary', function() {
  var work_id = $("#project_add_beneficiary option:selected").val();
  select_subcontracts("subcontract_add_beneficiary",'',work_id);
  select_users('supervisor_add_beneficiary','','supervisor',work_id);
})
$('body').on('change', '#project_edit_beneficiary', function() {
  var work_id = $("#project_edit_beneficiary option:selected").val();
  select_subcontracts("subcontract_edit_beneficiary",'',work_id);
  select_users('supervisor_edit_beneficiary','','supervisor',work_id);
})
<?php } ?>
<?php if ($page_name == 'work_profile') { ?>
  var work_id = "<?php echo $work_data->work_id ?>";
  select_subcontracts("subcontract_add_beneficiary",'',work_id);
  select_users('supervisor_add_beneficiary','','supervisor',work_id);
  select_subcontracts("subcontract_edit_beneficiary",'',work_id);
  select_users('supervisor_edit_beneficiary','','supervisor',work_id);
  <?php } ?>
function select_users(select_id,branch_id='',user_role='',project='',selected_value='',select_type=''){
  $('#'+select_id).html('');
  if(select_type=='filter'){
    $('#'+select_id).append("<option value='all' selected >All Supervisor</option>");
  }else{
    $('#'+select_id).append("<option disabled selected >Select Supervisor</option>");
  }
  $.post("<?php echo base_url() ?>work/select_assigned_users/select",{work_id:project},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++;
      }
      if(selected_value!=''){
        $("#"+select_id).val(selected_value).trigger("change");
      }
    }
  })

}
</script>
<script>
$('body').on('click', '#beneficiary_edit_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#beneficiary_id_edit').val($(this).data('id'));

  $('#beneficiary_name_edit').val(no.eq(3).text());
  $('#guardian_name_edit').val(no.eq(4).text());
  $('#ward_no_edit').val(no.eq(6).text());
  $('#house_no_edit').val(no.eq(7).text());
  $('#street_name_edit').val(no.eq(8).text());
  $('#beneficiry_address_edit').val(no.eq(5).text());
  $('#landmark_edit').val(no.eq(9).text());
  $('#beneficiry_phone_no_edit').val(no.eq(10).text());
  $('#aadhar_no_edit').val(no.eq(11).text());
  $('#meter_no_edit').val(no.eq(13).text());
  $('#kwa_approval_no_edit').val(no.eq(14).text());
  $('#road_cutting_concrete_edit').val(no.eq(17).text());
  $('#additional_pipe_edit').val(no.eq(18).text());
  $('#other_measurements_edit').val(no.eq(19).text());
  $('#beneficiary_remarks_edit').val(no.eq(20).text());
  $('#meter_make_edit').val(no.eq(24).text()).trigger('change');
  $('#project_edit_beneficiary').val(no.eq(23).text()).trigger('change');
  select_subcontracts("subcontract_edit_beneficiary",no.eq(25).text(),work_id);
  select_users('supervisor_edit_beneficiary','','supervisor',work_id,no.eq(26).text());
})
$('body').on('click', '#beneficiary_delete_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#beneficiary_id_delete').val($(this).data('id'));
})
</script>
<script>
<?php if($page_name=='project_beneficiary_accounts'){?>
function GetSearchwork() {
  return $('#table_filter_beneficiary_work').val();
}
function GetSearchSubcontract() {
  return $('#table_filter_beneficiary_subcontract').val();
}
function GetSearchsupervisor() {
  return $('#table_filter_beneficiary_supervisor').val();
}
function GetSearchwardno() {
  return $('#table_filter_beneficiary_wardno').val();
}
$('body').on('click', '#btn_print_list', function() {
  var work_id = $('#table_filter_beneficiary_work').val();
  var subcontract = $('#table_filter_beneficiary_subcontract').val();
  var supervisor = $('#table_filter_beneficiary_supervisor').val();
  var wardno = $('#table_filter_beneficiary_wardno').val();
  window.open('<?php echo base_url() . 'work/beneficiary_accounts/print/' ?>?work='+work_id+'&subcontract='+subcontract+'&supervisor='+supervisor+'&wardno='+wardno, 'newwindow', 'width=1200,height=700');
  return false
});
<?php } ?>

var project_beneficiary_accounts_view_table = $('#project_beneficiary_accounts_view_table').DataTable({
  "ajax": {
    url: "<?php echo base_url() . 'work/select_beneficiary_accounts' ?>", // json datasource
    type: "post", // type of method  , by default would be get
    data: function(d) {
      <?php if ($page_name == 'work_profile') { ?>
        d.work = "<?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 }else { ?>
          d.work = GetSearchwork();
          d.subcontract = GetSearchSubcontract();
          d.supervisor = GetSearchsupervisor();
          d.wardno = GetSearchwardno();
          <?php } ?>
        }
      },
      "bProcessing": true,
      "deferRender": true,
      "bDeferRender": true,
      "scrollX": true,
      buttons: [{
        extend: 'print',
        className: 'btn dark btn-outline',
        title: 'List of Beneficiary Accounts'
      },
      {
        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": [23,24,25,26],
      className: "hidden"
    },
    {
      // render: function (data, type, full, meta) {
      //   return "<div class='text-wrap width-200'>" + data + "</div>";
      // },
      // targets: [ 6 ],
    },],
    'order': false
  });
  $(".table_filter").on("change keyup", function() {
    project_beneficiary_accounts_view_table.ajax.reload();
  });

  <?php if($page_name=='project_beneficiary_accounts'){?>
    $(".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: {
          "mobile_number": {
            required: !0,
            number: !0,
            minlength: 8,
            maxlength: 12
          }
        },
        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');
            project_beneficiary_accounts_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>
