<?php $this->view("includes/Inc_pagehead");?>
<!-- Page Styles Goes Here-->
<style>
.m-form .m-form__group {
  padding-top: 0px;
  padding-bottom: 0px;
}
</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 Order
        </h3>
        <ul class="m-subheader__breadcrumbs m-nav m-nav--inline">
          <li class="m-nav__item m-nav__item--home">
            <a href="#" class="m-nav__link m-nav__link--icon">
              <i class="m-nav__link-icon la la-home"></i>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo base_url().'dashboard'?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Home
              </span>
            </a>
          </li>
          <li class="m-nav__separator">
            -
          </li>
          <li class="m-nav__item">
            <a href="<?php echo base_url().'purchase_order' ?>" class="m-nav__link">
              <span class="m-nav__link-text">
                Edit Purchase Order
              </span>
            </a>
          </li>
        </ul>
      </div>
      <div>

      </div>
    </div>
  </div>
  <!-- END: Subheader -->
  <div class="m-content">
    <form autocomplete="off" id="form_order_edit" data-form-type="order_update" method="post" action="<?php echo base_url()?>purchase_order/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 Order #<?php echo $order_data->order_id?>
              </h3>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            <div class="modal-body">
              <div class="m-form__content">
                <div class="m-alert m-alert--icon alert alert-warning m--hide" role="alert" id="form_material_edit_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-3">
                    <div class="form-group m-form__group">
                      <label for="user_name">
                        Order to Location
                      </label>
                      <!--                                                                        Dropdown From Datatable-->
                      <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">
                          <option selected disabled>Select Location</option>
                          <?php
                          foreach($stock_locations as $row): ?>
                          <option data-work-status="<?php echo $row->work_status?>" value="<?php echo $row->location_id?>"><?php echo $row->location_name?></option>
                          <?php
                        endforeach;
                        ?>
                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
                <div class="col-lg-3">
                  <div class="form-group m-form__group">
                    <label for="user_name">
                      Supplier Name
                    </label>
                    <div class="input-group m-input-group m-input-group--pill">
                      <div class="input-group-prepend">
                        <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">

                      </select>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==2){ echo "display:none";} ?>">
                    <label for="user_name">
                      Vendor No
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input value="<?php echo $order_data->vender_no?>" type="text" name="vendor_no" class="form-control m-input m-input--pill m-input--air" placeholder="Vendor No" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
                <div class="col-lg-2">
                  <div class="form-group m-form__group">
                    <label for="user_name">
                      Order 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 value="<?php echo date('d-m-Y',strtotime($order_data->order_date))?>"  data-date-format="dd-mm-yyyy" id="order_date" required type="text" name="order_date" class="form-control m-input   " placeholder="Order Date" >
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==1){ echo "display:none";} ?>">
                    <label for="user_name">
                      WBS
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input value="<?php echo $order_data->wbs?>" type="text" style="text-transform:uppercase" name="wbs" class="form-control m-input m-input--pill m-input--air"  placeholder="WBS" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==2){ echo "display:none";} ?>">
                    <label for="user_name">
                      Expense Code
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input value="<?php echo $order_data->expense_code?>" type="text" name="expense_code" class="form-control m-input m-input--pill m-input--air" placeholder="Expense Code" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
                <div class="col-lg-2">
                  <div class="form-group m-form__group" >
                    <label for="user_name">
                      Reference No
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input  type="text" name="order_reference_no" value="<?php echo $order_data->reference_no ?>" class="form-control m-input m-input--pill m-input--air" placeholder="Order Reference No" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" >
                    <label for="user_name">
                      Contact Person
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input value="<?php echo $order_data->contact_person_name?>" type="text" name="contact_person" class="form-control m-input m-input--pill m-input--air" placeholder="Contact Person" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
                <div class="col-lg-2">
                  <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==2){ echo "display:none";} ?>">
                    <label for="user_name">
                      Vehicle/Ship No
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input  type="text" value="<?php echo $order_data->vehicle_no?>" style="text-transform:uppercase" name="vehicle_no" class="form-control m-input m-input--pill m-input--air"  placeholder="Vehicle/Ship No" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==1){ echo "display:none";} ?>">
                    <label for="user_name">
                      Service
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input  type="text" value="<?php echo $order_data->service?>" style="text-transform:uppercase" name="service" class="form-control m-input m-input--pill m-input--air"  placeholder="Service" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                  <div class="form-group m-form__group" >
                    <label for="user_name">
                      Contact Person Phone
                    </label>
                    <div class="m-input-icon m-input-icon--right">
                      <input  type="text" value="<?php echo $order_data->contact_person_phone?>" name="contact_person_phone" class="form-control m-input m-input--pill m-input--air" placeholder="Contact Person Phone" >
                      <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                    </div>
                    <span class="m-form__help"></span>
                  </div>
                </div>
                <input type="hidden" name="order_id" value="<?php echo $order_data->order_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>
                      <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && $this->config->item('Purchase_order_tax_enabled')==1){ ?>
                        <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' && $this->config->item('Purchase_order_tax_enabled')==1){
                      $description_colspan=6;
                    }
                    foreach ($order_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' && $this->config->item('Purchase_order_tax_enabled')==1){
                          $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->item_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" >
                <?php if($order_data->purchase_bill_id==0){?>
                  <a style="margin-left: 5px;margin-right: 5px" data-bill-type="purchase_order" data-bill-id="<?php echo $order_data->order_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>
                <?php } ?>
              </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>
          <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">Terms and Conditions</h4>
                </div>
              </div>
            </div>
            <div class="m-portlet__body">

              <div class="row">
                <div class="col-lg-12">
                  <table style="width: 100%;max-width: 100%"  id="table_terms" class="table m-table m-table--head-bg-success order-list table-striped table-bordered table-advance table-hover">
                    <thead>
                      <tr>
                        <th style="width:5%">Sl No</th>
                        <th style="width:20%">Title</th>
                        <th style="width:30%">Description</th>
                        <th style="width:6%">&nbsp;</th>
                      </tr>
                    </thead>
                    <tbody id="table_body_terms">
                      <?php

                      $terms = unserialize($order_data->terms_and_conditions);
                      if($terms!='' && $terms!=null) {
                        $count = sizeof($terms);
                        $i = 0;

                        foreach ($terms as $key => $value) {
                          ?>
                          <tr>
                            <td>
                              <div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input item_slno" data-sl-no="<?php echo $i+1 ?>" name="terms[sl_no][<?php echo $i ?>]" value="<?php echo $i+1 ?>"/></div></div>
                            </td>
                            <td>
                              <div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">
                                <input type="text" class="form-control m-input" name="terms[title][<?php echo $i ?>]" value='<?= $value['title'] ?>' id="title_<?php echo $i+1 ?>"/></div>
                              </div>
                            </td>
                            <td>
                              <div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;">
                                <textarea rows="2" class="form-control m-input m-input--pill m-input--air"  name="terms[description][<?php echo $i ?>]" id="description_<?php echo $i+1 ?>"/><?= $value['description'] ?></textarea>
                              </div>
                            </td>
                            <td><a href="javascript:" data-row-sl-no="<?= $i ?>" class="ibtnDel_terms btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td>
                            </tr>
                            <?php $i++; } } ?>
                          </tbody>
                          <tfoot>
                            <tr>
                              <td colspan="10"  style="text-align: left;border-bottom: 1px solid #e7ecf1;">
                                <button type="button"  class="btn btn-block " id="addrow_terms"><i class="fa fa-plus-square"></i> Add new Terms and Condition</button>
                              </td>
                            </tr>
                          </tfoot>
                        </table>
                        <input type="hidden" value="<?php echo $i ?>" id="current_row_count_terms_and_conditions" name="current_row_count" >
                        <input type="hidden" value="<?php echo $i ?>" id="actual_row_count_terms_and_conditions" name="actual_row_count" >
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-lg-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">
                      <br/>
                      <?php if ($this->config->item('Data_billing_addresses') == 1){?>
                        <div class="form-group m-form__group" >
                          <label for="user_name">
                            Select Billing Address
                          </label>
                          <div class="m-select2 m-select2--air m-select2--pill">
                            <select required style="width: 100%" class="form-control m-select2 form_subcontract_add_select" id="billing_address_id_add"  name="billing_address_id" data-placeholder="Select Billing Address">
                              <option selected disabled>Select Billing Address</option>
                              <?php
                              foreach($billing_address as $row): ?>
                              <option data-address="<?php echo $row->billing_address?>" value="<?php echo $row->id?>"><?php echo $row->title?></option>
                              <?php
                            endforeach;
                            ?>
                          </select>
                        </div>
                      </div>
                      <br/>
                    <?php } ?>
                      <div class="form-group m-form__group" >
                        <label for="user_name">
                          Billing Address
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <textarea rows="4" name="billing_address" class="form-control m-input m-input--pill m-input--air"><?= $order_data->billing_address ?></textarea>
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                      <div class="form-group m-form__group" >
                        <label for="user_name">
                          Delivery Address
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <textarea rows="4" name="delivery_address" class="form-control m-input m-input--pill m-input--air"><?= $order_data->delivery_address ?></textarea>
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                      <div class="form-group m-form__group">
                        <label for="user_name">
                          Delivery Date & Time
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <input  type="text" id="delivery_date_time" name="delivery_date_time" class="form-control m-input m-input--pill m-input--air" value="<?php if($order_data->delivery_date!='0000-00-00 00:00:00'){ echo date('d-m-Y H:i',strtotime($order_data->delivery_date));} ?>" placeholder="Delivery Date & Time" >
                            <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-calendar"></i></span></span>
                          </div>
                          <span class="m-form__help"></span>
                        </div>
                        <span class="m-form__help"></span>
                        <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && $this->config->item('Purchase_order_tax_enabled')==1){ ?>
                          <div class="form-group m-form__group">
                            <label for="user_name">
                              Total Taxable Amount
                            </label>
                            <div class="input-group m-input-group m-input-group--pill m-input-group--air">
                              <div class="input-group-prepend">
                                <span class="input-group-text" id="basic-addon1">
                                  <?php echo $this->config->item('Currency_currency_format'); ?>
                                </span>
                              </div>
                              <input value="0" readonly type="text" name="order_taxable_amount" id="order_taxable_amount" class="form-control m-input m-input--solid" placeholder="Taxable Amount" aria-describedby="basic-addon1">
                            </div>
                            <span class="m-form__help"></span>
                          </div>
                          <div class="form-group m-form__group">
                            <label for="user_name">
                              Total 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="0" readonly type="text" name="order_tax_amount" id="order_tax_amount" class="form-control m-input m-input--solid" placeholder="Tax Amount" aria-describedby="basic-addon1">
                            </div>
                            <span class="m-form__help"></span>
                          </div>
                        <?php } ?>
                        <div class="form-group m-form__group">
                          <label for="user_name">
                            Total Estimated 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 $order_data->total_est_amount?>" readonly type="text" name="order_total_amount" id="order_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="exampleTextarea">Remarks / Notes</label>
                          <textarea class="form-control m-input m-input--air m-input--pill" id="remarks" name="remarks" rows="3"><?php echo $order_data->remarks?></textarea>
                        </div>
                        <br/>
                        <div id="bill_uploaded_div" class="form-group m-form__group" style="display: none">
                          <?php if($order_data->order_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/'.$order_data->order_attachment?>" style="margin-left: 5px;margin-right: 5px" ><?php echo $order_data->order_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 class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==1){ echo "display:none";} ?>">
                        <label for="user_name">
                          Required By
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <input value="<?php echo $order_data->requiredby?>" type="text"  name="required_by" class="form-control m-input m-input--pill m-input--air"  placeholder="Required By" >
                          <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                      <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==1){ echo "display:none";} ?>">
                        <label for="user_name">
                        Delivery Mode
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <input  type="text" value="<?php echo $order_data->delivery_mode?>" name="delivery_mode" class="form-control m-input m-input--pill m-input--air"  placeholder="Delivery Mode" >
                          <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                        </div>
                        <span class="m-form__help"></span>
                      </div>
                      <div class="form-group m-form__group" style="<?php if($this->config->item('Purchase_order_template')==1){ echo "display:none";} ?>">
                        <label for="user_name">
                        Payment Terms
                        </label>
                        <div class="m-input-icon m-input-icon--right">
                          <input  type="text" value="<?php echo $order_data->payment_terms?>" name="payment_terms" class="form-control m-input m-input--pill m-input--air"  placeholder="Payment Terms" >
                          <span class="m-input-icon__icon m-input-icon__icon--right"><span><i class="la la-edit"></i></span></span>
                        </div>
                        <span class="m-form__help"></span>
                      </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_order_menu").addClass('m-menu__item--active m-menu__item--open');
    $("#purchase_order_menu_2").addClass('m-menu__item--active');
    $("#order_date").datepicker( {
      todayHighlight:!0, orientation:"bottom left", templates: {
        leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
      },
      endDate: '+0d',
      <?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 keyup', '#order_paid_amount', function() {
        var paid_amount = $(this).val();
      })
      $("#location_add").select2({
        placeholder: "Select Location",
        dropdownParent: $("#form_order_edit"),
        templateResult: format_project_dropdown
      })
      $("#supplier_add").select2({
        placeholder: "Select Supplier",
        dropdownParent: $("#form_order_edit")
      })
      $("#category_add").select2({
        dropdownParent: $("#form_order_edit"),
        placeholder: "Select Category"
      })
      $("#billing_address_id_add").select2({
        placeholder: "Select Address",
        dropdownParent: $("#form_order_edit")
      })

      $('body').on('change', '#billing_address_id_add', function() {
        var address = $('#billing_address_id_add :selected').data('address');
        $("#billing_address").val(address);
      })
      <?php if ($this->config->item('Data_billing_addresses') == 1){?>
        $("#billing_address_id_add").val('<?php echo $order_data->billing_address_id ?>').trigger('change');
        <?php } ?>
      $("#material_add").select2({
        dropdownParent: $("#form_order_edit"),
        placeholder: "Select Material"
      })
      $("#delivery_date_time").datetimepicker({ todayHighlight:!0,autoclose:!0,format:"dd-mm-yyyy hh:ii"});
      $("#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")
      })
      selected_supplier="<?php echo $order_data->supplier_id?>";
      selected_location="<?php echo $order_data->location_id?>";
      $("#location_add").val(selected_location).trigger("change");
      select_category();
      select_material();
      select_units();
      select_supplier(selected_supplier);
      $(".m_selectpicker").selectpicker();
      $('.m_selectpicker').selectpicker('refresh');
      <?php
      $i=0;
      foreach ($order_items as $key=>$value){ ?>
        $("#tax_percent_<?php echo $i+1 ?>").selectpicker('val','<?php echo $value->tax_percent ?>');
        <?php
        $i++;
      } ?>

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

      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_id){
        $('#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(supplier_id!=''){
              $('#supplier_add').val(supplier_id).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] + "][" + obj.item_code[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 order_attachment = "<?php echo $order_data->order_attachment?>";
      if(order_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);
      })

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

      </script>
      <script>

      jQuery(document).ready(function() {

        calculate_summary();
        $('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 order_tax_enabled = "<?php echo $this->config->item('Purchase_order_tax_enabled')?>";
          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(order_tax_enabled==1 && 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(order_tax_enabled==1 && 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')?>));
          }
          calculate_summary();
        }
        function calculate_summary(){
          var total_amount = bill_tax_amount = 0;
          $(".item_amount_field").each(function(){
            total_amount += parseFloat($(this).val());
          });
          <?php if($this->config->item('Tax_tax_enabled')==1 && $this->config->item('Tax_purchase_tax_type')=='item_wise' && $this->config->item('Purchase_order_tax_enabled')==1){ ?>
            $(".item_tax_amount").each(function(){
              if(isNaN(parseFloat($(this).val()))){
              }else{
                bill_tax_amount += parseFloat($(this).val());
              }
            });
            <?php } ?>

            var taxable_amount = total_amount-bill_tax_amount;
            $("#order_taxable_amount").val(taxable_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
            $("#order_tax_amount").val(bill_tax_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
            $("#order_total_amount").val(total_amount.toFixed(<?php echo $this->config->item('Currency_amount_decimals_2')?>));
          }

          var purchase_order_payment_table=function() {
            $('#payments_view_table').dataTable().fnDestroy();
            var purchase_order_id = "<?php echo $order_data->order_id?>";
            var table = $('#payments_view_table').DataTable({
              "ajax": {
                url: "<?php echo base_url().'accounts/select_account_transactions/purchase_order' ?>", // json datasource
                type: "post", // type of method  , by default would be get
                data: function (d) {
                  d.order_id = purchase_order_id;
                }
              },
              "scrollX" : true,
              scrollX:!0, scrollCollapse:!0,
              "bProcessing": true,
              "deferRender": true,
              "bDeferRender": true,
              bFilter: false,
              "bLengthChange": false,
              "bPaginate": false,
              dom:"<'row'<'col-sm-6 text-left'><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
              "columnDefs": [
                {
                  "targets": [ 4,5,6,7,19],
                  className: "hidden"
                }
              ],
              'order': false
            });
            $(".hidden").hide();
          }
          purchase_order_payment_table();

          var purchase_order_item_table=function() {
            var order_id = "<?php echo $order_data->order_id?>";
            // 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_order_item_table();
          $("#btn_add_item").on("click", function () {
            var material_id = $('#material_add :selected').val();
            if(material_id!=null && material_id!='' && material_id!='Select Material'){
              // 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) {
                  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){
                    // $('#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" data-sl-no="' + (counter+1) + '" name="item[sl_no]['+(counter)+']" value="' + (actual_row_count+1) + '"/></div></div></td>';
                    newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                    // newRow += '<input type="text" readonly class="form-control m-input" name="item[material_name]['+(counter)+']" value="'+obj.name[0]+'" id="material_name_' + (counter+1) + '"/></div>';
                    newRow += "<input type='text' readonly class='form-control m-input' name='item[material_name]["+(counter)+"]' value='"+obj.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' && $this->config->item('Purchase_order_tax_enabled')==1){
                      $tax_percent = $this->config->item('Tax_tax_percent'); ?>
                      newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><select class="form-control m-bootstrap-select m-bootstrap-select--air m-bootstrap-select--pill m_selectpicker item_tax_percent item_rate_fields" data-sl-no="' + (counter+1) + '" name="item[tax_percent]['+(counter)+']" id="tax_percent_' + (counter+1) + '" title="Tax %">';
                      <?php
                      $tax_percent = $this->config->item('Tax_tax_percent');
                      foreach($tax_percent as $row){
                        $selected_tax='';
                        if($row->tax_percentage==0){
                          $selected_tax='selected';
                        }
                        ?>
                        newRow += '<option <?php echo $selected_tax?> data-tax-percent="<?php echo $row->tax_percentage?>" value="<?php echo $row->tax_id?>"><?php echo $row->tax_name?></option>';
                        <?php } ?>
                        newRow += '</select></div></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');
                        $(".m_selectpicker").selectpicker();
                        $('.m_selectpicker').selectpicker('refresh');
                        change_amount_type();
                        purchase_order_item_table();
                        calculate_item_total(counter);
                      }else{
                        toastr["error"]("Item Already Added to Cart", "Already Added");
                      }
                    }else{
                      toastr["error"]("Some Error Associated with Selected Material", "Error Occurred");
                    }
                  })
                }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 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" data-sl-no="' + (counter+1) + '" 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[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]+'" class="item_material_id" id="material_id_' + (counter+1) + '"/>';
                        newRow += '</div></td>';
                        newRow += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air">';
                        newRow += '<input type="text" readonly class="form-control m-input" value="'+obj.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 quantity_field" data-sl-no="' + (counter+1) + '" value="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 unit_price_field" data-sl-no="' + (counter+1) + '" value="'+obj.unit_price[i]+'" name="item[unit_price]['+(counter)+']" id="unit_price_' + (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_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 colspan="5"><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++;
                      }
                      // Clear Selectbox Selection
                      $("#category_add").val("").trigger('change');
                      change_amount_type();
                      purchase_order_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);
                })
                calculate_summary();
              });


              $(".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 = $("#current_row_count").val();
                var form_type = l.attr('data-form-type');
                var item_count_error = 0;

                l.validate(
                  {
                    rules: {
                      order_paid_amount: {
                        number: !0,
                        required: !0
                      },
                      order_total_amount: {
                        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=="order_create"){
                      $("#"+$(this).attr("id")).rules('add', {
                        number: !0
                      });
                    }
                  });
                  if(l.valid()==true){
                    if(item_count==0 && form_type=='order_create'){
                      // Show Confirm Alert
                      swal({
                        title: "Please Confirm Action",
                        text: "Are you Sure to Submit Order Without Adding Items?",
                        type: "warning",
                        showCancelButton: !0,
                        confirmButtonText: "Confirm & Proceed",
                        cancelButtonText: "Close",
                        confirmButtonColor: '#f4516c',
                        cancelButtonColor: '#d33',
                        reverseButtons: !0,
                        closeOnClickOutside: false,
                        allowOutsideClick: false,
                      }).then(function(e) {
                        e.value ? form_submit_function(l,a) : "cancel" === e.dismiss;
                      })
                    }else{
                      form_submit_function(l,a);
                    }
                    function form_submit_function(l,a){
                      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) {
                            $("#"+modal_id).modal('toggle');
                            $("."+form_id+"_fields").val('');
                            $("."+form_id+"_select").val('').trigger("change");
                            a.removeClass("m-loader m-loader--right m-loader--light").attr("disabled", !1);
                            purchase_order_payment_table();
                            toastr[obj.flashdata_type](obj.flashdata_msg, obj.flashdata_title);
                            if(form_type=="material_create"){
                              select_material();
                              $("#material_add").trigger("change");
                            }else if(form_type=="supplier_create"){
                              select_supplier(selected_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();
                              $("#unit").trigger("change");
                            }else if(form_type=='order_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 Order",
                                  confirmButtonColor: '#3085d6',
                                  cancelButtonColor: '#d33',
                                  reverseButtons: !0,
                                  closeOnClickOutside: false,
                                  allowOutsideClick: false,
                                  html: "<br>" +
                                  '<a href="<?php echo base_url()?>purchase_order/profile/'+obj.order_id+'"  class="SwalBtn1  btn btn-primary m-btn m-btn--custom customSwalBtn">' + 'View Purchase Order' + '</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()?>purchase_order/add/");
                                })
                              }else{
                                swal({
                                  width: 500,
                                  title: obj.flashdata_title,
                                  text: obj.flashdata_msg,
                                  type: obj.flashdata_type,
                                  showCancelButton: !0,
                                  confirmButtonText: "View Purchase Order",
                                  cancelButtonText: "Add New Purchase Order",
                                  confirmButtonColor: '#3085d6',
                                  cancelButtonColor: '#d33',
                                  closeOnClickOutside: false,
                                  allowOutsideClick: false,
                                  reverseButtons: !0
                                }).then(function(e) {
                                  e.value ? window.location.replace("<?php echo base_url()?>purchase_order/profile/"+obj.order_id) : "cancel" === e.dismiss && window.location.replace("<?php echo base_url()?>purchase_order/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");
                        }
                      })
                    }
                  }
                });




              });


              $("#addrow_terms").on("click", function () {
                var i = parseInt($('#current_row_count_terms_and_conditions').val());
                var new_i = i + 1;
                var new_row = '<tr class="row_'+i+'">';
                new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input style="padding: 10px" readonly type="text" class="form-control m-input item_slno" data-sl-no="'+new_i+'" name="terms[sl_no]['+i+']" value="'+new_i+'"/></div></div></td>';
                new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><div class="input-group m-input-group m-input-group--pill m-input-group--air"><input type="text" class="form-control m-input" name="terms[title]['+i+']" id="title_'+new_i+'"/></div></div></td>';

                new_row += '<td><div class="form-group m-form__group" style="padding: 0px !important;margin: 0px !important;"><textarea rows="2" class="form-control m-input m-input--pill m-input--air" name="terms[description]['+i+']" id="description_'+new_i+'"/></textarea></div></td><td>';

                new_row += '<a href="javascript:" data-row-sl-no="'+i+'" class="ibtnDel_terms btn btn-danger btn-icon-only" ><i class="fa fa-trash"></i></td></tr>';

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

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

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

              });
              </script>
