<?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">
          Material Issue Return
        </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().'subcontracts/material_issue/return' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Add Material Issue Return
              </span>
            </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;">
        <form autocomplete="off" id="form_transfer_add" method="post" action="javascript:;" enctype="multipart/form-data" class="m-form m-form--fit m-form--state m-form--label-align-right " >
          <div class="m-form m-form--label-align-right m--margin-bottom-10">
            <div class="row ">
              <div class="col-xl-12 order-2 order-xl-1">
                <div class="row">
                  <div class="col-lg-4">
                    <div class="form-group m-form__group"  >
                      <label for="user_name">
                        Select Project
                      </label>
                      <div class="m-select2 m-select2--air m-select2--pill">
                        <select required id="location_from" name="location_from_1"  style="width: 100%" class="form-control m-input" aria-describedby="basic-addon1" data-placeholder="Select Location">
                          <?php if($this->config->item('app_module_stock_management')==1){?>
                            <option selected disabled>Select Location</option>
                          <?php }else{?>
                            <option selected disabled>Select Work</option>
                          <?php } ?>
                          <?php
                          foreach($stock_locations as $row):
                            $location_name = $row->location_name;
                            if($row->location_type=='work_site'){
                              ?>
                              <option data-location-type="<?php echo $row->location_type?>" data-work-id="<?php echo $row->work_id?>" data-work-status="<?php echo $row->work_status?>" value="<?php echo $row->location_id?>"><?php echo $location_name?></option>
                            <?php }
                          endforeach;
                          ?>
                        </select>
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-4">
                    <div class="form-group m-form__group"  >
                      <label for="user_name">
                        Select Subcontract
                      </label>
                      <div class="m-select2 m-select2--air m-select2--pill">
                        <select required id="subcontract_add" name="subcontract" style="width: 100%" class="form-control m-input" aria-describedby="basic-addon1" data-placeholder="Select Subcontract">

                        </select>
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                  </div>
                  <div class="col-lg-2">
                    <div class="form-group m-form__group" >
                      <label> Returned Date:</label>
                      <div class="input-group m-input-group--air m-input-group--pill date">
                        <input required data-date-format="dd-mm-yyyy" autocomplete="off" id="returned_date" name="returned_date_1"  type="text" class="form-control  m-input " placeholder="Returned Date" >
                      </div>

                    </div>
                  </div>
                  <div class="col-lg-1">
                    <br/>
                    <button type="submit" style="margin-top: 7px" id="btn_go" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
                      <span>
                        <i class="la la-search"></i>
                        <span>
                          Get Issued Items
                        </span>
                      </span>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
        <form autocomplete="off" id="form_items_add" method="post" action="<?php echo base_url()?>subcontracts/create_material_return" style="display: none" enctype="multipart/form-data" class="cart_div m-form m-form--fit m-form--state m-form--label-align-right " >
          <input type="hidden" name="location_form" id="location_from_2" />
          <input type="hidden" name="subcontract" id="subcontract_2" />
          <input type="hidden" name="returned_date" id="returned_date_2" />
          <div style="background: white;border: 4px solid #f7f7fa;padding: 10px;margin: 5px;padding-bottom: 0px;" >
            <div class="m-section">
              <div class="row">
                <div class="col-lg-12">
                  <?php $this->view("modules/include_tables/table_material_issue_items");?>
                </div>
              </div>
            </div>
          </div>
          <div  style="background: white;border: 4px solid #f7f7fa;padding: 30px;margin: 20px;padding-bottom: 0px;" >
            <div class="m-section">
              <h3 class="m-section__heading">Summary</h3>
              <div class="row">
                <div class="col-lg-3">
                  <div class="form-group m-form__group" style="padding-bottom: 0px">
                    <label for="user_name">
                      Total Items
                    </label>
                    <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                      <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1">
                          <i class="la la-edit"></i>
                        </span>
                      </div>
                      <input value="0" readonly type="text" name="total_items" id="total_items"  class="form-control  m-input" aria-describedby="basic-addon1">
                    </div>
                  </div>
                </div>
                <div class="col-lg-6">
                  <div class="form-group m-form__group" style="padding-top: 0px">
                    <label for="user_name">
                      Remarks
                    </label>
                    <textarea rows="3" name="remarks" id="remarks"   class="form-control  m-input m-input--pill m-input--air" placeholder="Remarks" ></textarea>
                    <span class="m-form__help"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="m-portlet__foot m-portlet__foot--fit">
            <div class="m-form__actions m-form__actions">
              <div class="row">
                <div class="col-lg-9 ml-lg-auto">
                  <button type="submit" class="btn btn-brand form_submit_btn_2">
                    Save & Submit
                  </button>
                  <button type="reset" class="btn btn-secondary">
                    Cancel
                  </button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>

  </div>
</div>
</div>
<!-- end:: Body -->
<!-- begin::Footer -->
<?php $this->view("modules/include_modals/modal_vehicle_add");?>

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

<?php $this->view("includes/Inc_sidebar");?>
<?php $this->view("includes/Inc_scripts");?>
<?php $this->view("modules/include_scripts/vehicles_scripts");?>
<!--begin::Page Snippets -->
<script>
$("#subcontract_menu").addClass('m-menu__item--active m-menu__item--open');
$("#subcontract_menu_6").addClass('m-menu__item--active');


$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");

$("#returned_date").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 } ?>
  })
  $("#location_from").select2({
    // dropdownParent: $("#form_purchase_add"),
    placeholder: "Select Location",
    templateResult: format_project_dropdown
  })
  $("#btn_add_item").click(function() {
    $('html, body').animate({
      scrollTop: $("#stock_list_div").offset().top
    }, 1000);
  });
  $("#form_transfer_add").validate( {
    rules: {
      location_from_1: {
        required: !0
      },
      subcontract: {
        required: !0
      },
      returned_date_1: {
        required: !0
      }
    },
    invalidHandler:function(e, r) {
      var i=$("#form_work_msg");
      i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
    }
    , submitHandler:function(e) {
      $("#stock_list_div").show();
      $(".cart_div").show();
      material_issue_items_table();
      // item_table();
      $("#location_from_2").val($("#location_from option:selected").val())
      $("#subcontract_2").val($("#subcontract_add option:selected").val())
      $("#returned_date_2").val($("#returned_date").val())
      $("#btn_go").hide();
      $("#location_from").attr('disabled',true);
      $("#subcontract_add").attr('disabled',true);
      $("#returned_date").attr('disabled',true);

    }
  }
);
var material_issue_items_table=function() {
  $('#stock_list_table').dataTable().fnDestroy();
  var material_issue_items_view_table = $('#material_issue_items_view_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'subcontracts/select_material_issue_items/list/return' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        d.location = $("#location_from option:selected").val();
        d.subcontract = $("#subcontract_add option:selected").val();
        // d.material_id = GetSearchMaterial();
      }
    },
    "bProcessing": true,
    "deferRender": true,
    "bDeferRender": true,
    "scrollX" : true,
    scrollX:!0, scrollCollapse:!0,
    dom:"<'row'<'col-sm-6 text-left'><'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
    "columnDefs": [
      {
        "targets": [ 1,2,4,5,12,13,14,15,16 ],
        className: "hidden"
      }
    ],
    "paging":false,
    // "searching":false,
    "info": false,
    'order': false
  });
}
$("#subcontract_add").select2({
  placeholder: "Select Subcontract",
  // dropdownParent: $("#form_vehicle_work_slip_add")
})
$("#supervisor").select2({
  placeholder: "Select Supervisor",
})
function select_subcontracts(select_id,selected_value='',project){
  $('#'+select_id).html('');
  $('#'+select_id).append("<option disabled selected >Select Subcontract</option>");
  var project = $("#location_from option:selected").data('work-id');
  if(project!='' && project!=null && project!='Select Location'){
    $.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");
        }
      }
    })
  }
}
select_subcontracts("subcontract_add");
$('body').on('change', '#location_from', function() {
  select_subcontracts("subcontract_add");
})
function select_users(select_id,branch_id='',user_role='',project=''){
  $('#'+select_id).html('');
  $('#'+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++;
      }
    }
  })

}

$('body').on('change keyup', '.returned_qty', function() {
  var count = 0;
  $(".returned_qty").each(function() {
    if(parseFloat($(this).val())>0){
      count++;
    }
    $("#total_items").val(count);
  });
});


$(".form_submit_btn_2").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: {
      quantity: {
        number: !0
      }
    }, invalidHandler: function (e, r) {
      var i = $("#" + form_id + "_msg");
      i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
    }, submitHandler: function (e) {
    }
  }),
  $(".return_qty").each(function () {
    $(this).rules('add', {
      number: !0
    });
  }), 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);
        $("#"+modal_id).modal('toggle');
        $("."+form_id+"_fields").val('');
        $("."+form_id+"_select").val('').trigger("change");
        toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);

        swal({
          width: 500,
          title: obj.flashdata_title,
          text: obj.flashdata_msg,
          type: obj.flashdata_type,
          showCancelButton: !0,
          confirmButtonText: "View Issued Materials",
          cancelButtonText: "Add New Issue",
          confirmButtonColor: '#3085d6',
          cancelButtonColor: '#d33',
          reverseButtons: !0,
          closeOnClickOutside: false,
          allowOutsideClick: false,
        }).then(function(e) {
          e.value ? window.location.replace("<?php echo base_url()?>subcontracts/material_issue/") : "cancel" === e.dismiss && 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");
    }
  })
)

});
$(".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: {
      worked_duration: {
        number: !0,
        min: 1
      },
      basic_charge: {
        number: !0,
        min: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);
        $("#"+modal_id).modal('toggle');
        $("."+form_id+"_fields").val('');
        $("."+form_id+"_fields_1").val(0);
        $("."+form_id+"_fields_2").val(1);
        $("."+form_id+"_select").val('').trigger("change");
        toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
        select_vehicles("vehicle_add");
      } 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");
    }
  })
)
});
</script>
