<script>

$('body').on('click', '#daily_task_edit_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#work_edit').val(no.eq(12).text()).trigger('change');
  $('#assigned_to_edit').val(no.eq(13).text()).trigger('change');
  $('#due_date_edit').datepicker("setDate", no.eq(5).text());
  $('#task_description_edit').val(no.eq(7).text());
  $('#task_title_edit').val(no.eq(4).text());
  $('#task_id_edit').val(no.eq(1).text());
})
$('body').on('click', '#daily_task_view_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#work_view').val(no.eq(12).text()).trigger('change');
  $('#assigned_to_view').val(no.eq(13).text()).trigger('change');
  $('#due_date_view').datepicker("setDate", no.eq(5).text());
  $('#description_view').val(no.eq(7).text());
  $('#title_view').val(no.eq(4).text());
})
$('body').on('click', '#daily_task_delete_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#task_id_delete').val(no.eq(1).text());
})
$('body').on('click', '#daily_task_activity_add_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#task_id_activity_add').val(no.eq(1).text());
  $('#task_title_activity_add').val(no.eq(4).text());
})
$('body').on('click', '#daily_task_status_update_btn', function() {
  var no = $(this).closest('tr').children('td');
  $('#task_id_status_update').val(no.eq(1).text());
  $('#task_title_status_update').val(no.eq(4).text());
  var status = no.eq(14).text();
  $("input[name=task_status][value=" + status + "]").prop('checked', true);
})
$('body').on('click', '#activities_view_btn', function() {
  var no = $(this).closest('tr').children('td');
  var task_id = no.eq(1).text();

  $('#activities_view_table_2').dataTable().fnDestroy();
  activities_table(task_id);
})
$("#table_filter_user").select2({
  placeholder: "Select User"
})
$("#user_2").select2({
  placeholder: "Select User"
})
$("#table_filter_work").select2({
  placeholder: "Select  Work",
  templateResult: format_project_dropdown
})
$("#work_2").select2({
  placeholder: "Select  Work",
  templateResult: format_project_dropdown
})
$("#work_add").select2({
  placeholder: "Select Work",
  dropdownParent: $("#form_daily_task_add"),
  templateResult: format_project_dropdown
})
$("#assigned_to_add").select2({
  placeholder: "Select User",
  dropdownParent: $("#form_daily_task_add")
})
$("#work_edit").select2({
  placeholder: "Select Work",
  dropdownParent: $("#form_daily_task_edit"),
  templateResult: format_project_dropdown
})
$("#assigned_to_edit").select2({
  placeholder: "Select User",
  dropdownParent: $("#form_daily_task_edit")
})

$("#work_view").select2({
  placeholder: "Select Work",
  dropdownParent: $("#form_daily_task_view"),
  templateResult: format_project_dropdown
})
$("#assigned_to_view").select2({
  placeholder: "Select Supervisor",
  dropdownParent: $("#form_daily_task_view")
})
$("#due_date_add,#daily_task_activity_date_add").datepicker( {
  todayHighlight:!0, startDate: '-0m', orientation:"bottom left", templates: {
    leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
  }
})
$("#due_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>'
  }
})
$("#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>'
  }
})
<?php if($page_name=='work_profile'){?>
  select_assigned_user("assigned_to_add",<?php echo $work_data->work_id?>);
  select_assigned_user("assigned_to_edit",<?php echo $work_data->work_id?>);
  <?php }else{ ?>
$('body').on('change', '#work_add', function() {
  var work=$('#work_add :selected').val();
  if(work!='' && work!=null){
    select_assigned_user("assigned_to_add",work);
  }
})
$('body').on('change', '#work_edit', function() {
  var work=$('#work_edit :selected').val();
  if(work!='' && work!=null){
    select_assigned_user("assigned_to_edit",work);
  }
})
<?php } ?>
function select_assigned_user(select_id,work_id){
  $('#'+select_id).html('');
  $("#"+select_id).append("<option disabled selected >Select Supervisor</option>");
  if(work_id!=''){
    $.post("<?php echo base_url() ?>work/select_assigned_users/select/2",{work_id:work_id},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++;
        }
      }else{
        toastr["warning"]("No Supervisors Assigned For this Work", "Not Found!");
      }
    })
  }
}

var activities_table = function(task_id){
  var activities_view_table_2 = $('#activities_view_table_2').DataTable({
    "ajax":{
      url :"<?php echo base_url().'daily_tasks/select_daily_task_report' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        d.task_id = task_id;
      }
    },
    "bProcessing": true,
    "deferRender": true,
    "bDeferRender": true,
    "scrollX" : true,
    scrollX:!0, scrollCollapse:!0,
    buttons: [
      { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Daily Task Activities' },
      { 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": [ 1,2,4,9],
        className: "hidden"
      },
      {
        render: function (data, type, full, meta) {
          return "<div class='text-wrap width-300'>" + data + "</div>";
        },
        targets: 3
      },
      {
        render: function (data, type, full, meta) {
          return "<div class='text-wrap width-200'>" + data + "</div>";
        },
        targets: 4
      }
    ],
    'order': false
  });
  activities_view_table_2.ajax.reload();
}

function GetSearchStartDateDailyTask(){
  return $('#table_filter_start_date').val();
}
function GetSearchEndDateDailyTask(){
  return $('#table_filter_end_date').val();
}
function GetSearchworkDailyTask(){
  return $('#table_filter_work').val();
}
function GetSearchUserDailyTask(){
  return $('#table_filter_user').val();
}
var daily_task_view_table = $('#daily_task_view_table').DataTable({
  "ajax":{
    url :"<?php echo base_url().'daily_tasks/select_daily_tasks' ?>", // 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?>";
        d.user = GetSearchUserDailyTask();
        <?php }elseif($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
            d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
            <?php }else{ ?>
          d.start_date = GetSearchStartDateDailyTask();
          d.end_date = GetSearchEndDateDailyTask();
          d.work = GetSearchworkDailyTask();
            d.user = GetSearchUserDailyTask();
          <?php } ?>

        }
      },
      "bProcessing": true,
      "deferRender": true,
      "bDeferRender": true,
      "scrollX" : true,
      scrollX:!0, scrollCollapse:!0,
      buttons: [
        { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Daily Tasks' },
        { 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": [ 1,12,13,14 ],
          className: "hidden"
        }
      ],
      'order': false
    });
    $(".table_filter").on("change", function() {
      daily_task_view_table.ajax.reload();
    });
    $(".hide_column").hide();

    function GetSearchDate(){
      return $('#table_filter_date_range').val();
    }
    function GetSearchwork(){
      return $('#work_2').val();
    }
    function GetSearchUser2(){
      return $('#user_2').val();
    }
    var daily_report_view_table = $('#daily_report_view_table').DataTable({
      "ajax":{
        url :"<?php echo base_url().'daily_tasks/select_daily_task_report' ?>", // 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.date = GetSearchDate();
              d.work = GetSearchwork();
              d.user = GetSearchUser2();
              <?php } ?>

            }
          },
          "bProcessing": true,
          "deferRender": true,
          "bDeferRender": true,
          "scrollX" : true,
          scrollX:!0, scrollCollapse:!0,
          buttons: [
            { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Daily Task 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>>", // horizobtal scrollable datatable
          "lengthMenu": [
            [25, 50, 100, -1],
            [25, 50, 100, "All"] // change per page values here
          ],
          "columnDefs": [
            {
              "targets": [ 1,2,9 ],
              className: "hidden"
            }
          ],
          'order': false
        });
        $(".table_filter_2").on("change", function() {
          daily_report_view_table.ajax.reload();
        });
        $(".hide_column").hide();

        <?php if($page_name=='daily_tasks'){?>
        // 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'));
          daily_report_view_table.ajax.reload();
          daily_task_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");
                daily_task_view_table.ajax.reload();
                daily_report_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 } ?>

      </script>
