<?php $this->view("includes/Inc_pagehead");?>
<!-- Page Styles Goes Here-->
<style>
.m-form .m-form__group {
  padding-top: 0px;
  padding-bottom: 0px;
}
.table-bordered th, .table-bordered td {
  padding-left: .25rem;
  padding-right: .25rem;
}
</style>

<?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">
          Edit Purchase Bill
        </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().'purchases' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Edit Purchase Bill
              </span>
            </a>
          </li>


        </ul>
      </div>
      <div>

      </div>
    </div>
  </div>
  <!-- END: Subheader -->
  <div class="m-content">
    <form autocomplete="off" id="form_purchase_edit" data-form-type="purchase_update" method="post" action="<?php echo base_url()?>purchases/update" enctype="multipart/form-data" class="m-form m-form--fit m-form--state m-form--label-align-right " >
      <div class="m-portlet m-portlet--full-height">
        <div class="m-portlet__head">
          <div class="m-portlet__head-caption">
            <div class="m-portlet__head-title">
              <h3 class="m-portlet__head-text">
                Edit Purchase Bill #<?php echo $purchase_data->purchase_id?>  <?php if($purchase_data->purchase_order_id!='' && $purchase_data->purchase_order_id!=0){ echo ',    For Purchase Order ID : #'.$purchase_data->purchase_order_id;}?>
                </h3>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-12">
              <div class="modal-body">
                <div class="m-form__content padding-0">
                  <div class="m-alert m-alert--icon alert alert-warning m--hide" role="alert" id="form_material_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 class="row">
                    <div class="col-lg-6">
                      <?php

                      $column_size='4';

                      ?>
                      <div class="row">
                        <div class="col-lg-6">
                          <div class="form-group m-form__group" >
                            <label for="user_name">
                              Purchased to
                            </label>
                            <?php if($purchase_order_id!='' && $purchase_order_id!=0){ ?>
                              <div class="input-group m-input-group--pill m-input-group--air date">
                                <input disabled type="text" class="form-control m-input" value="<?php echo $purchase_order_data->location_name?>" >
                              </div>
                              <input  type="hidden" name="location" value="<?php echo $purchase_order_data->location_id?>" >
                            <?php }else{?>
                              <div class="m-select2 m-select2--air m-select2--pill ">
                                <select required id="location_add" name="location" 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($this->config->item('app_module_stock_management')==1){
                                      if($row->location_type=='work_site'){
                                        $location_name .= " [Work Site]";
                                      }elseif($row->location_type=='ware_house'){
                                        $location_name .= " [Warehouse]";
                                      }
                                    }
                                    ?>
                                    <option data-work-status="<?php echo $row->work_status?>" data-work_id="<?= $row->work_id ?>" value="<?php echo $row->location_id?>"><?php echo $location_name?></option>
                                    <?php
                                  endforeach;
                                  ?>
                                </select>
                              </div>
                            <?php } ?>
                          </div>
                        </div>
                        <div class="col-lg-6 padding-0">
                          <div class="form-group m-form__group" >
                            <label for="user_name">
                              Supplier Name
                            </label>
                            <?php if($purchase_order_id!='' && $purchase_order_id!=0){ ?>
                              <div class="input-group m-input-group--pill m-input-group--air date">
                                <input disabled type="text" class="form-control m-input" value="<?php echo $purchase_order_data->supplier_name?>" >
                              </div>
                              <input  type="hidden" name="supplier" value="<?php echo $purchase_order_data->supplier_id?>" >
                            <?php }else{?>
                              <div class="input-group m-input-group m-input-group--pill">
                                <div class="input-group-prepend" id='suppler_add_btn'>
                                  <a href="#supplier_add_modal"   data-toggle="modal" data-target="#supplier_add_modal" class="btn btn-focus">
                                    <i class="fa fa-plus-circle"></i>
                                  </a>
                                </div>
                                <select style="width: 80%" class="form-control m-select2 m-select2-general" required id="supplier_add" name="supplier" data-placeholder="Select Supplier">

                                </select>
                              </div>
                            <?php } ?>
                            <span class="m-form__help"></span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="col-lg-6">
                      <div class="row" style="padding-right: 15px">
                        <div class="col-lg-<?php echo $column_size;?> padding-0">
                          <div class="form-group m-form__group" >
                            <label for="user_name">
                              Bill Date
                            </label>
                            <div class="m-input-icon m-input-icon--right">
                              <input value="<?php echo date('d-m-Y',strtotime($purchase_data->purchase_date))?>"  data-date-format="dd-mm-yyyy" id="purchase_date" required type="text" name="purchase_date" class="form-control m-input  m-input--pill m-input--air " placeholder="Purchase Date" >
                              <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-calendar"></i></span></span>
                            </div>
                          </div>
                          <span class="m-form__help"></span>
                        </div>
                        <div class="col-lg-<?php echo $column_size;?> padding-0">
                          <div class="form-group m-form__group" >
                            <label for="user_name">
                              Invoice No
                            </label>
                            <div class="m-input-icon m-input-icon--right">
                              <input value="<?php echo $purchase_data->bill_invoice_no?>" type="text" name="invoice_no" class="form-control m-input m-input--pill m-input--air  " placeholder="Bill Invoice No" >
                              <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                            </div>
                          </div>
                          <span class="m-form__help"></span>
                        </div>
                        <div class="col-lg-<?php echo $column_size;?> padding-0">
                          <div class="form-group m-form__group" >
                            <label for="user_name">
                              Vehicle No
                            </label>
                            <div class="m-input-icon m-input-icon--right">
                              <input  type="text" value="<?php echo $purchase_data->vehicle_no?>" style="text-transform:uppercase" name="vehicle_no" class="form-control m-input m-input--pill m-input--air  " placeholder="Vehicle No" >
                              <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-tag"></i></span></span>
                            </div>
                          </div>
                          <span class="m-form__help"></span>
                        </div>

                      </div>
                    </div>
                    <input type="hidden" name="purchase_id" value="<?php echo $purchase_data->purchase_id?>">
                    <input type="hidden" name="redirect_url" value="<?php echo base_url(uri_string())?>" >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row"  >
          <div class="col-lg-9" >
            <div class="m-portlet ">
              <div class="m-portlet__head">
                <div class="m-portlet__head-caption">
                  <div class="m-portlet__head-title">
                    <h4 class="m-portlet__head-text">Add Items to Cart</h4>
                  </div>
                </div>
              </div>
              <div class="m-portlet__body">
                <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">
                        <?php if ($this->session->userdata('user_role') != 'supervisor'){?>
                        <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>
                      <?php } ?>
                        <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 style="text-align:center">
                          <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){ ?>
                            <th style="width:10%">Sl No</th>
                            <th style="width:25%">Material</th>
                            <th style="width:9%">Unit</th>
                            <th style="width:12%">Qty</th>
                            <th style="width:13%"><div class="m-form__group form-group"><div class="m-checkbox-list"><label style="color: white" class="m-checkbox m-checkbox--bold m-checkbox--state-danger">Unit Price <input type="checkbox" id="amount_type_checkbox_unit_price" class="amount_type_checkbox" value="unit_price"><span></span></label></div></div></th>
                            <th style="width:9%"><?php echo $this->config->item('Tax_tax_name')." %" ?></th>
                            <th style="width:10%"><?php echo $this->config->item('Tax_tax_name')." Amt" ?></th>
                            <th style="width:18%"><div class="m-form__group form-group"><div class="m-checkbox-list"><label style="color: white" class="m-checkbox m-checkbox--bold m-checkbox--state-danger">Total Amt <input type="checkbox" id="amount_type_checkbox_total"  class="amount_type_checkbox" value="total"><span></span></label></div></div></th>
                            <th style="width:6%">&nbsp;</th>
                          <?php }else{ ?>
                            <th style="width:10%">Sl No</th>
                            <th style="width:30%">Material</th>
                            <th style="width:12%">Unit</th>
                            <th style="width:13%">Qty</th>
                            <th style="width:16%"><div class="m-form__group form-group"><div class="m-checkbox-list"><label style="color: white" class="m-checkbox m-checkbox--bold m-checkbox--state-danger">Unit Price <input type="checkbox" id="amount_type_checkbox_unit_price" class="amount_type_checkbox" value="unit_price"><span></span></label></div></div></th>
                            <th style="width:19%"><div class="m-form__group form-group"><div class="m-checkbox-list"><label style="color: white" class="m-checkbox m-checkbox--bold m-checkbox--state-danger">Total Amt <input type="checkbox" id="amount_type_checkbox_total"  class="amount_type_checkbox" value="total"><span></span></label></div></div></th>
                            <th style="width:6%">&nbsp;</th>
                          <?php } ?>
                        </tr>
                      </thead>
                      <tbody id="table_body">
                        <?php
                        $i=0;
                        $description_colspan=4;
                        if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){
                          $description_colspan=6;
                        }
                        foreach ($purchase_items 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 sl_no item_slno" name="item[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;"><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[material_name][<?php echo $i ?>]" value='<?php echo $value->material_name ?>' id="material_name_<?php echo $i+1 ?>"/></div>
                              <input type="hidden" name="item[material_id][<?php echo $i ?>]" value="<?php echo $value->material_id ?>" id="material_id_<?php echo $i+1 ?>" class="item_material_id" />
                              <input type="hidden" name="item[item_id][<?php echo $i ?>]" value="<?php echo $value->item_id ?>" id="item_id_<?php echo $i+1 ?>"/>
                            </div></td>
                            <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" value="<?php echo $value->unit_name ?>" name="item[unit_name][<?php echo $i ?>]" id="unit_name_<?php echo $i+1 ?>"/></div>
                              <input type="hidden" name="item[unit_id][<?php echo $i ?>]" value="<?php echo $value->unit_id ?>" id="unit_id_<?php echo $i+1 ?>"/>
                            </div></td>
                            <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" data-sl-no="<?php echo $i+1 ?>" value="<?php echo $value->quantity ?>" name="item[quantity][<?php echo $i ?>]" id="quantity_<?php echo $i+1 ?>"/></div></div></td>
                            <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" class="form-control m-input numeric_fields item_rate_fields unit_price_field" value="<?php echo $value->unit_price ?>" data-sl-no="<?php echo $i+1 ?>" name="item[unit_price][<?php echo $i ?>]" id="unit_price_<?php echo $i+1 ?>"/></div></div></td>
                            <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){
                              $tax_percent = $this->config->item('Tax_tax_percent'); ?>
                              <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="<?php echo $i+1 ?>" name="item[tax_percent][<?php echo $i ?>]" id="tax_percent_<?php echo $i+1 ?>" title="Tax %">
                                <?php foreach($tax_percent as $row){
                                  $selected_tax='';
                                  if($row->tax_percentage==0){
                                    $selected_tax='selected';
                                  }
                                  ?>
                                  <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 } ?>
                              </select></div></td>
                              <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="<?php echo $value->tax_amount ?>" data-sl-no="<?php echo $i+1 ?>"  name="item[tax_amount][<?php echo $i ?>]" id="tax_amount_<?php echo $i+1 ?>"/></div></div></td>
                            <?php } ?>
                            <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_amount_field item_rate_fields total_amount_field" data-sl-no="<?php echo $i+1 ?>" value="<?php echo $value->total_amount ?>" name="item[total_amount][<?php echo $i ?>]" id="total_amount_<?php echo $i+1 ?>"/></div></div></td>
                            <td><a data-row-sl-no="<?php echo $i ?>" data-sl-no="<?php echo $i+1 ?>" data-item-id="<?php echo $value->item_id ?>" href="javascript:" class="ibtnDel btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td>
                            </tr>
                            <tr class="row_<?php echo $i ?>">
                              <td></td>
                              <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="<?php echo $i+1 ?>" name="item[item_code][<?php echo $i ?>]" value="<?php echo $value->item_code ?>" id="item_code_<?php echo $i+1 ?>"/></div></div></td>
                              <td colspan="<?php echo $description_colspan?>"><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="<?php echo $i+1 ?>" name="item[description][<?php echo $i ?>]" value="<?php echo $value->description ?>" id="description_<?php echo $i+1 ?>"/></div></div></td>
                              <td></td>
                            </tr>
                            <?php
                            $i++;
                          }

                          ?>
                        </tbody>
                      </table>
                      <input type="hidden" value="<?php echo $i ?>" id="current_row_count" name="current_row_count" >
                      <input type="hidden" value="<?php echo $i ?>" id="actual_row_count" name="actual_row_count" >
                      <input type="hidden" value="<?php echo $i ?>" id="items_count"  >
                      <input type="hidden"  id="deleted_items" name="deleted_items" >
                    </div>
                  </div>
                </div>
              </div>
              <div class="m-portlet ">
                <div class="m-portlet__head">
                  <div class="m-portlet__head-caption">
                    <div class="m-portlet__head-title">
                      <h4 class="m-portlet__head-text" >List of Transactions</h4>
                    </div>
                  </div>
                  <div class="m-portlet__head-tools" >
                    <a style="margin-left: 5px;margin-right: 5px" data-bill-type="purchase_bill" data-bill-id="<?php echo $purchase_data->purchase_id?>" id="btn_add_bill_payment" data-toggle="modal"  href="#bill_payment_add_modal" class="btn m-btn--gradient-from-warning m-btn--gradient-to-danger  m-btn  m-btn--icon m-btn--air m-btn--pill">
                      <span>
                        <i class="la la-plus"></i>
                        <span>
                          Add Payment
                        </span>
                      </span>
                    </a>
                  </div>
                </div>
                <div class="m-portlet__body" style="padding-top: 0px">
                  <div class="row">
                    <div class="col-lg-12">
                      <table width="100%" class="table m-table  table-header-fixed table-striped table-bordered table-hover m-table--head-bg-brand nowrap" id="payments_view_table">
                        <thead>
                          <tr class="">
                            <th>Sl No</th>
                            <th>ID</th>
                            <th>Paid Date</th>
                            <th>Bill ID</th>
                            <th>Project</th>
                            <th>Supplier</th>
                            <th></th>
                            <th></th>
                            <th>Bill No</th>
                            <th>Consignee</th>
                            <th>Paid Amount</th>
                            <th>Debit Acc</th>
                            <th>Payment Mode</th>
                            <th>TR Ref No</th>
                            <th>TR Ref Date</th>
                            <th>Remarks</th>
                            <th>Created By</th>
                            <th>Created Date</th>
                            <th>Actions</th>
                            <th>Debit Acc</th>
                          </tr>
                        </thead>
                        <tbody>
                        </tbody>
                      </table>
                    </div>

                  </div>
                </div>
              </div>
              <?php if($loading_charge == 0 || $transportation_charge == 0 ) { ?>
                <div class="m-portlet ">
                  <div class="m-portlet__body" style="padding-top: 5px;">
                    <?php if($loading_charge==0) { ?>
                      <div class="m-form__content" style="margin-top:15px;padding: 0px">
                        <div style="background: white;border: 4px solid #f7f7fa;padding: 15px;margin: 5px;padding-bottom: 0px">
                          <div class="m-section" style="margin-bottom: 10px">
                            <h3 class="m-section__heading">Loading/Unloading Charges</h3>
                            <div class="row">
                              <div class="col-lg-3">
                                <div class="form-group m-form__group" >
                                  <label for="user_name">
                                    Consignee
                                  </label>
                                  <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                                    <input type="text"  name="loading_consignee"  class="form-control bill_inputs  m-input" placeholder="Cosignee Name" 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">
                                    Bill 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" id="loading_bill_amount" name="loading_bill_amount"  class="form-control bill_inputs  m-input" placeholder="Bill Amount" 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">
                                    Paid 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" id="loading_charge" name="loading_charge"  class="form-control bill_inputs  m-input" placeholder="Loading/Unloading Charge" 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">
                                    Balance to Pay
                                  </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 readonly type="text" id="loading_balance_amount" name="loading_balance_amount"  class="form-control bill_inputs  m-input" placeholder="Loading/Unloading Charge" 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 transaction_details_div_2" style="display: none;" >
                                  <label for="user_name">
                                    Paid Date
                                  </label>
                                  <div class="input-group m-input-group--pill m-input-group--air date">
                                    <div class="input-group-prepend">
                                      <span class="input-group-text">
                                        <i class="la la-calendar"></i>
                                      </span>
                                    </div>
                                    <input  data-date-format="dd-mm-yyyy" id="paid_date_2"  type="text" name="paid_date_2" class="form-control m-input transaction_required_fields_2  " placeholder="Paid Date" >
                                  </div>                                                    <span class="m-form__help"></span>
                                </div>
                              </div>
                              <div class="col-lg-3">
                                <div class="form-group m-form__group transaction_details_div_2" style="display: none;" >
                                  <label for="user_name">
                                    Paid From Account
                                  </label>
                                  <div class="m-select2 m-select2--air m-select2--pill">
                                    <select required id="debit_acc_2" name="debit_acc_2" style="width: 100%" class="form-control m-input transaction_required_fields_2"  aria-describedby="basic-addon1" data-placeholder="Select Debit Acc">
                                      <?php
                                      foreach($this->config->item('account_heads') as $row):
                                        $selected="";
                                        if($row->acc_head_id==1){
                                          $selected="selected";
                                        }
                                        ?>
                                        <option <?php echo $selected?> value="<?php echo $row->acc_head_id?>"><?php echo $row->acc_head_name?></option>
                                        <?php
                                      endforeach;
                                      ?>
                                    </select>
                                  </div>
                                  <span class="m-form__help"></span>
                                </div>
                              </div>
                              <div class="col-lg-3">
                                <div class="form-group m-form__group transaction_details_div_2" style="display: none;" >
                                  <label for="user_name">
                                    Payment Mode
                                  </label>
                                  <div class="m-select2 m-select2--air m-select2--pill">
                                    <select id="payment_mode_add_2" name="payment_mode_2" style="width: 100%" class="form-control m-input transaction_required_fields_2"  aria-describedby="basic-addon1">
                                      <option selected disabled>Select Payment Mode</option>
                                      <?php
                                      foreach($this->config->item('payment_modes') as $row):
                                        ?>
                                        <option value="<?php echo $row?>"><?php echo $row?></option>
                                        <?php
                                      endforeach;
                                      ?>
                                    </select>
                                  </div>
                                  <span class="m-form__help"></span>
                                </div>
                              </div>
                            </div>
                            <div class="row transaction_details_div_2" style="display: none;" >

                            </div>
                          </div>
                        </div>
                      </div>
                    <?php } ?>
                    <?php if($transportation_charge==0) { ?>
                      <div class="m-form__content" style="margin-top:15px;padding: 0px">
                        <div style="background: white;border: 4px solid #f7f7fa;padding: 15px;margin: 5px;padding-bottom: 0px">
                          <div class="m-section" style="margin-bottom: 10px">
                            <h3 class="m-section__heading">Transportation Charges</h3>
                            <div class="row">
                              <div class="col-lg-3">
                                <div class="form-group m-form__group" >
                                  <label for="user_name">
                                    Consignee
                                  </label>
                                  <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                                    <input type="text"  name="transportation_consignee"  class="form-control bill_inputs  m-input" placeholder="Cosignee Name" 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">
                                    Bill 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" id="transportation_bill_amount" name="transportation_bill_amount"  class="form-control bill_inputs  m-input" placeholder="Bill Amount" 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">
                                    Paid 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" id="transportation_charge" name="transportation_charge"  class="form-control bill_inputs  m-input" placeholder="Transportation Charge" 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">
                                    Balance to Pay
                                  </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 readonly type="text" id="transportation_balance_amount" name="transportation_balance_amount"  class="form-control bill_inputs  m-input" placeholder="Loading/Unloading Charge" 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 transaction_details_div_3" style="display: none;" >
                                  <label for="user_name">
                                    Paid Date
                                  </label>
                                  <div class="input-group m-input-group--pill m-input-group--air date">
                                    <div class="input-group-prepend">
                                      <span class="input-group-text">
                                        <i class="la la-calendar"></i>
                                      </span>
                                    </div>
                                    <input  data-date-format="dd-mm-yyyy" id="paid_date_3"  type="text" name="paid_date_3" class="form-control m-input transaction_required_fields_3  " placeholder="Paid Date" >
                                  </div>                                                    <span class="m-form__help"></span>
                                </div>
                              </div>
                              <div class="col-lg-3">
                                <div class="form-group m-form__group transaction_details_div_3" style="display: none;" >
                                  <label for="user_name">
                                    Paid From Account
                                  </label>
                                  <div class="m-select2 m-select2--air m-select2--pill">
                                    <select required id="debit_acc_3" name="debit_acc_3" style="width: 100%" class="form-control m-input transaction_required_fields_3"  aria-describedby="basic-addon1" data-placeholder="Select Debit Acc">
                                      <?php
                                      foreach($this->config->item('account_heads') as $row):
                                        $selected="";
                                        if($row->acc_head_id==1){
                                          $selected="selected";
                                        }
                                        ?>
                                        <option <?php echo $selected?> value="<?php echo $row->acc_head_id?>"><?php echo $row->acc_head_name?></option>
                                        <?php
                                      endforeach;
                                      ?>
                                    </select>
                                  </div>
                                  <span class="m-form__help"></span>
                                </div>
                              </div>
                              <div class="col-lg-3">
                                <div class="form-group m-form__group transaction_details_div_3" style="display: none;" >
                                  <label for="user_name">
                                    Payment Mode
                                  </label>
                                  <div class="m-select2 m-select2--air m-select2--pill">
                                    <select id="payment_mode_add_3" name="payment_mode_3" style="width: 100%" class="form-control m-input transaction_required_fields_3"  aria-describedby="basic-addon1">
                                      <option selected disabled>Select Payment Mode</option>
                                      <?php
                                      foreach($this->config->item('payment_modes') as $row):
                                        ?>
                                        <option value="<?php echo $row?>"><?php echo $row?></option>
                                        <?php
                                      endforeach;
                                      ?>
                                    </select>
                                  </div>
                                  <span class="m-form__help"></span>
                                </div>
                              </div>
                            </div>
                            <div class="row transaction_details_div_3" style="display: none;" >

                            </div>
                          </div>
                        </div>
                      </div>
                    <?php } ?>
                  </div>
                </div>
              <?php } ?>
              <?php if($loading_charge > 0 || $transportation_charge > 0) { ?>
                <div class="m-portlet ">
                  <div class="m-portlet__head">
                    <div class="m-portlet__head-caption">
                      <div class="m-portlet__head-title">
                        <h4 class="m-portlet__head-text" >List of Other Charges</h4>
                      </div>
                    </div>
                    <div class="m-portlet__head-tools" >

                    </div>
                  </div>
                  <div class="m-portlet__body" style="padding-top: 0px">
                    <div class="row">
                      <div class="col-lg-12">
                        <table width="100%" class="table m-table  table-header-fixed table-striped table-bordered table-hover m-table--head-bg-brand nowrap" id="other_charges_view_table">
                          <thead>
                            <tr class="">
                              <th>Sl No</th>
                              <th>ID</th>
                              <th>Paid Date</th>
                              <th>Bill ID</th>
                              <th>Project</th>
                              <th>Supplier</th>
                              <th></th>
                              <th></th>
                              <th>Bill No</th>
                              <th>Consignee</th>
                              <th>Paid Amount</th>
                              <th>Debit Acc</th>
                              <th>Payment Mode</th>
                              <th>TR Ref No</th>
                              <th>TR Ref Date</th>
                              <th>Remarks</th>
                              <th>Created By</th>
                              <th>Created Date</th>
                              <th>Actions</th>
                              <th>Debit Acc</th>
                            </tr>
                          </thead>
                          <tbody>
                          </tbody>
                        </table>
                      </div>

                    </div>
                  </div>
                </div>
              <?php } ?>
            </div>
            <div class="col-lg-3">
              <div class="m-portlet m-portlet--full-height" style="padding-bottom: 30px;">
                <div class="m-portlet__body" style="padding: 0px">
                  <div class="m-form__content" style="padding-bottom: 20px;" >
                    <br/>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Bill Grand 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="<?php echo number_format($purchase_data->bill_total_amount,$this->config->item('Currency_amount_decimals_2'),'.','')?>" readonly type="text" name="bill_total_amount" id="bill_total_amount" class="form-control m-input m-input--solid" placeholder="Bill Total Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Bill Discount 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="<?php echo number_format($purchase_data->bill_discount_amount,$this->config->item('Currency_amount_decimals_2'),'.','')?>" required type="text" id="bill_discount_amount" name="bill_discount_amount"  class="form-control bill_inputs m-input " placeholder="Bill Discount Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group" style="display: none">
                      <label for="user_name">
                        Commission 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="<?php echo number_format($purchase_data->bill_commission_amount,$this->config->item('Currency_amount_decimals_2'),'.','')?>" required type="text" id="commission_amount" name="commission_amount"  class="form-control bill_inputs m-input" placeholder="Commission Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Tax 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="<?php echo number_format($purchase_data->bill_tax_amount,$this->config->item('Currency_amount_decimals_2'),'.','');?>" required type="text" id="bill_tax_amount" name="bill_tax_amount"  class="form-control bill_inputs m-input " placeholder="Bill GST Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Other Charges
                      </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="<?php echo number_format($purchase_data->bill_other_amount,$this->config->item('Currency_amount_decimals_2'),'.','');?>" required type="text" id="bill_other_amount" name="bill_other_amount"  class="form-control bill_inputs m-input " placeholder="Other Charges" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        TDS 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="<?php echo number_format($purchase_data->bill_tds_amount,$this->config->item('Currency_amount_decimals_2'),'.','');?>" required type="text" id="bill_tds_amount" name="bill_tds_amount"  class="form-control bill_inputs m-input " placeholder="Bill TDS Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <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="<?php echo number_format($purchase_data->bill_round_amount,$this->config->item('Currency_amount_decimals_2'),'.','');?>" required type="number" id="bill_round_amount" name="bill_round_amount"  class="form-control bill_inputs m-input " placeholder="Bill Round Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Payable 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="<?php echo number_format($purchase_data->bill_payable_amount,$this->config->item('Currency_amount_decimals_2'),'.','')?>" readonly type="text" name="bill_payable_amount" id="bill_payable_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 class="form-group m-form__group" <?php if($this->config->item('app_module_purchase_order')==0 || $purchase_order_id==''){ echo "style='display:none'";}?>>
                      <label for="user_name">
                        Advance Payment (Purchase Order)
                      </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  readonly type="text" id="advance_amount" name="advance_amount"  class="form-control bill_user_input m-input"  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Total Paid
                      </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  readonly type="text" name="total_paid" id="total_paid" class="form-control m-input m-input--solid"  aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Balance 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  readonly type="text" name="balance_amount" id="balance_amount" class="form-control m-input m-input--solid" placeholder="Balance Amount" aria-describedby="basic-addon1">
                      </div>
                      <span class="m-form__help"></span>
                    </div>
                    <div class="form-group m-form__group">
                      <label for="exampleTextarea">Remarks / Notes</label>
                      <textarea class="form-control m-input m-input--air m-input--pill" id="remarks" name="remarks" rows="3"><?php echo $purchase_data->remarks?></textarea>
                    </div>
                    <br/>
                    <div id="bill_uploaded_div" class="form-group m-form__group" style="display: none">
                      <?php if($purchase_data->bill_attachment!=''){?>
                        <table width="100%" class="table table-bordered m-table">
                          <thead>
                            <tr class="">
                              <th>Document</th>
                              <th>Action</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr>
                              <td><a style="word-break: break-all" target="_blank" href="<?php echo base_url().'uploads/bills/'.$purchase_data->bill_attachment?>" style="margin-left: 5px;margin-right: 5px" ><?php echo $purchase_data->bill_attachment?></a></td>
                              <td><a style="margin-left: 5px;margin-right: 5px" id="uploaded_item_delete_btn" href="javascript:;" class="btn btn-sm btn-danger m-btn m-btn--icon  m-btn--icon-only m-btn--pill m-btn--air">
                                <i class="la la-trash"></i>
                              </a>
                              <input type="hidden" name="attachment_delete_status" id="attachment_delete_status" value="0" />
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    <?php } ?>
                  </div>
                  <div class="form-group m-form__group" id="bill_upload_div" style="display: none">
                    <label>
                      Upload Bill Copy
                    </label>
                    <div class="custom-file">
                      <input type="file" class="custom-file-input" name="uploaded_file" id="customFile">
                      <label class="custom-file-label" for="customFile">Choose file</label>
                    </div>
                  </div>
                </div>
              </div>
              <div class="m-portlet__foot m-portlet__foot--fit">
                <div class="m-form__actions m-form__actions" style="padding: 15px" >
                  <div class="row">
                    <div class="col-lg-9 ml-lg-auto">
                      <button type="submit" class="btn btn-focus  form_submit_btn">
                        Save & Update Bill
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </form>
    </div>

    <?php $this->view("modules/include_modals/modal_material_add");?>
    <?php $this->view("modules/include_modals/modal_unit_add");?>
    <?php $this->view("modules/include_modals/modal_supplier_add");?>
    <?php $this->view("modules/include_modals/modal_bills");?>
    <?php $this->view("modules/include_modals/modal_transaction_delete");?>
  </div>
</div>

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

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

<!-- end:: Page -->
<?php $this->view("includes/Inc_sidebar");?>
<?php $this->view("includes/Inc_scripts");?>
<!--begin::Page Snippets -->

<?php $this->view("modules/include_scripts/bill_scripts");?>
<?php $this->view("modules/include_scripts/transaction_scripts");?>
<script>
//    Toggle Sidebar
$("#m_aside_left_minimize_toggle").addClass("m-brand__toggler--active");
$("#body").addClass("m-brand--minimize m-aside-left--minimize");

$("#purchase_menu").addClass('m-menu__item--active m-menu__item--open');
$("#purchase_menu_2").addClass('m-menu__item--active');

$(".m_selectpicker").selectpicker();
$('.m_selectpicker').selectpicker('refresh');


// loading charge
$('body').on('change keyup', '#loading_charge,#loading_bill_amount', function() {
  var loading_charge = parseFloat($('#loading_charge').val());
  var loading_bill_amount = parseFloat($('#loading_bill_amount').val());
  $("#loading_charge").attr('max',loading_bill_amount);
  if(loading_charge>0){
    $(".transaction_details_div_2").show();
    $(".transaction_required_fields_2").attr('required',true);
  }else{
    $(".transaction_details_div_2").hide();
    $(".transaction_required_fields_2").removeAttr('required',true);
  }
  var balance_amount = loading_bill_amount-loading_charge;
  $("#loading_balance_amount").val(balance_amount);
})


// transportation charge
$('body').on('change keyup', '#transportation_charge,#transportation_bill_amount', function() {
  var transportation_charge = parseFloat($("#transportation_charge").val());
  var transportation_bill_amount = parseFloat($("#transportation_bill_amount").val());
  $("#transportation_charge").attr('max',transportation_bill_amount);
  if(transportation_charge>0){
    $(".transaction_details_div_3").show();
    $(".transaction_required_fields_3").attr('required',true);
  }else{
    $(".transaction_details_div_3").hide();
    $(".transaction_required_fields_3").removeAttr('required',true);
  }
  var balance_amount = transportation_bill_amount-transportation_charge;
  $("#transportation_balance_amount").val(balance_amount);

})

$("#debit_acc,#debit_acc_2,#debit_acc_3").select2({
  dropdownParent: $("#form_purchase_edit"),
  placeholder: "Select Debit Acc"
})
$("#payment_mode_add,#payment_mode_add_2,#payment_mode_add_3").select2({
  dropdownParent: $("#form_purchase_edit"),
  placeholder: "Select Payment Mode"
})

<?php
$i=0;
foreach ($purchase_items as $key=>$value){ ?>
  $("#tax_percent_<?php echo $i+1 ?>").selectpicker('val','<?php echo $value->tax_percent ?>');
  <?php
  $i++;
} ?>
$("#purchase_date,#paid_date,#paid_date_edit,#tax_date_add,#paid_date_2,#paid_date_3").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 } ?>
  })

  $('body').on('change', '#payment_mode_add', function() {
    var payment_mode=$('#payment_mode_add :selected').val();
    if(payment_mode=='POST DATED CHEQUE'){
      $('#paid_date').datepicker('destroy');
      $("#paid_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 } ?>
        })
    }else{
      $('#paid_date').datepicker('destroy');
      $("#paid_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 } ?>
        })
    }
  })
  $('body').on('change', '#payment_mode_add_2', function() {
    var payment_mode=$('#payment_mode_add_2 :selected').val();
    if(payment_mode=='POST DATED CHEQUE'){
      $('#paid_date_2').datepicker('destroy');
      $("#paid_date_2").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 } ?>
        })
    }else{
      $('#paid_date_2').datepicker('destroy');
      $("#paid_date_2").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 } ?>
        })
    }
  })
  $('body').on('change', '#payment_mode_add_3', function() {
    var payment_mode=$('#payment_mode_add_3 :selected').val();
    if(payment_mode=='POST DATED CHEQUE'){
      $('#paid_date_3').datepicker('destroy');
      $("#paid_date_3").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 } ?>
        })
    }else{
      $('#paid_date_3').datepicker('destroy');
      $("#paid_date_3").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 } ?>
        })
    }
  })

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

  $("#category_add").select2({
    dropdownParent: $("#form_purchase_edit"),
    placeholder: "Select Category"
  })
  $("#location_add").select2({
    dropdownParent: $("#form_purchase_edit"),
    placeholder: "Select Location",
    templateResult: format_project_dropdown
  })
  $("#supplier_add").select2({
    dropdownParent: $("#form_purchase_edit"),
    placeholder: "Select Suplier"
  })
  $("#tax_percent_add").select2({
    dropdownParent: $("#form_purchase_edit"),
    placeholder: "Select Tax Percentage"
  })
  $("#material_add").select2({
    dropdownParent: $("#form_purchase_edit"),
    placeholder: "Select Material"
  })

  $("#supplier_category_add").select2({
    placeholder: "Select Category",
    dropdownParent: $("#form_supplier_add")
  })
  function select_supplier_category(){
    $('#supplier_category_add').html('');
    $("#supplier_category_add").append("<option disabled selected >Select Category</option>");

    $.post("<?php echo base_url() ?>supplier/select_category",{},function(data) {
      var obj = $.parseJSON(data);
      var i=0;
      if(obj.count>0) {
        while (i < obj.data.length) {
          $("#supplier_category_add").append("<option value=" + obj.data[i]['sup_category_id'] + ">" + obj.data[i]['sup_category_name'] + "</option>");
          i++;
        }
      }
    })
  }
  select_supplier_category();

  selected_supplier="<?php echo $purchase_data->supplier_id?>";
  selected_location="<?php echo $purchase_data->location_id?>";
  $("#location_add").val(selected_location).trigger("change");
  <?php if($purchase_data->purchase_order_id!='0'){ ?>
    $("#supplier_add").attr('disabled',true);
    $("#suppler_add_btn").hide();
    $("#location_add").attr('disabled',true);
    <?php } ?>
    <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){ ?>
      var tax_percent="<?php echo $purchase_data->bill_tax_percent?>";
      $("#tax_percent_add").val(tax_percent).trigger("change");
      <?php } ?>
      select_category();
      select_material();
      select_supplier(selected_supplier);
      select_units();
      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_supplier(){
        $('#supplier_add').html('');
        $("#supplier_add").append("<option disabled selected >Select Supplier</option>");
        $.post("<?php echo base_url() ?>supplier/select",{},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");
            }
          }
        })
      }
      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++;
            }
          }
        })
      }
      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++;
            }
          }
        })
      }
      $('#category_add').on("change", function(e) {
        var category = $('#category_add :selected').val();
        select_material(category);
      });

      var bill_attachment = "<?php echo $purchase_data->bill_attachment?>";
      if(bill_attachment!=''){
        $('#bill_uploaded_div').show();
      }else{
        $('#bill_upload_div').show();
      }
      $('body').on('click', '#uploaded_item_delete_btn', function() {
        $('#bill_uploaded_div').hide();
        $('#bill_upload_div').show();
        $("#attachment_delete_status").val(1);
      })

      </script>
      <script>


      jQuery(document).ready(function() {

        var purchase_payments_table=function() {
          $('#payments_view_table').dataTable().fnDestroy();
          var purchase_id = "<?php echo $purchase_data->purchase_id?>";
          var table = $('#payments_view_table').DataTable({
            "ajax": {
              url: "<?php echo base_url().'accounts/select_account_transactions/purchase_bill' ?>", // json datasource
              type: "post", // type of method  , by default would be get
              data: function (d) {
                d.purchase_id = purchase_id;
              }
            },
            "bProcessing": true,
            "deferRender": true,
            "bDeferRender": true,
            "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
            ],
            "columnDefs": [
              {
                "targets": [ 4,5,6,7,19],
                className: "hidden"
              }
            ],
            'order': false
          });
          $(".hidden").hide();
        }

        var other_charges_table=function() {
          $('#other_charges_view_table').dataTable().fnDestroy();
          var purchase_id = "<?php echo $purchase_data->purchase_id?>";
          var table = $('#other_charges_view_table').DataTable({
            "ajax": {
              url: "<?php echo base_url().'accounts/select_account_transactions/expense_bill' ?>", // json datasource
              type: "post", // type of method  , by default would be get
              data: function (d) {
                d.purchase_id = purchase_id;
              }
            },
            "bProcessing": true,
            "deferRender": true,
            "bDeferRender": true,
            "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
            ],
            "columnDefs": [
              {
                "targets": [ 4,5,6,7,19],
                className: "hidden"
              }
            ],
            'order': false
          });
          $(".hidden").hide();
        }

        purchase_payments_table();
        other_charges_table();

        calculate_summary();

        $('#amount_type_checkbox_unit_price').prop('checked', true);
        $('body').on('change', '.amount_type_checkbox', function() {
          var amount_type = $('.amount_type_checkbox:checkbox:checked').val();
          $('.amount_type_checkbox:checkbox').not(this).prop('checked', false);
          change_amount_type();
        })
        function change_amount_type(){
          var amount_type = $('.amount_type_checkbox:checkbox:checked').val();
          if(amount_type=='unit_price'){
            $(".unit_price_field").removeAttr('readonly',true);
            $(".total_amount_field").attr('readonly',true);
          }else{
            $(".unit_price_field").attr('readonly',true);
            $(".total_amount_field").removeAttr('readonly',true);
          }
        }

        $('body').on('change keyup', '.item_amount_field,.bill_inputs', function() {
          // if($(this).val()==""){
          //   $(this).val(0);
          // }
          bill_total();
        })

        $('body').on('change keyup', '.item_rate_fields', function() {
          var sl_no = $(this).attr('data-sl-no');
          calculate_item_total(sl_no);
        })
        function calculate_item_total(sl_no){
          var unit_price = ($("#unit_price_"+sl_no).val()=='') ? 0 : parseFloat($("#unit_price_"+sl_no).val());
          var total_amount = ($("#total_amount_"+sl_no).val()=='') ? 0 : parseFloat($("#total_amount_"+sl_no).val());
          var quantity = ($("#quantity_"+sl_no).val()=='') ? 0 : parseFloat($("#quantity_"+sl_no).val());
          var amount_type = $('.amount_type_checkbox:checkbox:checked').val();
          var tax_enabled = "<?php echo $this->config->item('Tax_tax_enabled')?>";
          var tax_type = "<?php echo $this->config->item('Tax_purchase_tax_type')?>";
          var tax_percent = parseFloat($("#tax_percent_"+sl_no+" :selected").data('tax-percent'));
          if(amount_type=='unit_price'){
            var tax_amount = 0;
            var total_amount = parseFloat(quantity*unit_price);
            if(tax_enabled==1 && tax_type=='item_wise'){
              var tax_amount = parseFloat((total_amount*tax_percent)/100);
              $("#tax_amount_"+sl_no).val(tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
            }
            var net_total = (parseFloat(total_amount)+parseFloat(tax_amount));
            $("#total_amount_"+sl_no).val(net_total.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          }else{
            var unit_price = tax_amount = 0;
            if(tax_enabled==1 && tax_type=='item_wise'){
              unit_price = total_amount/(quantity+(quantity*tax_percent/100));
              total_amount = parseFloat(quantity*unit_price);
              var tax_amount = parseFloat((total_amount*tax_percent)/100);
              $("#tax_amount_"+sl_no).val(tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
            }else{
              unit_price = (total_amount/quantity);
            }
            $("#unit_price_"+sl_no).val(unit_price.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          }
          bill_total();
        }
        function calculate_summary(){
          var purchase_id = "<?php echo $purchase_data->purchase_id?>";
          $.post("<?php echo base_url() ?>purchases/select_purchase_total",{purchase_id:purchase_id},function(data) {
            var obj = $.parseJSON(data);
            var i=0;
            if(obj.status==1) {
              var tax_type = "<?php echo $this->config->item('Tax_purchase_tax_type')?>";
              var tax_enabled = "<?php echo $this->config->item('Tax_tax_enabled')?>";
              var total_amount = bill_tax_amount = 0;
              $(".item_amount_field").each(function(){
                total_amount += +parseFloat($(this).val());
              });
              if(tax_type=='item_wise' && tax_enabled==1){
                $(".item_tax_amount").each(function(){
                  bill_tax_amount += +parseFloat($(this).val());
                });
                $("#bill_tax_amount").attr('readonly',true);
                total_amount = total_amount-bill_tax_amount;
              }else{
                bill_tax_amount = parseFloat($("#bill_tax_amount").val());
              }
              $("#bill_discount_amount").attr('max',total_amount);
              $("#commission_amount").attr('max',total_amount);
              var commission_amount = parseFloat($("#commission_amount").val());
              var bill_discount_amount = parseFloat($("#bill_discount_amount").val());
              var bill_tds_amount = parseFloat($("#bill_tds_amount").val());
              var bill_other_amount = parseFloat($("#bill_other_amount").val());
              var bill_round_amount = parseFloat($("#bill_round_amount").val());
              var bill_payable_amount = parseFloat(total_amount-(commission_amount+bill_discount_amount)+(bill_tax_amount+bill_other_amount-bill_tds_amount-bill_round_amount));

              if(tax_type=='item_wise' && tax_enabled==1){
                $("#bill_tax_amount").val(bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
              }
              $("#bill_total_amount").val(total_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
              $("#bill_payable_amount").val(bill_payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));

              var advance_amount = parseFloat(obj.advance_amount);
              $("#advance_amount").val(advance_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
              var total_paid = parseFloat(obj.total_paid);
                $("#total_paid").attr('max',bill_payable_amount);
              $("#total_paid").val(total_paid.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
              var balance_amount = parseFloat(obj.balance_amount);
              $("#balance_amount").val(balance_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
              if(balance_amount>0){
                $("#btn_add_bill_payment").show();
              }else{
                $("#btn_add_bill_payment").hide();
              }
              $("#paid_amount").attr('max',balance_amount);
            }
          })
        }
        function bill_total(){
          var tax_type = "<?php echo $this->config->item('Tax_purchase_tax_type')?>";
          var tax_enabled = "<?php echo $this->config->item('Tax_tax_enabled')?>";
          var total_amount = bill_tax_amount = 0;
          $(".item_amount_field").each(function(){
            total_amount += +parseFloat($(this).val());
          });
          if(tax_type=='item_wise' && tax_enabled==1){
            $(".item_tax_amount").each(function(){
              bill_tax_amount += +parseFloat($(this).val());
            });
            $("#bill_tax_amount").attr('readonly',true);
            total_amount = total_amount-bill_tax_amount;
          }else{
            bill_tax_amount = parseFloat($("#bill_tax_amount").val());
          }
          $("#bill_discount_amount").attr('max',total_amount);
          $("#commission_amount").attr('max',total_amount);
          var commission_amount = parseFloat($("#commission_amount").val());
          var bill_discount_amount = parseFloat($("#bill_discount_amount").val());
          var bill_tds_amount = parseFloat($("#bill_tds_amount").val());
          var bill_other_amount = parseFloat($("#bill_other_amount").val());
          var bill_round_amount = parseFloat($("#bill_round_amount").val());
          var bill_payable_amount = parseFloat(total_amount-(commission_amount+bill_discount_amount)+(bill_tax_amount+bill_other_amount-bill_tds_amount-bill_round_amount));

          total_amount = total_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>);
          bill_tax_amount = bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>);
          bill_payable_amount = bill_payable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>);
          if(tax_type=='item_wise' && tax_enabled==1){
            $("#bill_tax_amount").val(bill_tax_amount);
          }
          $("#bill_total_amount").val(total_amount);
          $("#bill_payable_amount").val(bill_payable_amount);

          var total_paid = parseFloat($("#total_paid").val());
          var balance_amount = (bill_payable_amount-total_paid).toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>);
          $("#balance_amount").val(balance_amount);
          if(balance_amount>0){
            $("#btn_add_bill_payment").show();
          }else{
            $("#btn_add_bill_payment").hide();
          }
          $("#paid_amount").attr('max',balance_amount);
        }


        var purchase_item_table=function() {
          var purchase_id = $("#purchase_id").val();
          // 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();
        }
        purchase_item_table();
        change_amount_type();
        $("#btn_add_item").on("click", function () {

          var material_id = $('#material_add :selected').val();
          if(material_id!=null && material_id!='' && material_id!='Select Material'){
            var boq_integration = <?= $this->config->item('boq_purchase_integration');?>;
            var work_id = $('#location_add :selected').data('work_id');
            // if(work_id!=0 && boq_integration == 1)
            // {
            //      Check Already Added to Cart
            var already_added=0;
            <?php if ($this->config->item('Purchase_material_cart_allow_duplication') == 0){?>
            $(".item_material_id").each(function(){
              if($(this).val()==material_id){
                already_added=1;
              }
            });
            <?php }?>
            if(already_added==0){
              // Get Material Details
              $.post("<?php echo base_url() ?>material/select",{id:material_id},function(data) {
                var obj = $.parseJSON(data);
                var i=0;
                if(obj.count==1) {
                  // $('#table_items').dataTable().fnDestroy();
                  var counter = parseInt($("#current_row_count").val());
                  var actual_row_count = parseInt($("#actual_row_count").val());
                  var items_count =  parseInt($("#items_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" name="item[sl_no]['+(counter)+']" value="' + (items_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.name[0]+"' id='material_name_" + (counter+1) + "'/></div>";

                  newRow += '<input type="hidden" name="item[material_id]['+(counter)+']" value="'+obj.id[0]+'" id="material_id_' + (counter+1) + '" class="item_material_id"/>';
                  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.unit_name[0]+'" name="item[unit_name]['+(counter)+']" id="unit_name_' + (counter+1) + '"/></div>';
                  newRow += '<input type="hidden" name="item[unit_id]['+(counter)+']" value="'+obj.unit[0]+'" 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"><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 numeric_fields  item_rate_fields unit_price_field" value="'+obj.unit_price[0]+'" data-sl-no="' + (counter+1) + '" name="item[unit_price]['+(counter)+']" id="unit_price_' + (counter+1) + '"/></div></div></td>';
                  <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){
                    $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 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></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" data-sl-no="' + (counter+1) + '" name="item[tax_amount]['+(counter)+']" id="tax_amount_' + (counter+1) + '"/></div></div></td>';
                      <?php } ?>
                      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 item_amount_field total_amount_field" data-sl-no="' + (counter+1) + '" value="'+obj.unit_price[0]+'" 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-danger btn-icon-only" ><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.item_code[0]+'" id="item_code_' + (counter+1) + '"/></div></div></td>';
                      newRow += '<td colspan="<?php echo $description_colspan?>"><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++;
                      items_count++;
                      actual_row_count++;
                      $("#current_row_count").val(counter);
                      $("#items_count").val(items_count);
                      $("#actual_row_count").val(actual_row_count);
                      // Clear Selectbox Selection
                      $("#material_add").val("").trigger('change');
                      change_amount_type();
                      purchase_item_table();
                      calculate_item_total(counter);
                      $(".m_selectpicker").selectpicker();
                      $('.m_selectpicker').selectpicker('refresh');
                    }else{
                      toastr["error"]("Some Error Associated with Selected Material", "Error Occurred");
                    }
                  })
                }else{
                  toastr["error"]("Item Already Added to Cart", "Already Added");
                }
              }else{
                toastr["warning"]("Please Select a Material From List", "Select Item");
              }


            });
            $("#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",{category:category},function(data) {
                  var obj = $.parseJSON(data);
                  var i=0;
                  if(obj.count>0) {
                    while (i < obj.id.length) {
                      // $('#table_items').dataTable().fnDestroy();
                      var counter = parseInt($("#current_row_count").val());
                      var items_count =  parseInt($("#items_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[i]+'" id="material_name_' + (counter+1) + '"/></div>';
                      newRow += "<input type='text' readonly class='form-control m-input' name='item[material_name]["+(counter)+"]' value='"+obj.name[i]+"' id='material_name_" + (counter+1) + "'/></div>";

                      newRow += '<input type="hidden" name="item[material_id]['+(counter)+']" value="'+obj.id[i]+'" id="material_id_' + (counter+1) + '" class="item_material_id"/>';
                      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.unit_name[i]+'" name="item[unit_name]['+(counter)+']" id="unit_name_' + (counter+1) + '"/></div>';
                      newRow += '<input type="hidden" name="item[unit_id]['+(counter)+']" value="'+obj.unit[i]+'" 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"><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 numeric_fields  item_rate_fields unit_price_field" value="'+obj.unit_price[i]+'" data-sl-no="' + (counter+1) + '" name="item[unit_price]['+(counter)+']" id="unit_price_' + (counter+1) + '"/></div></div></td>';
                      <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise'){
                        $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 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></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" data-sl-no="' + (counter+1) + '" name="item[tax_amount]['+(counter)+']" id="tax_amount_' + (counter+1) + '"/></div></div></td>';
                          <?php } ?>
                          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 item_amount_field total_amount_field" data-sl-no="' + (counter+1) + '" value="'+obj.unit_price[i]+'" 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-danger btn-icon-only" ><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.item_code[i]+'" id="item_code_' + (counter+1) + '"/></div></div></td>';
                          newRow += '<td colspan="<?php echo $description_colspan?>"><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++;
                          items_count++;
                          actual_row_count++;
                          $("#current_row_count").val(counter);
                          $("#items_count").val(items_count);
                          $("#actual_row_count").val(actual_row_count);
                          i++;
                          calculate_item_total(counter);
                          $(".m_selectpicker").selectpicker();
                          $('.m_selectpicker').selectpicker('refresh');
                        }
                        // Clear Selectbox Selection
                        $("#category_add").val("").trigger('change');
                        change_amount_type();
                        purchase_item_table();
                      }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($("#current_row_count").val());
                  $('.row_'+row_sl_no).remove();

                  var items_count =  parseInt($("#items_count").val());
                  items_count -= 1;
                  $("#items_count").val(items_count)

                  // counter -= 1;
                  // $("#current_row_count").val(counter);
                  var deleted_sl_no = $(this).attr('data-sl-no');
                  var deleted_item_id = $(this).attr('data-item-id');

                  // Check Item Id Exist, If Exist, Store it in Deleted  Item Array
                  if(deleted_item_id!='' && deleted_item_id != null){
                    var value = $("#deleted_items").val();
                    value += deleted_item_id+",";
                    $("#deleted_items").val(value);
                  }

                  //rearrange higher sl no
                  var new_sl_no = 0;
                  $(".item_slno").each(function () {
                    new_sl_no++;
                    $(this).val(new_sl_no);
                  })
                  bill_total();
                });

                $(".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 item_count = $("#items_count").val();
                  var form_type = l.attr('data-form-type');
                  var item_count_error = 0;
                  if(item_count==0 && form_type=='purchase_update'){
                    item_count_error = 1;
                  }
                  if(item_count_error==0){
                    l.validate(
                      {
                        rules: {
                          bill_paid_amount: {
                            number: !0,
                            required: !0
                          },
                          bill_total_amount: {
                            min: 0,
                            required: !0
                          },
                          bill_discount_amount: {
                            number: !0,
                            required: !0
                          },
                          commission_amount: {
                            number: !0,
                            required: !0
                          }
                        }, invalidHandler: function (e, r) {
                          var i = $("#" + form_id + "_msg");
                          i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
                        }, submitHandler: function (e) {
                        }
                      }),
                      // ADD validation to item fields
                      $(".numeric_fields").each(function () {
                        if(form_type=="purchase_update"){
                          $("#"+$(this).attr("id")).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);
                            purchase_payments_table();
                            other_charges_table();

                            calculate_summary();
                            if(form_type=="material_create"){
                              select_material();
                              $("#material_add").trigger("change");
                            }else if(form_type=="supplier_create"){
                              select_supplier();
                              $("#supplier_add").trigger("change");
                            }else if(form_type=="supplier_category"){
                              select_supplier_category();
                              toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                            }else if(form_type=="unit_create"){
                              select_units();
                              $("#material_unit_add").trigger("change");
                            }else if(form_type=='purchase_update'){
                              if(obj.location_type=='work_site' && obj.work_id!=0) {
                                swal({
                                  width: 500,
                                  title: obj.flashdata_title,
                                  text: obj.flashdata_msg,
                                  type: obj.flashdata_type,
                                  showCancelButton: !0,
                                  confirmButtonText: "Go to Work Profile",
                                  cancelButtonText: "Add New Purchase Bill",
                                  confirmButtonColor: '#3085d6',
                                  cancelButtonColor: '#d33',
                                  reverseButtons: !0,
                                  closeOnClickOutside: false,
                                  allowOutsideClick: false,
                                  html: "<br>" +
                                  '<a href="<?php echo base_url()?>purchases/profile/'+obj.purchase_id+'"  class="SwalBtn1  btn btn-primary m-btn m-btn--custom customSwalBtn">' + 'View Purchase Bill' + '</button>'
                                }).then(function(e) {
                                  e.value ? window.location.replace("<?php echo base_url()?>work/profile/" + obj.work_id) : "cancel" === e.dismiss && window.location.replace("<?php echo base_url()?>purchases/add/");
                                })
                              }else{
                                swal({
                                  width: 500,
                                  title: obj.flashdata_title,
                                  text: obj.flashdata_msg,
                                  type: obj.flashdata_type,
                                  showCancelButton: !0,
                                  confirmButtonText: "View Purchase Bill",
                                  cancelButtonText: "Add New Purchase Bill",
                                  confirmButtonColor: '#3085d6',
                                  cancelButtonColor: '#d33',
                                  closeOnClickOutside: false,
                                  allowOutsideClick: false,
                                  reverseButtons: !0
                                }).then(function(e) {
                                  e.value ? window.location.replace("<?php echo base_url()?>purchases/profile/"+obj.purchase_id) : "cancel" === e.dismiss && window.location.replace("<?php echo base_url()?>purchases/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");
                        }
                      })
                    )
                  }else{
                    toastr["warning"]("Please Add Items to Cart", "Items Empty!");
                  }

                });

              });

              </script>
