<?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">
          Create New <?php echo $this->config->item('Quotation_sales_estimation_title') ?>
        </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().'sales_estimation/add' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Create New <?php echo $this->config->item('Quotation_sales_estimation_title') ?>
              </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_sale_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">
              <?php if ($this->config->item('app_module_company_branches') == 1 && $this->session->userdata('branch_id') == 0){?>
                <div class="col-lg-3">
                  <div class="form-group m-form__group">
                    <label for="user_name">
                      To
                    </label>
                    <div class="m-radio-inline" style="padding-top: 10px;">
                      <label class="m-radio m-radio--solid m-radio--state-info">
                        <input required type="radio" checked class="form_fields_radio"  name="estimation_to_add" value="Branch"> Branch
                        <span></span>
                      </label>
                      <label class="m-radio m-radio--solid m-radio--state-success">
                        <input type="radio" class="form_fields_radio" name="estimation_to_add"  value="Customer"> Customer
                        <span></span>
                      </label>
                    </div>
                  </div>
                </div>
              <?php } ?>
              <div class="col-lg-4">
                <div class="form-group m-form__group" style="padding-top:0px !important">
                  <label for="user_name">
                    Customer <?php if ($this->config->item('app_module_company_branches') == 1 && $this->session->userdata('branch_id') == 0){?>/ Branch <?php } ?>
                  </label>
                  <div class="input-group m-input-group m-input-group--pill" id="div_customer" style="display:none">
                    <div class="input-group-prepend">
                      <a href="#customer_add_modal"   data-toggle="modal" data-target="#customer_add_modal" class="btn btn-focus">
                        <i class="fa fa-plus-circle"></i>
                      </a>
                    </div>
                    <select style="width: 82%" class="form-control m-select2 m-select2-general" id="customer_add" name="customer" data-placeholder="Select Customer">

                    </select>
                  </div>
                  <?php if ($this->config->item('app_module_company_branches') == 1 && $this->session->userdata('branch_id') == 0){?>
                    <div class="m-select2 m-select2--air m-select2--pill" id="div_branch" >
                      <select required id="branch_add"  name="branch"  style="width: 100%" class="form-control m-input"  aria-describedby="basic-addon1" >
                        <option selected disabled>Select Branch</option>
                        <?php foreach ($branches as $key => $value) { ?>
                          <option value="<?php echo $value->branch_id ?>"><?php echo $value->branch_name ?></option>
                        <?php } ?>
                      </select>
                    </div>
                  <?php } ?>
                  <span class="m-form__help"></span>
                </div>
              </div>
              <?php if ($this->config->item('Material_sale_price_category_enable') == 1){ ?>
                <div class="col-lg-2">
                  <div class="form-group m-form__group" >
                    <label>Sale Price Category:</label>
                    <div class="m-select2 m-select2--air m-select2--pill">
                      <select required id="sale_price_category_1"  name="sale_price_category"  style="width: 100%" class="form-control m-input"  aria-describedby="basic-addon1" >
                        <option selected disabled>Select Price Category</option>
                        <option value="1"><?php echo $this->config->item('Material_sale_price1_name') ?></option>
                        <option value="2"><?php echo $this->config->item('Material_sale_price2_name') ?></option>
                        <option value="3"><?php echo $this->config->item('Material_sale_price3_name') ?></option>
                        <option value="4"><?php echo $this->config->item('Material_sale_price4_name') ?></option>
                        <option value="5"><?php echo $this->config->item('Material_sale_price5_name') ?></option>
                        <option value="6"><?php echo $this->config->item('Material_sale_price6_name') ?></option>
                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
              <?php } ?>
              <div class="col-lg-2">
                <div class="form-group m-form__group" >
                  <label>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="estimation_date_1" name=""  type="text" class="form-control  m-input " placeholder="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>
        </form>
      </div>
    </div>
    <div class="m-portlet  m-portlet--rounded m-portlet--bordered cart_div" style="display:none">
      <div class="m-portlet__body" style="padding: 1rem 2.2rem;">
        <form autocomplete="off" id="form_items_add" method="post" action="<?php echo base_url()?>sales_estimation/create_estimation"  enctype="multipart/form-data" class=" m-form m-form--fit m-form--state m-form--label-align-right " >
          <input type="hidden" name="customer_id" id="customer_id" />
          <input type="hidden" name="branch_id" id="branch_id" />
          <input type="hidden" name="estimation_date" id="estimation_date" />
          <input type="hidden" name="estimation_to" id="estimation_to" />
          <input type="hidden" name="sale_price_category" id="sale_price_category" />
          <input type="hidden" name="buyer_name" id="buyer_name" />
          <input type="hidden" name="buyer_address" id="buyer_address" />
          <input type="hidden" name="buyer_phone" id="buyer_phone" />
          <input type="hidden" name="buyer_taxno" id="buyer_taxno" />
          <input type="hidden" name="buyer_state_id" id="buyer_state_id" />
          <br/><br/>
          <div class="row">
            <div class="col-lg-4">
              <div class="form-group m-form__group" >
                <label>Buyer Address:</label>
                <textarea readonly class="form-control m-input m-input--air m-input--pill m-input--solid" id="buyer_address_show" name="buyer_address_show" rows="7"></textarea>
              </div>
            </div>
          </div>
          <br/>
          <div style="background: white;border: 4px solid #f7f7fa;padding: 15px;margin: 0px;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>
              <div class="row" style="margin-bottom: 10px">
                <div class="col-lg-5" style="padding-right: 0px;">
                  <div class="form-group m-form__group" style="border: 4px solid #e2e2e2;padding-top: 10px;padding-right:0px !important">
                    <div class="input-group m-input-group m-input-group--pill" >
                      <div class="input-group-prepend">
                        <button type="button" style="margin-bottom: 10px" id="btn_add_all_item" class="btn btn-info">
                          Add All to Cart
                        </button>
                      </div>
                      <select style="width: 62%"  class="form-control m-select2 m-select2-general" id="category_add" data-placeholder="Select Category">

                      </select>
                    </div>
                  </div>
                </div>
                <div class="col-lg-7" style="padding-left: 0px;">
                  <div class="form-group m-form__group"  style="border: 4px solid #e2e2e2;border-left: none;padding-bottom: 10px;padding-top: 10px;padding-right:0px !important" >
                    <div class="input-group m-input-group m-input-group--pill">
                      <div class="input-group-prepend">
                        <a href="#material_add_modal"   data-toggle="modal" data-target="#material_add_modal" class="btn btn-focus">
                          <i class="fa fa-plus-circle"></i>
                        </a>
                      </div>
                      <select style="width: 68%"  class="form-control m-select2 m-select2-general" id="material_add" data-placeholder="Select Material">

                      </select>
                      <div class="input-group-prepend">
                        <button style="float: right" type="button" id="btn_add_item" class="btn btn-brand">
                          Add to Cart
                        </button>
                      </div>
                    </div>
                  </div>
                </div>

              </div>
              <div class="row">
                <div class="col-lg-12">
                  <table style="width: 100%;max-width: 100%"  id="table_items" 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:22%">Item Name</th>
                        <th style="width:7%">UoM</th>
                        <th style="display:none">Unit Cost</th>
                        <th style="width:10%">Rate</th>
                        <th style="display:none">Available Qty</th>
                        <th style="width:8%">Qty</th>
                        <th style="width:8%">Disc Amt</th>
                        <th style="width:9%">Taxable Amt</th>
                        <th style="width:13%"><?php echo $this->config->item('Tax_tax_name')." %" ?></th>
                        <th style="width:9%"><?php echo $this->config->item('Tax_tax_name')." Amt" ?></th>
                        <th style="width:20%">Total Amount</th>
                        <th style="width:4%">&nbsp;</th>
                      </tr>
                    </thead>
                    <tbody id="table_body">

                    </tbody>
                  </table>
                  <input type="hidden" value="0" id="current_row_count" name="current_row_count" >
                  <input type="hidden" value="0" id="actual_row_count" name="actual_row_count" >
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-lg-8">
              <div style="background: white;border: 4px solid #f7f7fa;padding: 15px;margin: 0px;margin-top: 20px;padding-bottom: 0px">
                <div class="m-section" style="margin-bottom: 10px">
                  <h3 class="m-section__heading">Terms & Conditions</h3>
                  <div class="row">
                    <div class="col-lg-12">
                      <table style="width: 100%;max-width: 100%" id="table_terms" class="table m-table table-bordered item_table m-table--head-bg-success">
                        <thead>
                          <tr>
                            <th style="width:5%;text-align:left;color:white">Sl No</th>
                            <th style="width:70%;text-align:left;color:white">Description</th>
                            <th style="width:6%;text-align:left;color:white">&nbsp;</th>
                          </tr>
                        </thead>
                        <tbody id="table_body_terms">
                          <?php
                          $i = 0;
                          foreach ($terms_and_condition_templates as $key => $value) {?>
                            <tr class="row_<?php echo $i ?>">
                              <td>
                                <div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;">
                                  <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 item_slno" data-sl-no="<?php echo $i + 1 ?>" name="terms[sl_no][<?php echo $i ?>]" value="<?php echo $i + 1 ?>" /></div>
                                </div>
                              </td>
                              <td>
                                <div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;">
                                  <textarea rows="2" class="form-control m-input m-input--pill m-input--air" name="terms[description][<?php echo $i ?>]" id="description_<?php echo $i + 1 ?>" /><?php echo $value->description ?></textarea>
                                </div>
                              </td>
                              <td>
                                <a href="javascript:" data-row-sl-no="<?php echo $i ?>" class="ibtnDel_terms btn btn-danger btn-icon-only">
                                  <i class="fa fa-trash"></i>
                                </td>
                              </tr>
                              <?php $i++;
                            } ?>
                          </tbody>
                          <tfoot>
                            <tr>
                              <td colspan="10" style="text-align: left;border-bottom: 1px solid #e7ecf1;">
                                <button type="button" class="btn btn-block " id="addrow_terms"><i class="fa fa-plus-square"></i> Add new Terms and Condition</button>
                              </td>
                            </tr>
                          </tfoot>
                        </table>
                        <input type="hidden" value="<?php echo $i ?>" id="current_row_count_terms_and_conditions" name="current_row_count">
                        <input type="hidden" value="<?php echo $i ?>" id="actual_row_count_terms_and_conditions" name="actual_row_count">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-lg-4">
                <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="col-lg-12">
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          Net 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">
                              <?php echo $this->config->item('Currency_currency_format'); ?>
                            </span>
                          </div>
                          <input value="0" readonly="" type="text" name="bill_net_total_amount" id="bill_net_total_amount" class="form-control m-input m-input--solid summary_key" placeholder="Bill Net Total Amount" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-12">
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          <?php echo $this->config->item('Tax_tax_name')?> 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">
                              <?php echo $this->config->item('Currency_currency_format'); ?>
                            </span>
                          </div>
                          <input value="0" readonly type="text" id="bill_tax_amount" name="bill_tax_amount"  class="form-control m-input " placeholder="Bill GST Amount" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-12">
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          Grand Total
                        </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="bill_grand_total" id="bill_grand_total" class="form-control m-input m-input--solid" placeholder="Grand Total" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-12">
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          Round 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">
                              <?php echo $this->config->item('Currency_currency_format'); ?>
                            </span>
                          </div>
                          <input value="0" required type="text" name="bill_round_amount" id="bill_round_amount" class="form-control m-input bill_inputs" placeholder="Grand Total" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </div>
                    <div class="col-lg-12">
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          NET 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">
                              <?php echo $this->config->item('Currency_currency_format'); ?>
                            </span>
                          </div>
                          <input value="0" readonly type="text" name="bill_receivable_amount" id="bill_receivable_amount" class="form-control m-input m-input--solid" placeholder="Grand Total" aria-describedby="basic-addon1">
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                    </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">
                      Save & Submit
                    </button>
                    <button type="reset" class="btn btn-secondary">
                      Cancel
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </form>
        </div>
      </div>

      <?php $this->view("modules/include_modals/modal_customers");?>
      <?php $this->view("modules/include_modals/modal_material_add");?>
    </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");?>
<?php $this->view("modules/include_scripts/customers_scripts"); ?>
<!--begin::Page Snippets -->
<script>
//    Toggle Sidebar
$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");
$(".m_selectpicker").selectpicker();

$("#sales_estimation_menu").addClass('m-menu__item--active m-menu__item--open');
$("#sales_estimation_menu1").addClass('m-menu__item--active');

$("#estimation_date_1").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 } ?>
  })
  $("#buyers_order_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',
  })
  $("#delivery_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($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 } ?>
    })
    $("#credit_acc").select2({
      // dropdownParent: $("#form_sale_add"),
      placeholder: "Select Debit Acc"
    })
    $("#bank_account_add").select2({
      placeholder: "Select Bak Account"
    })
    $("#location_to").select2({
      // dropdownParent: $("#form_sale_add"),
      placeholder: "Select Warehouse"
    })
    $("#customer_add").select2({
      // dropdownParent: $("#form_sale_add"),
      placeholder: "Select Customer"
    })
    $("#branch_add").select2({
      // dropdownParent: $("#form_sale_add"),
      placeholder: "Select Branch"
    })
    $("#sale_price_category_1").select2({
      // dropdownParent: $("#form_sale_add"),
      placeholder: "Select Price Category"
    })
    $("#material_add").select2({
      dropdownParent: $("#form_items_add"),
      placeholder: "Select Material"
    })
    $("#category_add").select2({
      placeholder: "Select Category",
      dropdownParent: $("#form_items_add")
    })
    $("#material_unit_add").select2({
      placeholder: "Select Unit",
      dropdownParent: $("#form_material_add")
    })
    $("#material_category_add").select2({
      placeholder: "Select Category",
      dropdownParent: $("#form_material_add")
    })
    $("#material_tax_percent_add").select2({
      placeholder: "Select Tax %",
      dropdownParent: $("#form_material_add")
    })

    select_category();
    select_material();
    select_units();
    function select_units(){
      $('#material_unit_add').html('');
      $("#material_unit_add").append("<option disabled selected >Select Unit</option>");
      $.post("<?php echo base_url() ?>units/select",{},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#material_unit_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            i++;
          }
        }
      })
    }
    function select_category(){
      $('#material_category_add').html('');
      $("#material_category_add").append("<option selected disabled >Select Category</option>");

      $('#category_add').html('');
      $("#category_add").append("<option selected value='all' >All Categories</option>");

      $.post("<?php echo base_url() ?>material/select_category",{},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#material_category_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            $("#category_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
            i++;
          }
        }
      })
    }
    function select_material(category=''){
      $('#material_add').html('');
      $("#material_add").append("<option disabled selected >Select Material</option>");
      $.post("<?php echo base_url() ?>material/select",{category:category},function(data) {
        var obj = $.parseJSON(data);
        var i=0;
        if(obj.count>0) {
          while (i < obj.id.length) {
            $("#material_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + " [" + obj.unit_name[i] + "]</option>");
            i++;
          }
        }
      })
    }
    <?php if($this->session->userdata('branch_id')!=0){?>
      $("#div_customer").show();
      $("#customer_add").attr('required',true);
      <?php } ?>
      <?php if ($this->config->item('app_module_company_branches') == 1){?>
      $('body').on('change', 'input[type=radio][name=estimation_to_add]', function() {
        var estimation_to = $("input[name='estimation_to_add']:checked").val();
        if(estimation_to=='Branch'){
          $("#div_branch").show();
          $("#div_customer").hide();
          $("#branch_add").attr('required',true);
          $("#customer_add").removeAttr('required',true);
        }else{
          $("#div_branch").hide();
          $("#div_customer").show();
          $("#branch_add").removeAttr('required',true);
          $("#customer_add").attr('required',true);
        }
      })
      <?php }else{ ?>
        $("#div_customer").show();
        $("#customer_add").attr('required',true);
        <?php } ?>
      $('body').on('change', '#customer_add,#branch_add', function() {
        $("#sale_price_category_1").val('').trigger('change');
        var estimation_to = $("input[name='estimation_to_add']:checked").val();
        if(estimation_to=='Branch'){
          var branch_id = $('#branch_add').val();
          $.post("<?php echo base_url() ?>branches/select_details",{id:branch_id},function(data) {
            var obj = $.parseJSON(data);
            var i=0;
            if(obj.count==1) {
              $("#sale_price_category_1").val(obj.data['sale_price_category']).trigger('change');
              $("#buyer_name").val(obj.data['branch_name']);
              $("#buyer_address").val(obj.data['branch_address']);
              $("#buyer_phone").val(obj.data['branch_phone']);
              $("#buyer_taxno").val(obj.data['branch_taxno']);
              $("#buyer_state_id").val(obj.data['tax_state_id']);

              var address = obj.data['branch_name'];
              address += "\n"+obj.data['branch_address'];
              address += "\nPhone : "+obj.data['branch_phone'];
              address += "\nGSTIN : "+obj.data['branch_taxno'];
              address += "\nState : "+obj.data['state_name']+"          State Code : "+obj.data['state_code'];
              $("#buyer_address_show").val(address);
            }
          })
        }else{
          var customer_id = $('#customer_add').val();
          $.post("<?php echo base_url() ?>customers/select_details",{id:customer_id},function(data) {
            var obj = $.parseJSON(data);
            var i=0;
            if(obj.count==1) {
              $("#sale_price_category_1").val(obj.data['sale_price_category']).trigger('change');
              $("#buyer_name").val(obj.data['customer_name']);
              $("#buyer_address").val(obj.data['customer_location']);
              $("#buyer_phone").val(obj.data['customer_phone']);
              $("#buyer_taxno").val(obj.data['customer_tax_no']);
              $("#buyer_state_id").val(obj.data['customer_tax_state']);

              var address = obj.data['customer_name'];
              address += "\n"+obj.data['customer_location'];
              address += "\nPhone : "+obj.data['customer_phone'];
              address += "\nGSTIN : "+obj.data['customer_tax_no'];
              address += "\nState : "+obj.data['state_name']+"          State Code : "+obj.data['state_code'];
              $("#buyer_address_show").val(address);
            }
          })
        }
      })
      select_customer();
      function select_customer(){

        $('#customer_add').html('');
        $("#customer_add").append("<option disabled selected >Select Customer</option>");
        $.post("<?php echo base_url() ?>customers/select",{},function(data) {
          var obj = $.parseJSON(data);
          var i=0;
          if(obj.count>0) {
            while (i < obj.id.length) {
              $("#customer_add").append("<option value=" + obj.id[i] + ">" + obj.name[i] + " [" + obj.phone[i] + "]</option>");
              i++;
            }
          }
        })
      }

      jQuery.validator.addMethod("notEqual", function(value, element, param) {
        return $('#location_from').val() != $('#location_to').val()
      }, "Please Select a different Location");
      $("#form_sale_add").validate( {
        rules: {
          estimation_date_1: {
            required: !0
          }
        },
        invalidHandler:function(e, r) {
          var i=$("#form_sale_add_msg");
          i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
        }
        , submitHandler:function(e) {
          $("#stock_list_div").show();
          $(".cart_div").show();

          $("#customer_id").val($("#customer_add option:selected").val());
          $("#branch_id").val($("#branch_add option:selected").val());
          $("#estimation_to").val($("input[name='estimation_to_add']:checked").val());
          $("#sale_price_category").val($("#sale_price_category_1 option:selected").val());
          $("#estimation_date").val($("#estimation_date_1").val());

          $("#btn_go").hide();
          $("#estimation_date_1").attr('disabled',true);
          $("#customer_add").attr('disabled',true);
          $("#location_to").attr('disabled',true);
          $("#branch_add").attr('disabled',true);
          $("#sale_price_category_1").attr('disabled',true);
          $("input[type=radio][name=estimation_to_add]").attr('disabled',true);
          $("#sale_price_column").html("Sale Price<br/>("+$("#sale_price_category_1 option:selected").text()+")");

          item_table();
        }
      }
    );

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

    $("#btn_add_item").on("click", function () {

      var material_id = $('#material_add :selected').val();
      var unit_id = $('#material_add :selected').data('unit');

      if(material_id!=null && material_id!='' && material_id!='Select Material'){
        // Get Material Details
        $.post("<?php echo base_url() ?>material/select_details",{id:material_id},function(data) {
          var obj = $.parseJSON(data);
          var i=0;
          if(obj.count==1) {
            //      Check Already Added to Cart
            var already_added=0;
            $(".item_material_id").each(function(){
              if($(this).val()==material_id){
                already_added=1;
              }
            });
            if(already_added==0){
              <?php if ($this->config->item('Material_sale_price_category_enable') == 1){ ?>
                sale_price = obj.data['sale_price'+$("#sale_price_category").val()];
                <?php }else{?>
                  sale_price = obj.data['material_unit_price'];
                  <?php } ?>
                  // $('#table_items').dataTable().fnDestroy();
                  var counter = parseInt($("#current_row_count").val());
                  var actual_row_count = parseInt($("#actual_row_count").val());

                  var newRow = '<tr class="row_'+counter+'">';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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 item_slno" data-sl-no="' + (counter+1) + '" name="item[sl_no]['+(counter)+']" value="' + (actual_row_count+1) + '"/></div></div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                  // newRow += '<input type="text" readonly class="form-control m-input" name="item[material_name]['+(counter)+']" value="'+obj.name[0]+'" id="material_name_' + (counter+1) + '"/></div>';
                  newRow += "<input type='text' readonly class='form-control m-input' name='item[material_name]["+(counter)+"]' value='"+obj.data['material_name']+"' id='material_name_" + (counter+1) + "'/></div>";
                  newRow += '<input type="hidden" name="item[material_id]['+(counter)+']" value="'+obj.data['material_id']+'" id="material_id_' + (counter+1) + '" class="item_material_id"/>';
                  newRow += '<input type="hidden" name="item[unit_id]['+(counter)+']" value="'+obj.data['unit_id']+'" id="unit_id_' + (counter+1) + '"/>';
                  newRow += '</div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                  newRow += '<input type="text" readonly class="form-control m-input" value="'+obj.data['unit_name']+'" name="item[unit_name]['+(counter)+']" id="unit_name_' + (counter+1) + '"/></div>';
                  newRow += '</div></td>';
                  newRow += '<td style="display:none"><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 quantity" data-sl-no="' + (counter+1) + '" value="'+obj.data['material_unit_price']+'" name="item[unit_cost]['+(counter)+']" id="unit_cost_' + (counter+1) + '"/></div></div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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  item_rate_fields unit_price_field" value="'+sale_price+'"  data-sl-no="' + (counter+1) + '" name="item[unit_price]['+(counter)+']" id="unit_price_' + (counter+1) + '"/></div></div></td>';
                  newRow += '<td style="display:none"><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input"  value="" data-sl-no="' + (counter+1) + '" name="item[available_qty]['+(counter)+']" id="available_qty_' + (counter+1) + '"/></div></div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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 item_rate_fields quantity_field"  value="1" data-sl-no="' + (counter+1) + '" name="item[quantity]['+(counter)+']" id="quantity_' + (counter+1) + '"/></div></div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" required class="form-control m-input item_disc_amount item_rate_fields" value="0" data-sl-no="' + (counter+1) + '" name="item[disc_amount]['+(counter)+']" id="disc_amount_' + (counter+1) + '"/></div></div></td>';
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input item_taxable_amount" value="'+sale_price+'" data-sl-no="' + (counter+1) + '" name="item[taxable_amount]['+(counter)+']" id="taxable_amount_' + (counter+1) + '"/></div></div></td>';

                  <?php
                  $tax_percent = $this->config->item('Tax_tax_percent'); ?>
                  newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><select class="form-control m-bootstrap-select m-bootstrap-select--air m-bootstrap-select--pill m_selectpicker item_tax_percent item_rate_fields" data-sl-no="' + (counter+1) + '" name="item[tax_percent]['+(counter)+']" id="tax_percent_' + (counter+1) + '" title="Tax %">';
                  <?php
                  $tax_percent = $this->config->item('Tax_tax_percent');
                  foreach($tax_percent as $row){
                    $selected_tax='';
                    if($row->tax_percentage==0){
                      $selected_tax='selected';
                    }
                    ?>
                    newRow += '<option <?php echo $selected_tax?> data-tax-percent="<?php echo $row->tax_percentage?>" value="<?php echo $row->tax_id?>"><?php echo $row->tax_name?></option>';
                    <?php } ?>
                    newRow += '</select></div><input type="hidden" value="0" data-sl-no="' + (counter+1) + '" name="item[tax_percentage]['+(counter)+']" id="tax_percentage_' + (counter+1) + '"></td>';
                    newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input item_tax_amount" value="0" data-sl-no="' + (counter+1) + '" name="item[tax_amount]['+(counter)+']" id="tax_amount_' + (counter+1) + '"/></div></div></td>';

                    newRow += '<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 item_total_amount" value="'+sale_price+'" name="item[total_amount]['+(counter)+']" id="total_amount_' + (counter+1) + '"/></div></div></td>';
                    newRow += '<td><a href="javascript:" data-row-sl-no='+counter+' class="ibtnDel btn btn-sm btn-danger btn-icon-only m-btn--pill" ><i class="fa fa-trash"></i></td>';
                    newRow += '</tr>';

                    // newRow += '<tr class="row_'+counter+'">';
                    // newRow += '<td></td>';
                    // newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input placeholder="Item Code" type="text" class="form-control m-input" data-sl-no="' + (counter+1) + '" name="item[item_code]['+(counter)+']" value="'+obj.data['item_code']+'" id="item_code_' + (counter+1) + '"/></div></div></td>';
                    // newRow += '<td style="display:none"></td>';
                    // newRow += '<td style="display:none"></td>';
                    // newRow += '<td colspan="8"><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input placeholder="Description Here" type="text" class="form-control m-input" data-sl-no="' + (counter+1) + '" name="item[description]['+(counter)+']" id="description_' + (counter+1) + '"/></div></div></td>';
                    // newRow += '<td></td>';
                    // newRow += '</tr>';
                    $("#table_body").append(newRow);

                    counter++;
                    actual_row_count++;
                    $("#current_row_count").val(counter);
                    $("#actual_row_count").val(actual_row_count);
                    $(".m_selectpicker").selectpicker();
                    $('.m_selectpicker').selectpicker('refresh');
                    $("#tax_percent_"+counter).val(obj.data['material_tax_percent']).trigger('change');
                    $("#tax_percent_"+counter).selectpicker('refresh');

                    item_table();
                    calculate_summary();
                    toastr["info"]("Item Added to Cart", "Added to Cart");
                  }
                  else{
                    toastr["error"]("Item Already Added to Cart", "Already Added");
                  }
                }else{
                  toastr["error"]("Some Error Associated with Selected Material", "Error Occurred");
                }
              })
            }
          })
          $("#btn_add_all_item").on("click", function () {
            var category = $('#category_add :selected').val();
            if(category!=null && category!='' && category!='Select Category' && category!='all'){
              // Get Materials
              $.post("<?php echo base_url() ?>material/select_list",{category:category},function(data) {
                var obj = $.parseJSON(data);
                var i=0;
                if(obj.count>0) {
                  while (i < obj.data.length) {
                    //      Check Already Added to Cart
                    var already_added=0;
                    $(".item_material_id").each(function(){
                      if($(this).val()==obj.data[i]['material_id']){
                        already_added=1;
                      }
                    });
                    if(already_added==0){
                      <?php if ($this->config->item('Material_sale_price_category_enable') == 1){ ?>
                        var sprice_cat = $("#sale_price_category").val();
                        sale_price = obj.data[i]['sale_price'+sprice_cat];
                        <?php }else{?>
                          sale_price = obj.data[i]['unit_price'];
                          <?php } ?>
                          // $('#table_items').dataTable().fnDestroy();
                          var counter = parseInt($("#current_row_count").val());
                          var actual_row_count = parseInt($("#actual_row_count").val());
                          var newRow = '<tr class="row_'+counter+'">';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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 item_slno" data-sl-no="' + (counter+1) + '" name="item[sl_no]['+(counter)+']" value="' + (actual_row_count+1) + '"/></div></div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                          // newRow += '<input type="text" readonly class="form-control m-input" name="item[material_name]['+(counter)+']" value="'+obj.name[0]+'" id="material_name_' + (counter+1) + '"/></div>';
                          newRow += "<input type='text' readonly class='form-control m-input' name='item[material_name]["+(counter)+"]' value='"+obj.data[i]['material_name']+"' id='material_name_" + (counter+1) + "'/></div>";
                          newRow += '<input type="hidden" name="item[material_id]['+(counter)+']" value="'+obj.data[i]['metrial_id']+'" id="material_id_' + (counter+1) + '" class="item_material_id"/>';
                          newRow += '<input type="hidden" name="item[unit_id]['+(counter)+']" value="'+obj.data[i]['unit_id']+'" id="unit_id_' + (counter+1) + '"/>';
                          newRow += '</div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                          newRow += '<input type="text" readonly class="form-control m-input" value="'+obj.data[i]['unit_name']+'" name="item[unit_name]['+(counter)+']" id="unit_name_' + (counter+1) + '"/></div>';
                          newRow += '</div></td>';
                          newRow += '<td style="display:none"><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 quantity" data-sl-no="' + (counter+1) + '" value="'+obj.data[i]['unit_price']+'" name="item[unit_cost]['+(counter)+']" id="unit_cost_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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  item_rate_fields unit_price_field" value="'+sale_price+'"  data-sl-no="' + (counter+1) + '" name="item[unit_price]['+(counter)+']" id="unit_price_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td style="display:none"><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input"  value="" data-sl-no="' + (counter+1) + '" name="item[available_qty]['+(counter)+']" id="available_qty_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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 item_rate_fields quantity_field"  value="1" data-sl-no="' + (counter+1) + '" name="item[quantity]['+(counter)+']" id="quantity_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" required class="form-control m-input item_disc_amount item_rate_fields" value="0" data-sl-no="' + (counter+1) + '" name="item[disc_amount]['+(counter)+']" id="disc_amount_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input item_taxable_amount" value="'+sale_price+'" data-sl-no="' + (counter+1) + '" name="item[taxable_amount]['+(counter)+']" id="taxable_amount_' + (counter+1) + '"/></div></div></td>';

                          <?php
                          $tax_percent = $this->config->item('Tax_tax_percent'); ?>
                          newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><select class="form-control m-bootstrap-select m-bootstrap-select--air m-bootstrap-select--pill m_selectpicker item_tax_percent item_rate_fields" data-sl-no="' + (counter+1) + '" name="item[tax_percent]['+(counter)+']" id="tax_percent_' + (counter+1) + '" title="Tax %">';
                          <?php
                          $tax_percent = $this->config->item('Tax_tax_percent');
                          foreach($tax_percent as $row){
                            $selected_tax='';
                            if($row->tax_percentage==0){
                              $selected_tax='selected';
                            }
                            ?>
                            newRow += '<option <?php echo $selected_tax?> data-tax-percent="<?php echo $row->tax_percentage?>" value="<?php echo $row->tax_id?>"><?php echo $row->tax_name?></option>';
                            <?php } ?>
                            newRow += '</select></div><input type="hidden" value="0" data-sl-no="' + (counter+1) + '" name="item[tax_percentage]['+(counter)+']" id="tax_percentage_' + (counter+1) + '"></td>';
                            newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" readonly class="form-control m-input item_tax_amount" value="0" data-sl-no="' + (counter+1) + '" name="item[tax_amount]['+(counter)+']" id="tax_amount_' + (counter+1) + '"/></div></div></td>';

                            newRow += '<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 item_total_amount" value="'+sale_price+'" name="item[total_amount]['+(counter)+']" id="total_amount_' + (counter+1) + '"/></div></div></td>';
                            newRow += '<td><a href="javascript:" data-row-sl-no='+counter+' class="ibtnDel btn btn-sm btn-danger btn-icon-only m-btn--pill" ><i class="fa fa-trash"></i></td>';
                            newRow += '</tr>';

                            // newRow += '<tr class="row_'+counter+'">';
                            // newRow += '<td></td>';
                            // newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input placeholder="Item Code" type="text" class="form-control m-input" data-sl-no="' + (counter+1) + '" name="item[item_code]['+(counter)+']" value="'+obj.data[i]['item_code']+'" id="item_code_' + (counter+1) + '"/></div></div></td>';
                            // newRow += '<td style="display:none"></td>';
                            // newRow += '<td style="display:none"></td>';
                            // newRow += '<td colspan="8"><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input placeholder="Description Here" type="text" class="form-control m-input" data-sl-no="' + (counter+1) + '" name="item[description]['+(counter)+']" id="description_' + (counter+1) + '"/></div></div></td>';
                            // newRow += '<td></td>';
                            // newRow += '</tr>';

                            $("#table_body").append(newRow);
                            counter++;
                            actual_row_count++;
                            $("#current_row_count").val(counter);
                            $("#actual_row_count").val(actual_row_count);

                            $(".m_selectpicker").selectpicker();
                            $('.m_selectpicker').selectpicker('refresh');
                            $("#tax_percent_"+counter).val(obj.data[i]['material_tax_percent']).trigger('change');
                            $("#tax_percent_"+counter).selectpicker('refresh');

                            i++;
                            item_table();
                            calculate_summary();

                          }
                          else{
                            toastr["error"]("Item Already Added to Cart", "Already Added");
                          }

                        }
                        // Clear Selectbox Selection
                        $("#category_add").val("").trigger('change');
                      }else{
                        toastr["error"]("Some Error Associated with Selected Material", "Error Occurred");
                      }
                    })
                  }else{
                    toastr["warning"]("Please Select a Category From List", "Select Category");
                  }

                });


                $("#table_body").on("click", ".ibtnDel", function (event) {
                  var row_sl_no = $(this).data('row-sl-no');
                  var counter = parseInt($("#actual_row_count").val());
                  $('.row_'+row_sl_no).remove();
                  counter -= 1;
                  $("#actual_row_count").val(counter);

                  //rearrange higher sl no
                  var new_sl_no = 0;
                  $(".item_slno").each(function () {
                    new_sl_no++;
                    $(this).val(new_sl_no);
                  })
                });
                function calculate_item_total(sl_no){
                  var unit_price = ($("#unit_price_"+sl_no).val()=='') ? 0 : parseFloat($("#unit_price_"+sl_no).val());
                  var quantity = ($("#quantity_"+sl_no).val()=='') ? 0 : parseFloat($("#quantity_"+sl_no).val());
                  var discount_amount = ($("#disc_amount_"+sl_no).val()=='') ? 0 : parseFloat($("#disc_amount_"+sl_no).val());
                  var taxable_amount = parseFloat((quantity*unit_price)-discount_amount);
                  var tax_amount = 0;
                  var tax_percent = parseFloat($("#tax_percent_"+sl_no+" :selected").data('tax-percent'));
                  var tax_amount = parseFloat((taxable_amount*tax_percent)/100);
                  $("#tax_percentage_"+sl_no).val(tax_percent.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  $("#taxable_amount_"+sl_no).val(taxable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  $("#tax_amount_"+sl_no).val(tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  var net_total = (parseFloat(taxable_amount)+parseFloat(tax_amount));
                  $("#total_amount_"+sl_no).val(net_total.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));

                  calculate_summary();
                }

                $('body').on('change keyup', '.item_rate_fields', function() {
                  var sl_no = $(this).attr('data-sl-no');
                  calculate_item_total(sl_no);
                })
                $('body').on('change keyup', '.bill_inputs', function() {
                  calculate_summary();
                })
                $('body').on('change keyup', '#received_amount', function() {
                  var paid_amount = $(this).val();
                  if(paid_amount>0){
                    $(".received_date_div").show();
                    $("#received_date,#credit_acc").attr('required',true);
                  }else{
                    $(".received_date_div").hide();
                    $("#received_date,#credit_acc").removeAttr('required',true);
                  }
                  $("#purchase_date,#received_date").datepicker( {
                    todayHighlight:!0, orientation:"bottom left", templates: {
                      leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
                    }
                  })
                })
                function calculate_summary(){
                  var total_items = bill_item_total_amount = bill_discount_amount = bill_taxable_amount = bill_tax_amount = bill_round_amount = 0;
                  $(".item_total_amount").each(function(){
                    bill_item_total_amount += +$(this).val();
                  });
                  $(".item_disc_amount").each(function(){
                    bill_discount_amount += +parseFloat($(this).val());
                  });
                  $(".item_taxable_amount").each(function(){
                    bill_taxable_amount += +parseFloat($(this).val());
                  });
                  $(".item_tax_amount").each(function(){
                    bill_tax_amount += +parseFloat($(this).val());
                  });
                  $("#bill_tax_amount").val(bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  $("#bill_net_total_amount").val(bill_taxable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  var bill_grand_total = parseFloat(bill_taxable_amount+bill_tax_amount);
                  $("#bill_grand_total").val(bill_grand_total.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  bill_round_amount = ($("#bill_round_amount").val()=='') ? 0 : parseFloat($("#bill_round_amount").val());
                  var bill_receivable_amount = parseFloat(bill_grand_total-bill_round_amount);
                  $("#bill_receivable_amount").val(bill_receivable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));

                  $("#received_amount").attr('max',Math.ceil(bill_receivable_amount));
                  var received_amount = ($("#received_amount").val()=='') ? 0 : parseFloat($("#received_amount").val());
                  $("#total_received").val(received_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
                  var balance_amount = (bill_receivable_amount-received_amount);
                  $("#balance_amount").val(balance_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));

                }

                $(".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');
                  var items_count = $("#current_row_count").val();
                  var items_count_error =0;
                  if(form_id=='form_items_add' && items_count==0){
                    items_count_error = 1;
                  }
                  if(items_count_error==0){
                    l.validate({
                      rules: {
                        quantity: {
                          number: !0
                        },
                        mobile_number: {
                          required: !0,
                          number: !0,
                          minlength: 8,
                          maxlength: 12
                        }
                      }, 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);
                          if(form_id=='form_items_add'){
                            swal({
                              width: 500,
                              title: obj.flashdata_title,
                              text: obj.flashdata_msg,
                              type: obj.flashdata_type,
                              showCancelButton: !0,
                              confirmButtonText: "View All <?php echo $this->config->item('Quotation_sales_estimation_title') ?>",
                              cancelButtonText: "Add New <?php echo $this->config->item('Quotation_sales_estimation_title') ?>",
                              confirmButtonColor: '#3085d6',
                              cancelButtonColor: '#d33',
                              reverseButtons: !0,
                              closeOnClickOutside: false,
                              allowOutsideClick: false,
                              html: "<br>" +
                              '<a href="<?php echo base_url()?>sales_estimation/profile/'+obj.estimation_id+'"  class="SwalBtn1  btn btn-primary m-btn m-btn--custom customSwalBtn">' + 'View <?php echo $this->config->item('Quotation_sales_estimation_title') ?>' + '</button>'
                            }).then(function(e) {
                              e.value ? window.location.replace("<?php echo base_url()?>sales_estimation/") : "cancel" === e.dismiss && location.reload()
                            })
                          }else{
                            select_customer();
                            select_category();
                            select_material();
                            select_units();
                          }

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

              });
              </script>
              <script>
              $("#addrow_terms").on("click", function() {
                var i = parseInt($('#current_row_count_terms_and_conditions').val());
                var new_i = i + 1;
                console.log(new_i);

                var new_row = '<tr class="row_' + i + '">';
                new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><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 item_slno" data-sl-no="' + new_i + '" name="terms[sl_no][' + i + ']" value="' + new_i + '"/></div></div></td>';
                new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><textarea rows="2" class="form-control m-input m-input--pill m-input--air" name="terms[description][' + i + ']" id="description_' + new_i + '"/></textarea></div></td><td>';
                new_row += '<a href="javascript:" data-row-sl-no="' + i + '" class="ibtnDel_terms btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td></tr>';

                $('#table_body_terms').append(new_row);
                $('#current_row_count_terms_and_conditions').val(new_i);
              });

              $("#table_body_terms").on("click", ".ibtnDel_terms", function(event) {
                var sl_no = $(this).attr("data-sl-no");

                var counter = parseInt($("#current_row_count_terms_and_conditions").val());
                $(this).closest("tr").remove();
                counter -= 1;
                $("#current_row_count_terms_and_conditions").val(counter);

              });
              </script>
