<script>
$("#contractor_add").select2({
  placeholder: "Select Contractor",
  dropdownParent: $("#form_labour_add")
})

$("#contractor_edit").select2({
  placeholder: "Select Contractor",
  dropdownParent: $("#form_labour_edit")
})
$("#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>'
  }
})
$("#table_filter_subcontract").select2({
  placeholder: "Select Subcontract",
  // dropdownParent: $("#form_vehicle_work_slip_add")
})
select_contractors('contractor_add');
select_contractors('contractor_edit');
select_contractors('table_filter_contractor');

function select_contractors(target) {
  $('#' + target).html('');
  $("#" + target).append("<option disabled selected >Select contractor</option>");
  $.post("<?php echo base_url() ?>Subcontracts/select_contractors_list", {}, function(data) {
    var obj = $.parseJSON(data);
    var i = 0;
    if (obj.count > 0) {
      while (i < obj.id.length) {
        $("#" + target).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
        i++;
      }
    }
  })
}
function select_subcontracts(select_id,selected_value='',project){
  $('#'+select_id).html('');
  $('#'+select_id).append("<option disabled selected >Select Subcontract</option>");
  var contractor = $("#table_filter_contractor option:selected").val();
  if(contractor!='' && contractor!=null && contractor!='Select Contractor'){
    $.post("<?php echo base_url() ?>subcontracts/select_subcontracts_list",{contractor:contractor},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]['work_id'] + " - " + obj.data[i]['work_name'] + "]</option>");
          i++;
        }
        if(selected_value!=''){
          $("#"+select_id).val(selected_value).trigger("change");
        }
      }
    })
  }
}
select_subcontracts("table_filter_subcontract");
$('body').on('change', '#table_filter_contractor', function() {
  select_subcontracts("table_filter_subcontract");
})

$("#table_filter_contractor").select2({
  placeholder: "Select Contractor",
})

$("#table_filter_work_type").select2({
  placeholder: "Select Work Type"
})
$("#table_filter_labour").select2({
  placeholder: "Select Labour"
})
$("#table_filter_labour_group_head").select2({
  placeholder: "Select Team Head"
})
$("#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('click', '#btn_add_bill_payment', function() {
  var no = $(this).closest('tr').children('td');
  $('#labour_add_bill_payment').val(no.eq(0).text()).trigger('change');
})
$('body').on('click', '#btn_qr_code', function() {
  var no = $(this).closest('tr').children('td');
  var labour_id = no.eq(0).text();
  window.open('<?php echo base_url() . 'labours/print_qrcode/' ?>' + labour_id, 'newwindow', 'width=1200', 'height=700');
  return false
})

function select_work_type(select_id) {
  $('#' + select_id).html('');
  $("#" + select_id).append("<option disabled selected >Select Work Type</option>");
  $.post("<?php echo base_url() ?>work_types/select", {}, 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_work_type("work_type_add");
$("#work_type_add").select2({
  placeholder: "Select Work Type",
  dropdownParent: $("#form_labour_add")
})
select_work_type("work_type_edit");
$("#work_type_edit").select2({
  placeholder: "Select Work Type",
  dropdownParent: $("#form_labour_edit")
})
$('input[type=radio][name=fixed_wage]').change(function() {
  if (this.value == 1) {
    $(".wage_per_day_div").show();
    $("#daily_wage_add").attr('required', true);
  } else {
    $(".wage_per_day_div").hide();
    $("#daily_wage_add").removeAttr('required', true);
  }
});
$('input[type=radio][name=fixed_wage_edit]').change(function() {
  if (this.value == 1) {
    $(".wage_per_day_div").show();
    $("#daily_wage_edit").attr('required', true);
  } else {
    $(".wage_per_day_div").hide();
    $("#daily_wage_edit").removeAttr('required', true);
  }
});

function GetSearchContractor() {
  return $('#table_filter_contractor').val();
}
function get_branch_id_1() {
  return $('#company_branch_1 :selected').val();
}
function GetSearchSubcontract() {
  return $('#table_filter_subcontract').val();
}
function GetSearchStartDate() {
  return $('#table_filter_start_date').val();
}
function GetSearchEndDate() {
  return $('#table_filter_end_date').val();
}
var labour_view_table = $('#labour_view_table').DataTable({
  "ajax": {
    url: "<?php echo base_url() . 'subcontracts/select_labour' ?>", // json datasource
    type: "post", // type of method  , by default would be get
    data: function(d) {
      d.labour_type = 0;
      <?php if ($page_name == 'contractor_profile') {  ?>
        d.contractor = '<?= $contractor_data->contractor_id ?>';
        <?php } else { ?>
          d.contractor = GetSearchContractor();
          <?php if (!empty($this->config->item('company_branches'))) { ?>
            d.branch_id = get_branch_id_1();
            <?php } ?>
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX": true,
        buttons: [{
          extend: 'print',
          className: 'btn dark btn-outline',
          exportOptions: {
            columns: ':visible'
          },
          title: 'Subcontract Labours'
        },
        {
          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
      ],
      // set the initial value
      "pageLength": 25,
      "columnDefs": [{
        "targets": [<?php if ($page_name == 'contractor_profile') {
          echo "2,";
        } ?>14, 15, 16, 17, 18, 19, 20 <?php if ($this->session->userdata('user_role') == 'auditor') {
          echo ",21";
        } ?> <?php if (empty($this->config->item('company_branches'))) { echo ",1"; }?>                                                 ],
        className: "hidden"
      }],
      'order': [
        [0, 'desc']
      ]
    });


    $(".hide_column").hide();
    var labour_attendance_view_table = $('#labour_attendance_view_table').DataTable({
      "ajax": {
        url: "<?php echo base_url() . 'subcontracts/select_labour_attendance' ?>", // json datasource
        type: "post", // type of method  , by default would be get
        data: function(d) {
          d.contractor = GetSearchContractor();
          d.subcontract = GetSearchSubcontract();
          d.start_date = GetSearchStartDate();
          d.end_date = GetSearchEndDate();
          <?php if (!empty($this->config->item('company_branches'))) { ?>
            d.branch_id = get_branch_id_1();
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX": true,
        buttons: [{
          extend: 'print',
          className: 'btn dark btn-outline',
          exportOptions: {
            columns: ':visible'
          },
          title: 'Subcontract Labour Attendance'
        },
        {
          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
      ],
      // set the initial value
      "pageLength": 25,
      "columnDefs": [{
        "targets": [0 <?php if (empty($this->config->item('company_branches'))) { echo ",1"; }?> ],
        className: "hidden"
      }],
      'order': [
        [0, 'desc']
      ]
    });
    var labour_attendance_summary_view_table = $('#labour_attendance_summary_view_table').DataTable({
      "ajax": {
        url: "<?php echo base_url() . 'subcontracts/select_labour_attendance_summary' ?>", // json datasource
        type: "post", // type of method  , by default would be get
        data: function(d) {
          d.contractor = GetSearchContractor();
          d.subcontract = GetSearchSubcontract();
          d.start_date = GetSearchStartDate();
          d.end_date = GetSearchEndDate();
          <?php if (!empty($this->config->item('company_branches'))) { ?>
            d.branch_id = get_branch_id_1();
            <?php } ?>
          }
        },
        "bProcessing": true,
        "deferRender": true,
        "bDeferRender": true,
        "scrollX": true,
        buttons: [{
          extend: 'print',
          className: 'btn dark btn-outline',
          exportOptions: {
            columns: ':visible'
          },
          title: 'Subcontract Labour Attendance'
        },
        {
          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
      ],
      // set the initial value
      "pageLength": 25,
      "columnDefs": [{
        "targets": [<?php if (empty($this->config->item('company_branches'))) { echo ",1"; }?> ],
        className: "hidden"
      }],
      'order': [
        [0, 'desc']
      ]
    });
    $(".table_filter").on("change", function() {
      labour_view_table.ajax.reload();
      labour_attendance_view_table.ajax.reload();
      labour_attendance_summary_view_table.ajax.reload();
    });

    <?php if ($page_name != 'contractor_profile') { ?>

      $(".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: {
            op_balance: {
              number: !0
            },
            daily_wage: {
              number: !0
            },
            contact_no: {
              number: !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) {

              select_contractors('contractor_add');
              select_contractors('contractor_edit');
              select_contractors('table_filter_contractor');


              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");
              toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
              labour_view_table.ajax.reload();
              labour_attendance_view_table.ajax.reload();
              labour_attendance_summary_view_table.ajax.reload();
              select_work_type("work_type_add");
              select_work_type("work_type_edit");
              $('input[name=fixed_wage]').prop('checked', false);

              $(".custom-file-input").val(null);
              $(".custom-file-label").text('');
            } 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>
  <script>
  $('body').on('click', '#labour_edit_btn', function() {
    var no = $(this).closest('tr').children('td');
    $('#labour_id').val(no.eq(0).text());
    $('#contractor_edit').val(no.eq(19).text()).trigger('change');
    $('#name').val(no.eq(16).text());
    var contact_no = no.eq(4).text();
    if (contact_no.indexOf(',') > -1) {
      var contact_nos = contact_no.split(',');
      $('#contact_no').val(contact_nos[0]);
      $('#contact_no_2').val(contact_nos[1]);
    } else {
      $('#contact_no').val(no.eq(4).text());
      $('#contact_no_2').val('');
    }
    $('#aadhar_no').val(no.eq(9).text());
    $('#address').val(no.eq(10).text());

    $("input[name=fixed_wage_edit][value='" + no.eq(15).text() + "']").attr('checked', true);
    $("input[name=skill_type_edit][value='" + no.eq(20).text() + "']").attr('checked', true);

    $('#daily_wage_edit').val(no.eq(7).text());
    if (no.eq(14).text() == 1) {
      $(".wage_per_day_div").show();
      $("#daily_wage_edit").attr('required', true);
    } else {
      $(".wage_per_day_div").hide();
      $("#daily_wage_edit").removeAttr('required', true);
    }
    $('#op_balance').val(no.eq(8).text());
    $('#work_type_edit').val(no.eq(14).text()).trigger('change');
    // $("input[name=labour_type_edit][value=" + no.eq(12).text() + "]").prop('checked', true);
    if (no.eq(18).text() != '') {
      $("#photo_preview_edit").attr('src', "<?php echo base_url() ?>uploads/labours/" + no.eq(18).text());
    } else {
      $("#photo_preview_edit").attr('src', "");
    }

  })
  $('body').on('click', '#labour_delete_btn', function() {
    var no = $(this).closest('tr').children('td');
    $('#labour_id_delete').val(no.eq(0).text());
  })
  $('body').on('click', '#btn_delete_attendance', function() {
    var no = $(this).closest('tr').children('td');
    $('#attendance_id_delete').val(no.eq(0).text());
  })
</script>
