<?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">
          Add New Material Issue
        </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/add' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Add New Material Issue
              </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-3">
                    <div class="form-group m-form__group" >
                      <label> Issue 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="issue_date" name="issue_date_1"  type="text" class="form-control  m-input " placeholder="Issue 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>
                          Go
                        </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_issue" 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="issue_date" id="issue_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-6">
                  <h3 class="m-section__heading">Cart Items</h3>
                </div>
                <div class="col-lg-6">
                  <button style="float: right;margin-bottom: 10px" type="button" id="btn_add_item" class="btn btn-brand">
                    Add Items to Cart
                  </button>
                </div>
              </div>
              <div class="row">
                <div class="col-lg-12">
                  <table style="width: 100%;" class="table m-table m-table--head-bg-success order-list table-striped table-bordered table-advance table-hover">
                    <thead>
                      <tr>
                        <th style="width:5%">Sl No</th>
                        <th style="width:30%">Material</th>
                        <th style="width:12%">Item Code</th>
                        <th style="width:8%">Unit</th>
                        <th style="width:9%">Unit Price</th>
                        <th style="width:10%">Available Qty</th>
                        <th style="width:12%">Issue Qty</th>
                        <th style="width:12%">Issue<br/>Stock Amount</th>
                        <th style="width:6%">&nbsp;</th>
                      </tr>
                    </thead>
                    <tbody id="table_body">

                    </tbody>
                  </table>
                  <input type="hidden" value="0" id="current_row_count" name="current_row_count" >
                </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-3">
                  <div class="form-group m-form__group" style="padding-top: 0px">
                    <label for="user_name">
                      Total Item Cost
                    </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">
                          <?php echo $this->config->item('Currency_currency_format'); ?>
                        </span>
                      </div>
                      <input value="0" readonly type="text" name="total_item_cost" id="total_item_cost"  class=" form-control m-input"  aria-describedby="basic-addon1">
                    </div>
                  </div>
                </div>
                <div class="col-lg-3">
                  <div class="form-group m-form__group" style="padding-top: 0px">
                    <label for="user_name">
                      Vehicle No
                    </label>
                    <input type="text" name="vehicle_no"   class=" form-control  m-input m-input--pill m-input--air"  aria-describedby="basic-addon1">
                  </div>
                </div>
                <div class="col-lg-3">
                  <div class="form-group m-form__group" style="padding-top: 0px">
                    <label for="user_name">
                      Driver Phone No
                    </label>
                    <input type="text" name="driver_phone"   class=" form-control  m-input m-input--pill m-input--air"  aria-describedby="basic-addon1">
                  </div>
                </div>
              </div>
              <br/>
              <div class="row">
                <div class="col-lg-6">
                  <div class="form-group m-form__group">
                    <label for="user_name">
                      Supervisor
                    </label>
                    <div class="m-select2 m-select2--air m-select2--pill">
                      <select style="width: 100%" class="form-control m-select2 m-select2-general" required id="supervisor" name="supervisor">

                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </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 style="display: none" id="stock_list_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" id="stock_list_div_title"></h3>
          </div>
        </div>
        <div class="m-portlet__head-tools">

        </div>
      </div>
      <div class="m-portlet__body">
        <!--begin: Datatable -->
        <table width="100%" class="table m-table  table-header-fixed table-striped- table-bordered table-hover table-header-fixed" id="stock_list_table">
          <thead>
            <tr class="">
              <th rowspan="2">Sl No</th>
              <th rowspan="2">Stock ID</th>
              <th rowspan="2">Material ID</th>
              <th rowspan="2">Unit ID</th>
              <th rowspan="2">Location ID</th>
              <th rowspan="2">Material Name</th>
              <th rowspan="2">Unit</th>
              <th rowspan="2">Unit Price</th>
              <th rowspan="2">Supplier</th>
              <th colspan="2">Currently Available Stock</th>
              <th rowspan="2">Location</th>
              <th rowspan="2">Location Type</th>
              <th colspan="2" style="display: none">Total Purchased Stock</th>
              <th colspan="2" style="display: none">Total Transferred In Stock</th>
              <th colspan="2" style="display: none">Total Transferred Out Stock</th>
              <th colspan="2" style="display: none">Total Consumed Stock</th>
              <th rowspan="2">Supplier ID</th>
              <th rowspan="2"></th>
              <th rowspan="2"></th>
              <th rowspan="2"></th>
              <th rowspan="2"></th>
            </tr>
            <tr>
              <th><span class="hidden">Currently Available Stock</span> Qty</th>
              <th>Amount</th>
              <th><span class="hidden">Total Purchased Stock</span> Qty</th>
              <th>Amount</th>
              <th><span class="hidden">Total Transferred In Stock</span>Qty</th>
              <th>Amount</th>
              <th><span class="hidden">Total Transferred Out Stock</span>Qty</th>
              <th>Amount</th>
              <th><span class="hidden">Total Consumed Stock</span>Qty</th>
              <th>Amount</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
        <!--end: Datatable -->

      </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");

$("#issue_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
      },
      issue_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();
      stock_list_table();
      // item_table();
      $("#location_from_2").val($("#location_from option:selected").val())
      $("#subcontract_2").val($("#subcontract_add option:selected").val())
      $("#issue_date_2").val($("#issue_date").val())
      $("#btn_go").hide();
      $("#location_from").attr('disabled',true);
      $("#subcontract_add").attr('disabled',true);
      $("#issue_date").attr('disabled',true);
      var work_id = $("#location_from option:selected").data('work-id');
      select_users('supervisor','','supervisor',work_id);

    }
  }
);
$("#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++;
      }
    }
  })

}
var stock_list_table=function() {
  $('#stock_list_table').dataTable().fnDestroy();
  function GetSearchLocation(){
    return $('#location_from').val();
  }
  function GetSearchMaterial(){
    return $('#material_filter').val();
  }
  var loc_name = $("#location_from option:selected").text();
  $("#stock_list_div_title").text('List of Available Stock in '+loc_name);

  var table = $('#stock_list_table').DataTable({
    "ajax":{
      url :"<?php echo base_url().'stock/select_stock_register_2/transfer_list' ?>", // json datasource
      type: "post", // type of method  , by default would be get
      data: function(d){
        d.location_id = GetSearchLocation();
        d.material_id = GetSearchMaterial();
        d.quantity = 'available';
      }
    },
    "bProcessing": true,
    "deferRender": true,
    "bDeferRender": true,
    dom:"<'row'<'col-sm-6 text-left material_filter'><'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,3,4,11,12,13,14,15,16,17,18,19,20,21,23,24,25 ],
        className: "hidden"
      }
    ],
    'paging': false,
    'order': false
  });
  $(".hide_column").hide();
  $(".hidden").hide();
  $('<div class="form-group m-form__group row" >'+
  '<div class="col-lg-6"><div class="m-select2 m-select2--air m-select2--pill">'+
  '<select style="width: 100%" class="form-control m-select2 table_filter" id="material_filter"  name="material_filter" >'+
  '<option value="all">All Materials</option>'+
  <?php
  foreach($materials as $row): ?>
  '<option value="<?php echo $row->material_id?>"><?php echo $row->material_name.' [ in '.$row->unit_name.']';?></option>'+
  <?php
endforeach;
?>
'</select></div></div></div>').appendTo("#stock_list_table_wrapper .material_filter");
$("#material_filter").select2({
  // dropdownParent: $("#form_purchase_add"),
  placeholder: "Select Material"
})
$(".table_filter").on("change", function() {
  table.ajax.reload();
});
}

// var item_table=function() {
//   var table = $('#table_items').DataTable({
//     "scrollX": true,
//     bFilter: false,
//     "bLengthChange": false,
//     "bPaginate": false,
//     "dom": "<'row' <'col-md-12'>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", // horizobtal scrollable datatable
//     "lengthMenu": [
//       [25, 50, 100, -1],
//       [25, 50, 100, "All"] // change per page values here
//     ],
//     'ordering': false
//   });
//   $(".hidden").hide();
// }
$('body').on('click', '#btn_transfer_cart', function() {
  var no = $(this).closest('tr').children('td');
  var location = $('#location_to').val();
  var location_type = $('#location_to :selected').data('location-type');
  var work_id = $('#location_to :selected').data('work_id');
  var stock_id = no.eq(1).text();
  var material_id = no.eq(2).text();
  var item_code = no.eq(23).text();
  var description = no.eq(24).text();
  var specification = no.eq(25).text();
  var material_name = no.eq(5).text();
  var unit_id = no.eq(3).text();
  var unit_name = no.eq(6).text();
  var unit_price = no.eq(7).text();
  var supplier = no.eq(8).text();
  var available_qty = no.eq(9).text();
  var already_added=0;
  $(".items_stock_id").each(function(){
    if($(this).val()==stock_id){
      already_added=1;
    }
  });
  if(already_added==0){

    $('#table_items').dataTable().fnDestroy();
    var counter = parseInt($("#current_row_count").val());
    var cols = '<tr class="row_'+counter+'">';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input" name="item[sl_no]['+(counter)+']" value="' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
    cols += '<input type="text" readonly class="form-control m-input" name="item[material_name]['+(counter)+']" value="'+material_name+'" id="material_name_' + (counter+1) + '"/></div>';
    cols += '<input type="hidden" class="items_stock_id" name="item[stock_id]['+(counter)+']" value="'+stock_id+'" id="stock_id_' + (counter+1) + '"/>';
    cols += '</div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input" name="item[item_code]['+(counter)+']" value="'+item_code+'" id="item_code_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input" value="'+unit_name+'" name="item[unit_name]['+(counter)+']" id="unit_name_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input" value="'+unit_price+'" name="item[unit_price]['+(counter)+']" id="unit_price_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input" value="'+available_qty+'" name="item[available_qty]['+(counter)+']" id="available_qty_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" required class="form-control m-input numeric_fields quantity" max="'+available_qty+'" data-sl-no="' + (counter+1) + '" value="1" name="item[quantity]['+(counter)+']" id="quantity_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input total_amount" value="'+unit_price+'" name="item[total_amount]['+(counter)+']" id="total_amount_' + (counter+1) + '"/></div></div></td>';
    cols += '<td><a href="javascript:" data-sl-no='+counter+' class="ibtnDel btn btn-sm btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td>';
    cols += '</tr><tr class="row_'+counter+'">';
    cols += '<td></td>';
    cols += '<td colspan="2"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input" placeholder="Description/Specification" name="item[description]['+(counter)+']" value="'+specification+' '+description+'" id="description_' + (counter+1) + '"/></div></div></td>';
    cols += '<td colspan="5"><div class="form-group m-form__group" style="padding: 0px;margin: 0px;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input" placeholder="Remarks" name="item[remarks]['+(counter)+']"  id="remarks_' + (counter+1) + '"/></div></div></td>';
    cols += '<td></td>';
    cols += '</tr>';
    $("#table_body").append(cols);
    counter++;
    $("#current_row_count").val(counter);

    // item_table();
    calculate_summary();
    toastr["info"]("Item Added to Cart", "Added to Cart");
  }else{
    toastr["warning"]("Item Already Added to Cart", "Already Added");
  }

});
$("#table_body").on("click", ".ibtnDel", function (event) {
  var counter = parseInt($("#current_row_count").val());
  var row_sl_no = $(this).data('sl-no');
  $('.row_'+row_sl_no).remove();
  counter -= 1;
  $("#current_row_count").val(counter);
});
$('body').on('change keyup', '.quantity', function() {
  var sl_no = $(this).attr('data-sl-no');
  var quantity = parseFloat($("#quantity_"+sl_no).val());
  var unit_price = parseFloat($("#unit_price_"+sl_no).val());
  $("#total_amount_"+sl_no).val(quantity*unit_price);
  calculate_summary();
});
function calculate_summary(){
  var total_items = total_item_cost = 0;
  $(".total_amount").each(function(){
    total_item_cost += +$(this).val();
  });
  $("#total_item_cost").val(total_item_cost);
  $("#total_items").val($("#current_row_count").val());
}

$(".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');
  var items_count = $("#current_row_count").val();
  if(items_count>0){
    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) {
      }
    }),
    $(".numeric_fields").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,
            html: "<br>" +
                  '<a href="<?php echo base_url()?>subcontracts/material_issue/view/'+obj.bill_id+'"  class="SwalBtn1  btn btn-primary m-btn m-btn--custom customSwalBtn">' + 'View Bill' + '</button>'
          }).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");
      }
    })
  )
}else{
  toastr["warning"]("Please Add Items to Cart", "Cart Empty");
}

});
$(".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>
