<?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 Purchase 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().'purchase/return' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Purchase Return
              </span>
            </a>
          </li>
        </ul>
      </div>
      <div>
      </div>
    </div>
  </div>
  <!-- END: Subheader -->
  <div class="m-content">
    <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">
              Add Purchase Return
            </h3>
          </div>
        </div>
      </div>
      <div class="m-portlet__body">
        <form class="m-form m-form--fit m-form--state m-form--label-align-right "  id="form_purchase_return_get_list" 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-lg-4">
                <div class="form-group m-form__group">
                  <label  for="user_name">
                    Supplier
                  </label>
                  <div class="m-select2 m-select2--air m-select2--pill">
                    <select style="width: 80%" class="form-control m-select2 m-select2-general" required id="supplier_add" name="supplier" data-placeholder="Select Supplier">

                    </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">
                    Purchased To Location
                  </label>
                  <div class="m-select2 m-select2--air m-select2--pill">
                    <select required style="width: 100%" class="form-control m-select2 m-select2--solid m-input--solid m-input " id="purchase_return_location_add" name="work" data-placeholder="Select Work">
                      <option selected disabled>Select Location</option>
                      <?php
                      foreach($stock_locations as $row): ?>
                      <option data-work-status="<?php echo $row->work_status?>" value="<?php echo $row->location_id?>"><?php echo $row->location_name?></option>
                      <?php
                    endforeach;
                    ?>
                  </select>
                </div>
                <span class="m-form__help"></span>
              </div>
            </div>
            <div class="col-lg-2">
              <div class="form-group m-form__group">
                <label for="user_name">
                  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="date"  type="text" class="form-control  m-input " placeholder="Returned Date" >
                </div>
              </div>
            </div>
            <div class="col-lg-2">
              <button type="submit" style="margin-top:25px" class="btn btn-info" id="btn_get_list">
                Get List
              </button>
            </div>
          </div>
        </div>
      </form>
      <form style="display:none" data-form-type='purchase_return' class="m-form m-form--fit m-form--state m-form--label-align-right "  autocomplete="off" id="form_purchase_return_add" method="post" action="<?php echo base_url().'purchases/create_return'?>" enctype="multipart/form-data" class="m-form m-form--fit m-form--state m-form--label-align-right " >
        <div class="modal-body">
          <div class="m-form__content">
            <div class="m-alert m-alert--icon alert alert-warning m--hide" role="alert" id="form_purchase_return_add_msg">
              <div class="m-alert__icon">
                <i class="la la-warning"></i>
              </div>
              <div class="m-alert__text">
                Oh snap! Change a few things up and try submitting again.
              </div>
              <div class="m-alert__close">
                <button type="button" class="close" data-close="alert" aria-label="Close"></button>
              </div>
            </div>
          </div>
          <div class="row">
            <input type="hidden" name="redirect_url" value="<?php echo base_url(uri_string())?>" >
            <input type="hidden" name="count" value="0" id="stock_return_count" >
            <input type="hidden" name="returned_date"  id="returned_date_2" >
          </div>
          <div class="row">
            <div style="width:100%;padding: 15px;padding-bottom: 0px;border-top: 2px dashed black;margin-top:20px"></div>
            <div class="col-lg-12" style="margin-top: 20px;">
              <table width="100%" class="table m-table nowrap  table-header-fixed table-striped- table-bordered table-striped table-hover table-header-fixed" id="stock_list_table">
                <caption id="stock_list_table_caption" style="caption-side: top;text-align: center;font-weight: 700;"></caption>
                <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">Returned Qty</th>
                    <th rowspan="2">Unit Rate</th>
                    <th rowspan="2"><?php echo $this->config->item('Tax_tax_name')?> %</th>
                    <th rowspan="2">Total Amt</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>
            </div>
            <div style="width:100%;padding: 15px;padding-bottom: 0px;border-top: 2px dashed black;margin-top:20px"></div>
            <div class="col-lg-12" style="margin-top: 20px;">
              <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-5">
                      <div class="form-group m-form__group" >
                        <label for="user_name">
                          Supplier
                        </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" id="supplier_name"  class="form-control form_subcontract_add_fields m-input" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-3">
                      <div class="form-group m-form__group" >
                        <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"  id="total_items"  class="form-control form_subcontract_add_fields m-input" aria-describedby="basic-addon1">
                        </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">
                          Total Amount
                        </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_return_amount" id="total_return_amount"  class="form-control form_subcontract_add_fields m-input" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-12">
                      <div class="m-alert m-alert--icon alert alert-info" role="alert" >
                        <div class="m-alert__icon">
                          <i class="la la-warning"></i>
                        </div>
                        <div class="m-alert__text">
                          Total Amount will be Credited to Supplier Advance. You can Redeem Advance at the time of Purchase Bill creation.
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary " data-dismiss="modal">
            Close
          </button>
          <button type="submit" class="btn btn-primary form_submit_btn_6">
            Save & Submit
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


</div>
</div>
<!-- end:: Body -->
<!-- begin::Footer -->

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

<?php $this->view("includes/Inc_sidebar");?>
<?php $this->view("includes/Inc_scripts");?>


<!--begin::Page Snippets -->
<script></script>
<script>
$("#purchase_return_menu").addClass('m-menu__item--active m-menu__item--open');
$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");

$("#supplier_add").select2({
  dropdownParent: $("#form_purchase_return_get_list"),
  placeholder: "Select Suplier"
})
$("#purchase_return_location_add").select2({
  placeholder: "Select  Work",
  dropdownParent: $("#form_purchase_return_get_list"),
  templateResult: format_project_dropdown
})
$("#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 } ?>
  })

  function select_supplier(selected_supplier=''){
    purchase_type='construction';
    $('#supplier_add').html('').trigger('change');
    $("#supplier_add").append("<option disabled selected >Select Supplier</option>");
    $.post("<?php echo base_url() ?>supplier/select",{supplier_type:purchase_type},function(data) {
      var obj = $.parseJSON(data);
      var i=0;
      if(obj.count>0) {
        while (i < obj.id.length) {
          $("#supplier_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
          i++;
        }
        if(selected_supplier!=''){
          $("#supplier_add").val(selected_supplier).trigger("change");
        }
      }
    })
  }
  select_supplier();

  $('body').on('change keyup', '.amt_fields', function() {
    var count = 0;
    var slno = $(this).data('slno');
    var rate =  parseFloat($("#rate_"+slno).val());
    if(isNaN(rate)) {
      rate = 0;
    }
    var qty =  parseFloat($("#qty_"+slno).val());
    if(isNaN(qty)) {
      qty = 0;
    }
    var tax_percent =parseFloat($("#tax_percent_"+slno+" :selected").data('tax-percent'));
    var tax_amount = rate*qty*tax_percent/100;
    var total = (rate*qty)+tax_amount;
    $("#total_"+slno).val(total.toFixed(2));
    calculate_total();
  });

  function calculate_total(){
    var total = count =  0;
    $(".consumed_qty").each(function() {
      if(parseFloat($(this).val())>0){
        count++;
        var slno = $(this).data('slno');
        total += parseFloat($("#total_"+slno).val());
      }
      $("#stock_return_count").val(count);
    });
    $("#total_items").val(count);
    $("#total_return_amount").val(total);

  }

  var stock_list_table=function(location_id,loc_name,supplier,supplier_name) {

    $("#supplier_name").val(supplier_name);
    $('#stock_list_table_caption').text("List of Materials Available in "+loc_name+ ' - From Supplier :'+supplier_name);
    $('#stock_list_table').dataTable().fnDestroy();
    function GetSearchLocation(){
      return $('#location_from').val();
    }
    function GetSearchMaterial(){
      return $('#material_filter').val();
    }
    $("#stock_list_div_title").text('List of Available Stock in '+loc_name+ ' - From Supplier :'+supplier_name);

    var table = $('#stock_list_table').DataTable({
      "ajax":{
        url :"<?php echo base_url().'stock/select_stock_register_2/return' ?>", // 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';
          d.location_id = location_id;
          d.supplier = supplier;
        }
      },
      "bProcessing": true,
      "deferRender": true,
      "bDeferRender": true,
      "scrollX" : true,
      scrollX:!0, scrollCollapse:!0,
      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 ],
          className: "hidden"
        },

      ],
      // "scrollX" : true,
      'paging': false,
      'order': false,
      "initComplete": function( settings, json ) {
        $(".tax_percent_fields").select2({
          placeholder: "Select Tax",
          dropdownParent: $("#form_purchase_return_add")
        })
        $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust()
          .responsive.recalc();
      }
    });
    $(".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" >'+
    '</select></div></div></div>').appendTo("#stock_list_table_wrapper .material_filter");
    $("#material_filter").select2({
      // dropdownParent: $("#form_purchase_add"),
      placeholder: "Select Material"
    })
    function select_material(){
      $("#material_filter").append("<option value='all'>All Materials</option>");
      $.post("<?php echo base_url() ?>material/select",{},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#material_filter").append("<option value=" + obj.id[i] + ">" + obj.name[i] + " [" + obj.unit_name[i] + "][" + obj.item_code[i] + "]</option>");
            i++;
          }
        }
      })
    }
    select_material('material_filter');
    $(".table_filter").on("change", function() {
      table.ajax.reload();
    });
  }

  $("#form_purchase_return_get_list").validate( {
    rules: {
      email: {
        email: !0
      },pincode: {
        number: !0,
        minlength: 6,
        maxlength: 6
      },
    }
    , invalidHandler:function(e, r) {
      var i=$("#form_purchase_return_get_list_msg");
      i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
    }
    , submitHandler:function(e) {

      $("#returned_date_2").val($("#returned_date").val());
      var project_id = $("#purchase_return_location_add").val();
      var supplier_id = $("#supplier_add").val();
      var project_name = $('#purchase_return_location_add option:selected').text();
      var supplier_name = $('#supplier_add option:selected').text();
      stock_list_table(project_id,project_name,supplier_id,supplier_name);
      $("#form_purchase_return_add").show();

    }
  }
);

$(".form_submit_btn_6").click(function (e) {
  e.preventDefault();
  var a = $(this),
  l = $(this).closest("form"),
  action = l.attr('action');
  var form_id = l.attr('id');

  var count =  0;
  $(".consumed_qty").each(function() {
    if(parseFloat($(this).val())>0){
      count++;
    }
  });
  if(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: "Ok",
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            reverseButtons: !0,
            closeOnClickOutside: false,
            allowOutsideClick: false
          }).then(function(e) {
            location.replace('<?php echo base_url()?>purchases/return');
          })
        } 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 Quantity for atleast 1 Item", "No Items Selected");
}
});

</script>
