<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css_form.php"; ?>
<!-- </copy> -->  
<style type="text/css">
   table.table-bordered > thead > tr > th {
   /* border:1px solid black;*/
   text-align: center;
   }
   .table > tbody > tr > td, 
   .table > tbody > tr > th, 
   .table > tfoot > tr > td, 
   .table > tfoot > tr > th, 
   .table > thead > tr > td, 
   .table > thead > tr > th 
   {
   padding-left: 2px;
   padding-right: 2px;  

   }
</style>
</head>



<body class="hold-transition skin-blue sidebar-mini">
  
<div class="wrapper">
 
 
 <?php include"sidebar.php"; ?>
 
 <?php
    if(!isset($purchase_id)){
      $supplier_id  = $pur_date = $purchase_status = $warehouse_id =
      $reference_no  =
      $other_charges_input          = $other_charges_tax_id =
      $discount_input = $discount_type  = $purchase_note='';
      $pur_date=show_date(date("d-m-Y"));
    }
    else{
      $q2 = $this->db->query("select * from db_purchase where id=$purchase_id");
      $supplier_id=$q2->row()->supplier_id;
      $pur_date=show_date($q2->row()->purchase_date);
      $purchase_status=$q2->row()->purchase_status;
      $warehouse_id=$q2->row()->warehouse_id;
      $reference_no=$q2->row()->reference_no;
      $discount_input=$q2->row()->discount_to_all_input;
      $discount_type=$q2->row()->discount_to_all_type;
      $other_charges_input=$q2->row()->other_charges_input;
      $other_charges_tax_id=$q2->row()->other_charges_tax_id;
      $purchase_note=$q2->row()->purchase_note;

      $items_count = $this->db->query("select count(*) as items_count from db_purchaseitems where purchase_id=$purchase_id")->row()->items_count;
    }
    
    ?>

 

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- **********************MODALS***************** -->
    <?php include"modals/modal_supplier.php"; ?>
    <?php include"modals/modal_purchase_item.php"; ?>
    <!-- **********************MODALS END***************** -->
    <!-- Content Header (Page header) -->
    <section class="content-header">
         <h1>
            <?=$page_title;?>
            <small>Add/Update Purchase</small>
         </h1>
         <ol class="breadcrumb">
            <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
            <li><a href="<?php echo $base_url; ?>purchase"><?= $this->lang->line('purchase_list'); ?></a></li>
            <li><a href="<?php echo $base_url; ?>purchase/add"><?= $this->lang->line('new_purchase'); ?></a></li>
            <li class="active"><?=$page_title;?></li>
         </ol>
      </section>

    <!-- Main content -->
     <section class="content">
               <div class="row">
                <!-- ********** ALERT MESSAGE START******* -->
               <?php include"comman/code_flashdata.php"; ?>
               <!-- ********** ALERT MESSAGE END******* -->
                  <!-- right column -->
                  <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-info " >
                        <!-- style="background: #68deac;" -->
                        
                        <!-- form start -->
                         <!-- OK START -->
                        <?= form_open('#', array('class' => 'form-horizontal', 'id' => 'purchase-form', 'enctype'=>'multipart/form-data', 'method'=>'POST'));?>
                           <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                           <input type="hidden" value='1' id="hidden_rowcount" name="hidden_rowcount">
                           <input type="hidden" value='0' id="hidden_update_rowid" name="hidden_update_rowid">

                          
                           <div class="box-body">
                              <div class="form-group">
                                 <label for="supplier_id" class="col-sm-2 control-label"><?= $this->lang->line('supplier_name'); ?><label class="text-danger">*</label></label>
                                 <div class="col-sm-3">
                                    <div class="input-group">
                                       <select class="form-control select2" id="supplier_id" name="supplier_id"  style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                                          <?php
                                             
                                             $query1="select * from db_suppliers where status=1";
                                             $q1=$this->db->query($query1);
                                             if($q1->num_rows($q1)>0)
                                                { 
                                                  echo "<option value=''>-Select-</option>";
                                                  foreach($q1->result() as $res1)
                                                {
                                                  $selected=($supplier_id==$res1->id) ? 'selected' : '';
                                                  echo "<option selected  value='".$res1->id."'>".$res1->supplier_name ."</option>";
                                                }
                                              }
                                              else
                                              {
                                                 ?>
                                          <option value="">No Records Found</option>
                                          <?php
                                             }
                                             ?>
                                       </select>
                                       <span class="input-group-addon pointer" data-toggle="modal" data-target="#supplier-modal" title="New Supplier?"><i class="fa fa-user-plus text-primary fa-lg"></i></span>
                                       <span class="input-group-addon" id="viewHistory" data-toggle="collapse" data-target="#demo" title="Customer Sale History"><i id="viewHistoryIcon" class="fa fa-eye-slash text-success fa-lg" aria-hidden="true"></i></span>
                                    </div>
                                    <span id="supplier_id_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="pur_date" class="col-sm-2 control-label"><?= $this->lang->line('purchase_date'); ?> <label class="text-danger">*</label></label>
                                 <div class="col-sm-2">
                                    <div class="input-group date">
                                       <div class="input-group-addon">
                                          <i class="fa fa-calendar"></i>
                                       </div>
                                       <input type="text" class="form-control pull-right datepicker"  id="pur_date" name="pur_date" readonly onkeyup="shift_cursor(event,'purchase_status')" value="<?= $pur_date;?>">
                                    </div>
                                    <span id="pur_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 <label for="section_id" class="col-sm-1 control-label">Section<label class="text-danger">*</label></label>
                                 <div class="col-sm-2">
                                    <div class="input-group">
                                       <select class="form-control select2" id="section_id" name="section_id"  style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                                          <?php
                                             $query1="select * from db_section where status=1";
                                             $q1=$this->db->query($query1);
                                             if($q1->num_rows($q1)>0)
                                                { 
                                                  foreach($q1->result() as $res1)
                                                {
                                                  $selected=($section_id==$res1->section_id) ? 'selected' : '';
                                                  echo "<option value='".$res1->section_id."'>".$res1->section_name ."</option>";
                                                }
                                              }
                                              else
                                              {
                                                 ?>
                                          <option value="">No Records Found</option>
                                          <?php
                                             }
                                             ?>
                                       </select>                                       
                                    </div>
                                    <span id="section_id_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                              <div class="form-group" hidden>
                                 <label for="purchase_status" class="col-sm-2 control-label"><?= $this->lang->line('status'); ?> <label class="text-danger">*</label></label>
                                 <div class="col-sm-3">
                                       <select class="form-control select2" id="purchase_status" name="purchase_status"  style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                                         	<!-- <option value="">-Select-</option> -->
                                          <?php 
                                               $received_select = ($purchase_status=='Received') ? 'selected' : ''; 
                                               $pending_select = ($purchase_status=='Pending') ? 'selected' : ''; 
                                               $ordered_select = ($purchase_status=='Ordered') ? 'selected' : ''; 
                                          ?>
              							                <option <?= $received_select; ?> value="Received">Received</option>
              							                <option <?= $pending_select; ?> value="Pending">Pending</option>
              							                <option <?= $ordered_select; ?> value="Ordered">Ordered</option>
                                       </select>
                                    <span id="purchase_status_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                  <label for="reference_no" class="col-sm-2 control-label"><?= $this->lang->line('reference_no'); ?> </label>
                                 <div class="col-sm-3">
                                    <input type="text" value="<?php echo  $reference_no; ?>" class="form-control " id="reference_no" name="reference_no" placeholder="" >
                                    <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 
                              </div>
                              <!-- <div class="form-group">
                                <label for="warehouse_id" class="col-sm-2 control-label"><?= $this->lang->line('warehouse'); ?> <label class="text-danger">*</label></label>
                                 <div class="col-sm-3">
                                       <select class="form-control select2" id="warehouse_id" name="warehouse_id"  style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                                          <?php
                                             
                                             $query1="select * from db_warehouse where status=1";
                                             $q1=$this->db->query($query1);
                                             if($q1->num_rows($q1)>0)
                                                { 
                                                  //echo "<option value=''>-Select-</option>";
                                                  foreach($q1->result() as $res1)
                                                {
                                                  $selected=($warehouse_id==$res1->id) ? 'selected' : '';
                                                  echo "<option $selected  value='".$res1->id."'>".$res1->warehouse_name ."</option>";
                                                }
                                              }
                                              else
                                              {
                                                 ?>
                                          <option value="">No Records Found</option>
                                          <?php
                                             }
                                             ?>
                                       </select>
                                    <span id="warehouse_id_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div> -->
                              <br>
                              <div class="row">
                                 <div class="col-sm-12">
                                    <div id="demo" class="collapse">
                                       <div class="row">
                                          <div class="col-xs-12">
                                          <div class="col-md-6">
                                                <div class="form-group">
                                                <input type="text" class="form-control" id="his_itemname" onkeyup="filterHisData()" placeholder="Search for names.." title="Type in a item name">
                                                </div>
                                          </div>
                                          </div>
                                       </div>
                                       <div class="row">
                                          <div class="col-sm-12">
                                          <div class="table-responsive" style="height: 250px; table-layout: fixed; border-collapse: collapse;">
                                             <table id="example3" class="table table-bordered table-striped" width="100%">
                                                <thead class="bg-primary" style="position: sticky; top: 0px;">
                                                <tr>
                                                <th class="text-center"> #
                                                </th>
                                                <th class="text-center">GRN<br>Code</th>
                                                <th class="text-center">GRN<br>Date</th>
                                                <th class="text-center">Item Name</th>
                                                <th class="text-center">Cost<br>Price</th>
                                                <th class="text-center">Qty</th>
                                                <th class="text-center">Total Price</th>
                                                </tr>
                                                </thead>
                                                <tbody id="hisData" style="overflow: auto;">
                                       
                                                </tbody>
                                             </table>
                                          </div>
                                          </div>
                                       </div> 
                                    </div>
                                 </div>
                              </div>
                           </div>
                           
                           <div class="row">
                              <div class="col-md-12">
                                <div class="col-md-12">
                                  <div class="box">
                                    <div class="box-info">
                                      <div class="box-header">
                                        <div class="col-md-8 col-md-offset-2 d-flex justify-content" >
                                          <div class="input-group">
                                                <span class="input-group-addon" title="Select Items"><i class="fa fa-barcode"></i></span>
                                                 <input type="text" class="form-control " placeholder="Item name/Barcode/Itemcode" id="searchItem">
                                              </div>
                                        </div>
                                      </div>
                                      <div class="box-body">
                                       <div class="col-md-12">
                                          <div class="row">
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <label for="" class="col-sm-2 control-label">Item Code</label>   
                                                   <div class="col-sm-4">
                                                      <input type="hidden" class="form-control" id="itmID" name="itmID" placeholder="">
                                                      <input type="text" class="form-control" id="itmCode" name="itmCode" placeholder="" readonly>
                                                   </div>
                                                   <label for="" class="col-sm-2 control-label">Item Name</label>   
                                                   <div class="col-sm-4">
                                                      <input type="text" class="form-control" id="itmName" name="itmName" placeholder="" readonly>
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <label for="" class="col-sm-2 control-label"><?= $this->lang->line('category'); ?></label>   
                                                   <div class="col-sm-4">
                                                      <input type="text" class="form-control" id="categoryName" name="categoryName" placeholder="" readonly>
                                                      <input type="hidden" class="form-control" id="catID" name="catID" placeholder="">
                                                   </div>
                                                   <label for="" class="col-sm-2 control-label">SKU</label>   
                                                   <div class="col-sm-4">
                                                      <input type="text" class="form-control" id="sku" name="sku" placeholder="" readonly>
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12" hidden>
                                                <div class="form-group">
                                                   <label for="" class="col-sm-2 control-label">Color</label>   
                                                   <div class="col-sm-4">
                                                      <input type="text" class="form-control" id="color_name" name="color_name" placeholder="" readonly>
                                                      <input type="hidden" class="form-control" id="color_id" name="color_id" placeholder="" readonly>
                                                   </div>
                                                   <label for="" class="col-sm-2 control-label">Size</label>   
                                                   <div class="col-sm-4">
                                                      <input type="text" class="form-control" id="size_name" name="size_name" placeholder="" readonly>
                                                      <input type="hidden" class="form-control" id="size_id" name="size_id" placeholder="" readonly>
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <label for="" class="col-sm-2 control-label">Item Qty</label>   
                                                   <div class="col-sm-2">
                                                      <input type="number" class="form-control" id="itm_qty" name="itm_qty" value="0" placeholder="" >
                                                   </div>
                                                   <label for="" class="col-sm-2 control-label">Cost Price</label>   
                                                   <div class="col-sm-2">
                                                      <input type="number" class="form-control" id="cost_price" name="cost_price" value="0.00" placeholder="" >
                                                   </div>
                                                   <label hidden class="col-sm-2 control-label">Ins</label>   
                                                   <div class="col-sm-2" hidden>
                                                      <input type="number" class="form-control" id="item_ins" name="item_ins" value="0.00" placeholder="" >
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <label for="" class="col-sm-2 control-label">Sale Price</label>   
                                                   <div class="col-sm-2">
                                                      <input type="number" class="form-control" id="itm_sale01" name="itm_sale01" value="0.00" placeholder="" >
                                                   </div>
                                                   <label for="" class="col-sm-2 control-label">Last Price</label>   
                                                   <div class="col-sm-2">
                                                      <input type="number" class="form-control" id="itm_sale02" name="itm_sale02" value="0.00" placeholder="" >
                                                   </div>
                                                   <label hidden class="col-sm-2 control-label">Sale Price 03</label>   
                                                   <div class="col-sm-2" hidden>
                                                      <input type="number" class="form-control" id="itm_sale03" name="itm_sale03" value="0.00" placeholder="" >
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <label for="purchase_note" class="col-sm-2 control-label"><?= $this->lang->line('note'); ?></label>    
                                                   <div class="col-sm-10">
                                                      <textarea class="form-control text-left" id='purchase_note' name="purchase_note"><?=$purchase_note;?></textarea>
                                                   <span id="purchase_note_msg" style="display:none" class="text-danger"></span>
                                                   </div>
                                                </div>
                                             </div>
                                             <div class="col-md-12">
                                                <div class="form-group">
                                                   <input type="hidden" class="form-control" id="total_grn" name="total_grn" placeholder="" >
                                                   <button type="button" class="btn btn-primary" style="float:right;" id="itm_add" name="itm_add">Add Item</button>
                                                </div>
                                             </div>
                                          </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>

                              <div class="col-md-12">
                                 <div class="table-responsive" style="width: 100%">
                                    <table class="table table-hover table-bordered" style="width:100%" id="itm_purchase_list">
                                       <thead class="custom_thead">
                                          <tr class="bg-primary" >
                                             <th rowspan='2' style="width:2%; text-align:center; ">#</th>
                                             <th rowspan='2' style="width:5%" hidden>Item ID</th>
                                             <th rowspan='2' style="width:10%">Barcode</th>
                                             <th rowspan='2' style="width:15%"><?= $this->lang->line('item_name'); ?></th>
                                             <th rowspan='2' style="width:5%" hidden>Category</th>
                                             <th rowspan='2' style="width:5%" hidden>Color</th>
                                             <th rowspan='2' style="width:5%" hidden>Size</th>
                                             <th rowspan='2' style="width:5%;"><?= $this->lang->line('quantity'); ?></th>
                                             <th rowspan='2' style="width:10%">Cost Price</th>
                                             <th rowspan='2' style="width:10%">Sale Price</th>
                                             <th rowspan='2' style="width:10%">Last Price</th>
                                             <th rowspan='2' style="width:10%" hidden>Sale Price 3</th>
                                             <th rowspan='2' style="width:5%" hidden>Ins</th>
                                             <th rowspan='2' style="width:10%">Sub Total</th>
                                             <th rowspan='2' style="width:10%"><?= $this->lang->line('action'); ?></th>
                                          </tr>
                                       </thead>
                                       <tbody id="itm_p_details">
                                                               
                                       </tbody>
                                       <tfoot>
                                          <tr>
                                                <th colspan="3" style="text-align: right;">Total Qty</th>
                                                <th id="total_qty" style="text-align: right;">0.00</th>
                                                <th colspan="3" style="text-align: right;">Grand Total</th>
                                                <th id="sumtotal" style="text-align: right;">0.00</th>
                                          </tr>
                                       </tfoot>
                                    </table>
                                 </div>
                              </div>
                              
                              
                              <div class="col-md-6" hidden>
                                <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="" class="col-sm-4 control-label">Total GRN</label>    
                                          <div class="col-sm-4">
                                             <label class="control-label total_quantity text-success" style="font-size: 15pt;">0</label>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="other_charges_input" class="col-sm-4 control-label"><?= $this->lang->line('other_charges'); ?></label>    
                                          <div class="col-sm-4">
                                             <input type="text" class="form-control text-right only_currency" id="other_charges_input" name="other_charges_input" onkeyup="final_total();" value="<?php echo  $other_charges_input; ?>">
                                          </div>
                                          <div class="col-sm-4">
                                             <select class="form-control " id="other_charges_tax_id" name="other_charges_tax_id" onchange="final_total();" style="width: 100%;">
                                                <?php
                                                   $q1="select * from db_tax where status=1";
                                                   $q1=$this->db->query($q1);
                                                    if($q1->num_rows()>0)
                                                    {
                                                     echo "<option>None</option>";
                                                     foreach($q1->result() as $res1)
                                                      {
                                                        $selected=($other_charges_tax_id==$res1->id) ? 'selected' : '';
                                                        echo "<option $selected data-tax='".$res1->tax."' value='".$res1->id."'>".$res1->tax_name."</option>";
                                                      }
                                                    }
                                                    else
                                                    {
                                                       ?>
                                                <option value="">No Records Found</option>
                                                <?php
                                                   }
                                                   ?>
                                             </select>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="discount_to_all_input" class="col-sm-4 control-label"><?= $this->lang->line('discount_on_all'); ?></label>    
                                          <div class="col-sm-4">
                                             <input type="text" class="form-control  text-right only_currency" id="discount_to_all_input" name="discount_to_all_input" onkeyup="enable_or_disable_item_discount();" value="<?php echo  $discount_input; ?>">
                                          </div>
                                          <div class="col-sm-4">
                                             <select class="form-control" onchange="final_total();" id='discount_to_all_type' name="discount_to_all_type">
                                                <option value='in_percentage'>Per%</option>
                                                <option value='in_fixed'>Fixed</option>
                                             </select>
                                          </div>
                                          <!-- Dynamicaly select Supplier name -->
                                          <script type="text/javascript">
                                             <?php if($discount_type!=''){ ?>
                                                 document.getElementById('discount_to_all_type').value='<?php echo  $discount_type; ?>';
                                             <?php }?>
                                          </script>
                                          <!-- Dynamicaly select Supplier name end-->
                                       </div>
                                    </div>
                                 </div>
                                

                                 
                              </div>
                              

                              <div class="col-md-6" hidden>
                                 <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                           
                                          <table  class="col-md-9">
                                             <tr>
                                                <th class="text-right" style="font-size: 17px;"><?= $this->lang->line('subtotal'); ?></th>
                                                <th class="text-right" style="padding-left:10%;font-size: 17px;">
                                                   <h4>
                                                    <?= $CI->currency('<b id="subtotal_amt" name="subtotal_amt">0.00</b>'); ?>
                                                   </h4>
                                                </th>
                                             </tr>
                                             <tr>
                                                <th class="text-right" style="font-size: 17px;"><?= $this->lang->line('other_charges'); ?></th>
                                                <th class="text-right" style="padding-left:10%;font-size: 17px;">
                                                   <h4>
                                                    <?= $CI->currency('<b id="other_charges_amt" name="other_charges_amt">0.00</b>'); ?>
                                                  </h4>
                                                </th>
                                             </tr>
                                             <tr>
                                                <th class="text-right" style="font-size: 17px;"><?= $this->lang->line('discount_on_all'); ?></th>
                                                <th class="text-right" style="padding-left:10%;font-size: 17px;">
                                                   <h4>
                                                    <?= $CI->currency('<b id="discount_to_all_amt" name="discount_to_all_amt">0.00</b>'); ?></h4>
                                                </th>
                                             </tr>
                                             <tr style="<?= (!is_enabled_round_off()) ? 'display: none;' : '';?>">
                                                <th class="text-right" style="font-size: 17px;"><?= $this->lang->line('round_off'); ?>
                                                  
                                                    <i class="hover-q " data-container="body" data-toggle="popover" data-placement="top" data-content="Go to Site Settings-> Site -> Disable the Round Off(Checkbox)." data-html="true" data-trigger="hover" data-original-title="" title="Do you wants to Disable Round Off ?">
                                                      <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
                                                    </i>
                                                  
                                                </th>
                                                <th class="text-right" style="padding-left:10%;font-size: 17px;">
                                                   <h4>
                                                    <?= $CI->currency('<b id="round_off_amt" name="tot_round_off_amt">0.00</b>'); ?></h4>
                                                </th>
                                             </tr>
                                             <tr>
                                                <th class="text-right" style="font-size: 17px;"><?= $this->lang->line('grand_total'); ?></th>
                                                <th class="text-right" style="padding-left:10%;font-size: 17px;">
                                                   <h4>
                                                    <?= $CI->currency('<b id="total_amt" name="total_amt">0.00</b>'); ?></h4>
                                                </th>
                                             </tr>
                                          </table>
                                       </div>
                                    </div>
                                 </div>
                              </div>

                              <div class="col-xs-12 ">
                                 <div class="col-sm-12">
                                       <div class="box-body ">
                                        <div class="col-md-12">
                                          <table class="table table-hover table-bordered" style="width:100%" id="payments_table"><h4 class="box-title text-info"><?= $this->lang->line('previous_payments_information'); ?> : </h4>
                                             <thead>
                                                <tr class="bg-gray " >
                                                   <th>#</th>
                                                   <th><?= $this->lang->line('date'); ?></th>
                                                   <th><?= $this->lang->line('payment_type'); ?></th>
                                                   <th><?= $this->lang->line('payment_note'); ?></th>
                                                   <th><?= $this->lang->line('payment'); ?></th>
                                                   <th><?= $this->lang->line('action'); ?></th>
                                                </tr>
                                             </thead>
                                             <tbody>
                                                <?php 
                                                  if(isset($purchase_id)){
                                                    $q3 = $this->db->query("select * from db_purchasepayments where purchase_id=$purchase_id");
                                                    if($q3->num_rows()>0){
                                                      $i=1;
                                                      $total_paid = 0;
                                                      foreach ($q3->result() as $res3) {
                                                        echo "<tr class='text-center text-bold' id='payment_row_".$res3->id."'>";
                                                        echo "<td>".$i."</td>";
                                                        echo "<td>".show_date($res3->payment_date)."</td>";
                                                        echo "<td>".$res3->payment_type."</td>";
                                                        echo "<td>".$res3->payment_note."</td>";
                                                        echo "<td class='text-right' id='paid_amt_$i'>".
                                                         $CI->currency($res3->payment)."</td>";
                                                        echo '<td><i class="fa fa-trash text-red pointer" onclick="delete_payment('.$res3->id.')"> Delete</i></td>';
                                                        echo "</tr>";
                                                        $total_paid +=$res3->payment;
                                                        $i++;
                                                      }
                                                      echo "<tr class='text-right text-bold'><td colspan='4' >Total</td><td data-rowcount='$i' id='paid_amt_tot'>".
                                                      $CI->currency(number_format($total_paid,2,'.',''))."</td><td></td></tr>";
                                                    }
                                                    else{
                                                      echo "<tr><td colspan='6' class='text-center text-bold'>No Previous Payments Found!!</td></tr>";
                                                    }

                                                  }
                                                  else{
                                                    echo "<tr><td colspan='6' class='text-center text-bold'>Payments Pending!!</td></tr>";
                                                  }
                                                ?>
                                             </tbody>
                                          </table>
                                        </div>
                                       </div>
                                       <!-- /.box-body -->
                                    </div>
                                 <!-- /.box -->
                              </div>

                              <div class="col-xs-12 ">
                                 <div class="col-sm-12">
                                       <div class="box-body ">

                                          <div class="col-md-12 payments_div payments_div_">
                                            <h4 class="box-title text-info"><?= $this->lang->line('make_payment'); ?> : </h4>
                                          <div class="box box-solid bg-gray">
                                            <div class="box-body">
                                              <div class="row">
                                         
                                                <div class="col-md-6">
                                                  <div class="">
                                                  <label for="amount"><?= $this->lang->line('amount'); ?></label>
                                                    <input type="text" class="form-control text-right paid_amt only_currency" id="amount" name="amount" placeholder="">
                                                      <span id="amount_msg" style="display:none" class="text-danger"></span>
                                                </div>
                                               </div>
                                                <div class="col-md-6">
                                                  <div class="">
                                                    <label for="payment_type"><?= $this->lang->line('payment_type'); ?></label>
                                                    <select class="form-control select2" id='payment_type' name="payment_type" data-ID="1" onchange="displayChqArea(this)">
                                                      <?php
                                                        $q1=$this->db->query("select * from db_paymenttypes where status=1");
                                                         if($q1->num_rows()>0){
                                                            echo "<option value=''>-Select-</option>";
                                                             foreach($q1->result() as $res1){
                                                             echo "<option value='".$res1->payment_type."'>".$res1->payment_type ."</option>";
                                                           }
                                                         }
                                                         else{
                                                            echo "<option>None</option>";
                                                         }
                                                        ?>
                                                    </select>
                                                    <span id="payment_type_msg" style="display:none" class="text-danger"></span>
                                                  </div>
                                                </div>
                                            <div class="clearfix"></div>
                                        </div>
                                        <div class="row" id="chqArea_1" hidden>
                                            <div class="col-md-6">
                                                <div class="">
                                                <label for="">Cheque no.</label>
                                                <input type="text" class="form-control" id="chequeNo" name="chequeNo" onblur="checkAvailabilityChk();" placeholder="Cheque no.">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="">
                                                <label for="">Cheque Received Date</label>
                                                <input type="date" class="form-control" id="chequeDate" name="chequeDate" value="<?php $date = new DateTime("now", new DateTimeZone('Asia/Colombo') ); echo $date->format('Y-m-d');?>" placeholder="Cheque date">
                                                </div>
                                            </div>
                                             <div class="col-md-12"><span id="error_chk" class="text-danger"></span></div>
                                             <div class="col-md-6">
                                                <div class="">
                                                <label for="">Cheque clearance date</label>
                                                <input type="date" class="form-control" id="chequeClearance" name="chequeClearance" placeholder="Cheque clearance date">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="">
                                                <label for="">Bank</label>
                                                <input type="text" class="form-control" id="chequeBank" name="chequeBank" placeholder="Cheque bank">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                               <div class="col-md-12">
                                                  <div class="">
                                                    <label for="payment_note"><?= $this->lang->line('payment_note'); ?></label>
                                                    <textarea type="text" class="form-control" id="payment_note" name="payment_note" placeholder="" ></textarea>
                                                    <span id="payment_note_msg" style="display:none" class="text-danger"></span>
                                                  </div>
                                               </div>
                                                
                                            <div class="clearfix"></div>
                                        </div>   
                                        </div>
                                        </div>
                                        </div><!-- col-md-12 -->
                                       </div>
                                       <!-- /.box-body -->
                                    </div>
                                 <!-- /.box -->
                              </div>

                              

                           </div>
                           
                           <!-- /.box-body -->
                           <div class="box-footer col-sm-12">
                              <center>
                                <?php
                                if(isset($purchase_id)){
                                  $btn_id='update';
                                  $btn_name="Update";
                                  echo '<input type="hidden" name="purchase_id" id="purchase_id" value="'.$purchase_id.'"/>';
                                }
                                else{
                                  $btn_id='save';
                                  $btn_name="Save";
                                }

                                ?>
                                 <div class="col-md-3 col-md-offset-3">
                                    <button type="button" id="<?php echo $btn_id;?>" class="btn bg-maroon btn-block btn-flat btn-lg payments_modal" title="Save Data"><?php echo $btn_name;?></button>
                                 </div>
                                 <div class="col-sm-3"><a href="<?= base_url()?>dashboard">
                                    <button type="button" class="btn bg-gray btn-block btn-flat btn-lg" title="Go Dashboard">Close</button>
                                  </a>
                                </div>
                              </center>
                           </div>
                           

                           <?= form_close(); ?>
                           <!-- OK END -->
                     </div>
                  </div>
                  <!-- /.box-footer -->
                 
               </div>
               <!-- /.box -->
             </section>
            <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  
 <?php include"footer.php"; ?>
<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- GENERAL CODE -->
<?php include"comman/code_js_form.php"; ?>

 <script src="<?php echo $theme_link; ?>js/modals.js"></script>
  <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
  <div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<script src="<?php echo $theme_link; ?>js/purchase.js"></script>

<script type="text/javascript">
$("#supplier_id").change(function(){
  getCusHistoty();
});

</script>
<script>
    function getCusHistoty(){
      var sup_id = $("#supplier_id").val();

        $.ajax({
          url:"<?php echo site_url('purchase/cusHistory_info_get')?>",
          type: 'POST',
          data: {sup_id:sup_id},
          dataType: 'json',
          success: function (data) {

              $.each(data.data_count_info, function(){
                var dataCount =parseInt(this['d_count']);
                console.log(dataCount);
                if(dataCount>0) { 

                  var indexNo = 1;   
                  var transData = '';        
                  $.each(data.cus_info, function(){
                    var price_per_unit = parseFloat(this['cost_price']);
                    var sales_qty = parseFloat(this['purchase_qty']);
                    var tot_amt = price_per_unit*sales_qty;

                    //table.row.add([indexNo,this['sales_code'],this['sales_date'],this['item_name'], this['price_per_unit'], this['sales_qty'], tot_amt.toFixed(2)]);
                          transData += '<tr>';
                          transData += '<td style="border: 1px solid; text-align: center;">'+indexNo+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+this['purchase_code']+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+this['purchase_date']+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+this['item_name']+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+this['cost_price']+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+this['purchase_qty']+'</td>';
                          transData += '<td style="border: 1px solid; padding-left: 10px;">'+tot_amt.toFixed(2)+'</td>';
                          transData += '</tr>';                      

                    indexNo++;
                  });
                  $("#example3 tbody").empty().append(transData); //hisData
                  var icon = document.getElementById("viewHistoryIcon");
                  if (icon.classList.contains("fa-eye-slash")) {
                      icon.classList.remove("fa-eye-slash");
                      icon.classList.add("fa-eye");
                  } else {
                      icon.classList.remove("fa-eye");
                      icon.classList.add("fa-eye-slash");
                  }
                  // var viewHistoryButton = document.getElementById('viewHistory');
                  // viewHistoryButton.style.display = 'block';
                }else {
                    //$('#example3').DataTable().destroy();
                  //toastr["warning"]("Something Wrong! , Data Not Found. ");
                }
              });
          },
          error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
          }
        });
    }
</script>
<script>
  function filterHisData() {
    var input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("his_itemname");
    filter = input.value.toUpperCase();
    table = document.getElementById("hisData");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
      td = tr[i].getElementsByTagName("td")[3];
      if (td) {
        txtValue = td.textContent || td.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          tr[i].style.display = "";
        } else {
          tr[i].style.display = "none";
        }
      }       
    }
  }
</script>

<script>
  function displayChqArea(ctl){
   
    var p_type = $("#payment_type").val();
    //alert(p_type);
    if(p_type=="Cheque"){
      $("#chqArea_1").attr("hidden",false);
    }else{
      $("#chequeNo").val("");
      $("#chequeDate").val("");
      $("#chequeClearance").val("");
      $("#chequeBank").val("");

      $("#chqArea_1").attr("hidden",true);
    }
  }
</script>

<script>
  function checkAvailabilityChk() {
    var chequeNo    = $('#chequeNo').val();
      jQuery.ajax({
        url:"<?php echo site_url('sales/check_chkNo')?>",
        data:{chequeNo:chequeNo},
        type: "POST",
        success:function(data){
          var c_count = parseInt(data);
          if(c_count>0){
          $('#chequeNo').val("");
          $("#error_chk").html("This cheque no. already exists.");
          }else{
          $("#error_chk").html("");
          }
        },
        error:function (){}
    });
  }
</script>

<script>
         function addNewColor(ctl) {
            swal("Add New Color", {
               buttons: {
                  cancel: true,
                  confirm: true,
               },
               showConfirmButton: false,
               allowOutsideClick: false,
               allowEscapeKey: false,
               content: "input",
               })
               .then((value) => {
                  var color = value;
                  if(color==null){
                     //toastr["error"]("Sorry! Please Enter Color !");
                  }else{
                     $.ajax({
                        url: '<?php echo $base_url; ?>colors/itm_new_color',
                        type: 'POST',
                        data: {color:color},
                        dataType: 'JSON',
                        success: function(data) {
                           //console.log(data);
                           if (data=="success") {
                              color_fill();
                              //swal("Successfully!", "Color Added !", "success");
                              toastr["success"]("New Color Added!!");
                           }else if (data=="exist"){
                              //swal("Sorry","This Color Already Exist !!","error");
                              toastr["error"]("Sorry! This Color Already Exist.Try again!");
                           }else if (data=="failed"){
                              //swal("Sorry","Error occured !!","error");
                              toastr["error"]("Sorry! Something Wrong.Try again!");
                           }
                        }
                     });
                  }
               });
            }
      </script>
      <script>
         function newSizeAdd(ctl) {
            swal("Add New Size", {
               buttons: {
                  cancel: true,
                  confirm: true,
               },
               showConfirmButton: false,
               allowOutsideClick: false,
               allowEscapeKey: false,
               content: "input",
               })
               .then((value) => {
                  var size = value;
                  if(size==null){
                     toastr["error"]("Sorry! Please Enter Size !");
                  }else{
                     $.ajax({
                        url: '<?php echo $base_url; ?>size/itm_new_size',
                        type: 'POST',
                        data: {size:size},
                        dataType: 'JSON',
                        success: function(data) {
                           //console.log(data);
                           if (data=="success") {
                              size_fill();
                              swal("Successfully!", "Size Added !", "success");
                              toastr["success"]("New Size Added!!");
                           }else if (data=="exist"){
                              //swal("Sorry","This Size Already Exist !!","error");
                              toastr["error"]("Sorry! This Size Already Exist.Try again!");
                           }else if (data=="failed"){
                              //swal("Sorry","Error occured !!","error");
                              toastr["error"]("Sorry! Something Wrong.Try again!");
                           }
                        }
                     });
                  }
               });
            }
      </script>
      <script>
         function color_fill(){
            $.ajax({
               url: '<?php echo $base_url; ?>colors/s_all_color',
                  type: 'GET',
                  dataType: 'json',
                  success: function(data) {
                     console.log(data);
                     $('#color_id').empty();
                     $('#color_id').append('<option value="">-Select-</option>');
                     $.each(data.colorInfo, function(){
                        console.log(this['id']);
                        $('#color_id').append($("<option></option>").val(this['id']).html(this['color']));
                     });
                  }
            });
         }
      </script>
      <script>
         function size_fill(){
            $.ajax({
               url: '<?php echo $base_url; ?>size/s_all_size',
                  type: 'GET',
                  dataType: 'json',
                  success: function(data) {
                     console.log(data);
                     $('#size_id').empty();
                     $('#size_id').append('<option value="">-Select-</option>');
                     $.each(data.sizeInfo, function(){
                        console.log(this['id']);
                        $('#size_id').append($("<option></option>").val(this['id']).html(this['size']));
                     });
                  }
            });
         }
      </script>
       <script>
         // $("#searchItem").bind("paste", function(e){
         //    $("#searchItem").autocomplete('search');
         // } );
         // $("#searchItem").autocomplete({
         //    source: function(data, cb){
         //       $.ajax({
         //          autoFocus:true,
         //             url: $("#base_url").val()+'items/get_json_items_details',
         //             method: 'GET',
         //             dataType: 'json',
         //             /*showHintOnFocus: true,
         //       autoSelect: true, 
               
         //       selectInitial :true,*/
               
         //             data: {
         //                name: data.term
         //             },
         //             success: function(res){
         //             //console.log(res);
         //                var result;
         //                result = [
         //                   {
         //                         //label: 'No Records Found '+data.term,
         //                         label: 'No Records Found ',
         //                         value: ''
         //                   }
         //                ];

         //                if (res.length) {
         //                   result = $.map(res, function(el){
         //                      //console.log(el.label+"   "+el.id+"   "+el.value+"   "+el.category_name+"   "+el.color+"   "+el.size);
         //                      label: el.item_code +'--'+ el.label,
         //                      $('#itmID').val(el.id);
         //                      $('#itmName').val(el.item_name);
         //                      $('#categoryName').val(el.category_name);
         //                      $('#sku').val(el.sku);
         //                      $('#itmCode').val(el.item_code);
         //                      $('#catID').val(el.category_id);
         //                      $('#color_id').val(el.color_id);
         //                      $('#size_id').val(el.size_id);
         //                      $('#color_name').val(el.color);
         //                      $('#size_name').val(el.size);
         //                      $("#searchItem").val('');
         //                   });
         //                }

         //                cb(result);
         //             }
         //       });
         //    },

         //       response:function(e,ui){
         //          if(ui.content.length==1){
         //             $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
         //             $(this).autocomplete("close");
         //          }
         //          //console.log(ui.content[0].id);
         //       },

         //       //loader start
         //       search: function (e, ui) {
         //       },
         //       select: function (e, ui) { 
                  
         //             //$("#mobile").val(ui.item.mobile)
         //             //$("#item_search").val(ui.item.value);
         //             //$("#customer_dob").val(ui.item.customer_dob)
         //             //$("#address").val(ui.item.address)
         //             //alert("id="+ui.item.id);
         //             if(typeof ui.content!='undefined'){
         //             console.log("Autoselected first");
         //             if(isNaN(ui.content[0].id)){
         //                return;
         //             }
         //             //var stock=ui.content[0].stock;
         //             var item_id=ui.content[0].id;
         //             }
         //             else{
         //             console.log("manual Selected");
         //             //var stock=ui.item.stock;
         //             var item_id=ui.item.id;
         //             }

         //             return_row_with_data(item_id);
         //             $("#searchItem").val('');
         //       },   
         //       //loader end
         // });

         $("#searchItem").bind("paste", function(e){
            $("#searchItem").autocomplete('search');
         } );

         $("#searchItem").autocomplete({
            maxShowItems: 5,
            source: function(data, cb){
               $.ajax({
                  autoFocus:true,
                     url: $("#base_url").val()+'items/get_json_items_details',
                     method: 'GET',
                     dataType: 'json',
                     /*showHintOnFocus: true,
               autoSelect: true, 
               
               selectInitial :true,*/
               
                     data: {
                        name: data.term
                     },
                     success: function(res){
                     //console.log(res);
                        var result;
                        result = [
                           {
                                 //label: 'No Records Found '+data.term,
                                 label: 'No Records Found ',
                                 value: ''
                           }
                        ];

                        if (res.length) {
                           result = $.map(res, function(el){
                                 return {
                                    label: el.item_code +' -- '+el.sku +' -- '+ el.label +' -- '+ el.color +' -- '+ el.size,
                                    value: '',
                                    id: el.id,
                                    item_name: el.value,
                                    // mobile: el.mobile,
                                    //customer_dob: el.customer_dob,
                                    //address: el.address,
                                 };
                           });
                        }

                        cb(result);
                     }
               });
            },

               response:function(e,ui){
                  if(ui.content.length==1){
                     $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
                     $(this).autocomplete("close");
                  }
                  //console.log(ui.content[0].id);
               },

               //loader start
               search: function (e, ui) {
               },
               select: function (e, ui) { 
                  
                     //$("#mobile").val(ui.item.mobile)
                     //$("#item_search").val(ui.item.value);
                     //$("#customer_dob").val(ui.item.customer_dob)
                     //$("#address").val(ui.item.address)
                     //alert("id="+ui.item.id);
                     if(typeof ui.content!='undefined'){
                     console.log("Autoselected first");
                     if(isNaN(ui.content[0].id)){
                        return;
                     }
                     //var stock=ui.content[0].stock;
                     var item_id=ui.content[0].id;
                     }
                     else{
                     console.log("manual Selected");
                     //var stock=ui.item.stock;
                     var item_id=ui.item.id;
                     }

                     return_row_data(item_id);
                     $("#item_search").val('');
               },   
               //loader end
         });

         function return_row_data(item_id){
         $("#item_search").addClass('ui-autocomplete-loader-center');
            var base_url=$("#base_url").val().trim();
            //var rowcount=$("#hidden_rowcount").val();
            // $.post(base_url+"purchase/return_row_data/"+item_id,{},function(result){
            //    //alert(result);
            //    // $('#purchase_table tbody').append(result);
            //    //    $("#hidden_rowcount").val(parseFloat(rowcount)+1);
            //    // success.currentTime = 0;
            //    // success.play();
            //    // enable_or_disable_item_discount();
            //    
            // });

            $('#itmID').val("");
            $('#itmName').val("");
            $('#categoryName').val("");
            $('#sku').val("");
            $('#itmCode').val("");
            $('#catID').val("");
            $('#color_id').val("");
            $('#size_id').val("");
            $('#color_name').val("");
            $('#size_name').val("");
            // $('#cost_price').val("");
            //$('#item_ins').val("");
            // $('#itm_sale01').val("");
            // $('#itm_sale02').val("");
            // $('#itm_sale03').val("");

            $.ajax({
               type : "POST",
               url: base_url+'purchase/return_row_data',
               data : {item_id:item_id},
               dataType: 'JSON',
               success: function(data){
                  //console.log(data);
                  $.each(data, function(){
                     $('#itmID').val(this['id']);
                     $('#itmName').val(this['item_name']);
                     $('#categoryName').val(this['category_name']);
                     $('#sku').val(this['sku']);
                     $('#itmCode').val(this['item_code']);
                     $('#catID').val(this['category_id']);
                     $('#color_id').val(this['color_id']);
                     $('#size_id').val(this['size_id']);
                     $('#color_name').val(this['color']);
                     $('#size_name').val(this['size']);
                     $("#item_search").removeClass('ui-autocomplete-loader-center');
                     $('#itm_qty').focus();
                  });

                  $.ajax({
                     type : "POST",
                     url: base_url+'purchase/return_stock_data',
                     data : {item_id:item_id},
                     dataType: 'JSON',
                     success: function(data){
                        //console.log(data.price_Info.cost_price);
                        var count_Info = data.count_Info;
                        if(count_Info>0){
                           //$.each(data.price_Info, function(){
                              $('#cost_price').val(data.price_Info.cost_price);
                              $('#item_ins').val(data.price_Info.ins);
                              $('#itm_sale01').val(data.price_Info.unit_sales_price_01);
                              $('#itm_sale02').val(data.price_Info.unit_sales_price_02);
                              $('#itm_sale03').val(data.price_Info.unit_sales_price_03);
                           //});
                        }
                        
                     }
                  });
               }
            });
         }
      </script>
      
      <script>
         $("#itm_qty").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
         $("#cost_price").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
         $("#item_ins").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
         $("#itm_sale01").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
         $("#itm_sale02").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
         $("#itm_sale03").blur(function() {
            this.value = parseFloat(this.value).toFixed(2);
         });
      </script>
      <script>
         $('#item_ins').on('change',function(){
            var item_ins = parseFloat($('#item_ins').val());
            var cost_price = parseFloat($('#cost_price').val());
            var f_price = parseFloat(item_ins+cost_price);
            $('#cost_price').val(f_price.toFixed(2));
         });
      </script>
      
      <script>
         $('#itm_add').on('click', function() {
            var s_itmID = $('#itmID').val();
            var s_itmCode = $('#itmCode').val();
            var s_itmName = $('#itmName').val();
            var s_categoryName = $('#catID').val();
            var s_sku = $('#sku').val();
            var s_color_id = $('#color_id').val();
            var s_size_id = $('#size_id').val();
            var s_itm_qty = $('#itm_qty').val();
            var s_cost_price = $('#cost_price').val();
            var s_item_ins = $('#item_ins').val();
            var s_itm_sale01 = $('#itm_sale01').val();
            var s_itm_sale02 = $('#itm_sale02').val();
            var s_itm_sale03 = $('#itm_sale03').val();

            var qty  =parseFloat($('#itm_qty').val());
            var cal_price =parseFloat($('#cost_price').val());
            var sub_price = parseFloat(qty*cal_price);
            var f_sub_price = sub_price.toFixed(2);
            var count = parseInt($('#itm_p_details').children().length);
            var indexId =(count+1);

            if ((s_itmID.length=="")||(s_cost_price.length=="")){
               toastr["error"]("Sorry! Please enter item details!");
            }else{
               //console.log(packageDate+"   "+packageEvent);
               $('#itm_add').prop("disabled",true);
               $("#itm_purchase_list tbody").append(
                     "<tr>"+
                        "<td>"+indexId+"</td>"+
                        "<td hidden>"+s_itmID+"</td>"+
                        "<td>"+s_sku+"</td>"+
                        "<td>"+s_itmName+"</td>"+
                        "<td hidden>"+s_categoryName+"</td>"+
                        "<td hidden>"+s_color_id+"</td>"+
                        "<td hidden>"+s_size_id+"</td>"+
                        "<td style='text-align:right;'>"+s_itm_qty+"</td>"+
                        "<td style='text-align:right;'>"+s_cost_price+"</td>"+
                        "<td style='text-align:right;'>"+s_itm_sale01+"</td>"+
                        "<td style='text-align:right;'>"+s_itm_sale02+"</td>"+
                        "<td style='text-align:right;' hidden>"+s_itm_sale03+"</td>"+
                        "<td hidden>"+s_item_ins+"</td>"+
                        "<td style='text-align:right;'>"+f_sub_price+"</td>"+
                        "<td style='text-align:center;'> <button type='button' name='remove' data-id='"+indexId+"' class='btn btn-danger record_delete' id='btn_remove' onClick='rowDelete(this);'>X </button> </td>"+
                     "</tr>"
               );

               $('#sumtotal').empty();
               $('.total_quantity').empty();
               $('#subtotal_amt').empty();
               $('#other_charges_amt').empty();
               $('#discount_to_all_amt').empty();
               $('#round_off_amt').empty();
               $('#total_amt').empty();
               $('#total_qty').empty();

               var empty_val = 0;
               var qty_val = 0;
               $('#total_grn').val(0);
               $('#itm_purchase_list tbody tr').each(function(row,tr){
                 var sumTValue=parseFloat($('#total_grn').val());
                 var new_total = parseFloat($(tr).find('td:eq(13)').text());
                 var totQTY  = parseFloat($(tr).find('td:eq(7)').text());
                 var totalValue = parseFloat(sumTValue+new_total);
                 $('#total_grn').val(totalValue);
                 //alert(new_total);
                 qty_val += totQTY;
               });
               var finalTValue=parseFloat($('#total_grn').val());
               $('.total_quantity').append(finalTValue.toFixed(2));
               $('#sumtotal').append(finalTValue.toFixed(2));
               $('#other_charges_input').val(empty_val.toFixed(2));
               $('#discount_to_all_input').val(empty_val.toFixed(2));               
               $('#subtotal_amt').append(finalTValue.toFixed(2));
               $('#other_charges_amt').append(empty_val.toFixed(2));
               $('#discount_to_all_amt').append(empty_val.toFixed(2));
               $('#round_off_amt').append(empty_val.toFixed(2));
               $('#total_amt').append(finalTValue.toFixed(2));
               $('#total_qty').append(qty_val.toFixed(2));

               $('#itmID').val("");
               $('#itmCode').val("");
               $('#itmName').val("");
               $('#catID').val("");
               $('#categoryName').val("");
               $('#sku').val("");
               $('#color_id').val('');
               $('#size_id').val('');
               $('#color_name').val('');
               $('#size_name').val('');
               //$('#itm_qty').val("");
               // $('#cost_price').val("");
               // $('#item_ins').val("");
               // $('#itm_sale01').val("");
               // $('#itm_sale02').val("");
               // $('#itm_sale03').val("");
               //$("#packageEvent").val("");
               $('#itm_add').prop("disabled",false);
            }
         });
      </script>
      <script>
      function rowDelete(ctl) {
         swal({
         title: 'Are you sure?',
         text: 'This Record is delete!!',
         icon: 'warning',
         buttons: true,
         dangerMode: true,
      })
         .then((willDelete) => {
            if (willDelete) {
            $(ctl).parents("tr").remove();
            $('#sumtotal').empty();
            $('.total_quantity').empty();
            $('#subtotal_amt').empty();
            $('#other_charges_amt').empty();
            $('#discount_to_all_amt').empty();
            $('#round_off_amt').empty();
            $('#total_amt').empty();
            var empty_val = 0;
            $('#total_qty').empty();
            var qty_val = 0;

            $('#total_grn').val(0);
            $('#itm_purchase_list tbody tr').each(function(row,tr){
              var sumTValue=parseFloat($('#total_grn').val());
              var new_total = parseFloat($(tr).find('td:eq(13)').text());
              var totalValue = parseFloat(sumTValue+new_total);
              $('#total_grn').val(totalValue);
              //alert(new_total);
              var totQTY  = parseFloat($(tr).find('td:eq(7)').text());
              qty_val += totQTY;
            });
            $('#total_qty').append(qty_val.toFixed(2));
            var finalTValue=parseFloat($('#total_grn').val());
            $('.total_quantity').append(finalTValue.toFixed(2));
            $('#sumtotal').append(finalTValue.toFixed(2));
            $('#other_charges_input').val(empty_val.toFixed(2));
            $('#discount_to_all_input').val(empty_val.toFixed(2));               
            $('#subtotal_amt').append(finalTValue.toFixed(2));
            $('#other_charges_amt').append(empty_val.toFixed(2));
            $('#discount_to_all_amt').append(empty_val.toFixed(2));
            $('#round_off_amt').append(empty_val.toFixed(2));
            $('#total_amt').append(finalTValue.toFixed(2));
            swal('Record has been deleted!', {
               icon: 'success',
            });
            } else {
            swal('Your Data Record is safe!');
            }
         });
      };
      </script>
<script>
         $(".close_btn").click(function(){
           //if(confirm('Are you sure you want to navigate away from this page?')){
               window.location='<?php echo $base_url; ?>dashboard';
             //}
         });
         //Initialize Select2 Elements
             $(".select2").select2();
         //Date picker
             $('.datepicker').datepicker({
               autoclose: true,
            format: 'dd-mm-yyyy',
              todayHighlight: true
             });
          
       
         
         /* ---------- CALCULATE TAX -------------*/
         function calculate_tax(i){ //i=Row
           set_tax_value(i);

           //Find the Tax type and Tax amount
           var tax_type = $("#tr_tax_type_"+i).val();
           var tax_amount = $("#td_data_"+i+"_5").val();
           

           var qty=$("#td_data_"+i+"_3").val().trim();
           var purchase_price=parseFloat($("#td_data_"+i+"_4").val().trim());
           var discount=$("#td_data_"+i+"_8").val().trim();
           var tax=$("#tr_tax_value_"+i).val().trim();

           //Discount on All
           var discount_input = (isNaN(parseFloat($("#discount_to_all_input").val()))) ? 0 : parseFloat($("#discount_to_all_input").val());
           if(discount_input>0){
              discount=0;
           }

           //var tax=$('option:selected', "#td_data_"+i+"_15").attr('data-tax');
           //var tax=$("#tr_tax_value_"+i).val().trim();

           //tax        =(isNaN(parseFloat(tax)))         ? 0 : parseFloat(tax);
           discount   =(isNaN(parseFloat(discount)))    ? 0 : parseFloat(discount);

           var amt=parseFloat(qty) * purchase_price;//Taxable
           //var tax_amt=parseFloat((amt * tax)/100);
           var discount_amt=((amt) * discount)/100;

           var total_amt=amt-discount_amt;
           total_amt = (tax_type=='Inclusive') ? total_amt : parseFloat(total_amt) + parseFloat(tax_amount);
           console.log("total_amt=="+total_amt);
           //Set Unit cost
           
           //CAlculate Item wise price and tax and discount
           var tax_each = (tax_type=='Inclusive') ? 0 : calculate_exclusive(purchase_price,tax);
           
           var per_unit_total    = parseFloat(purchase_price)+parseFloat(tax_each);

           $("#td_data_"+i+"_10").val('').val(per_unit_total.toFixed(2));

          // $("#td_data_"+i+"_5").val('').val(tax_amount.toFixed(2));
           $("#td_data_"+i+"_9").val('').val(total_amt.toFixed(2));
           //alert("calculate_tax() end");
           final_total();
           
         }
        
         /* ---------- CALCULATE GST END -------------*/

        
         /* ---------- Final Description of amount ------------*/
         function final_total(){
           

           var rowcount=$("#hidden_rowcount").val();
           var subtotal=parseFloat(0);
           
           var other_charges_per_amt=parseFloat(0);
           var other_charges_total_amt=0;
           var taxable=0;
          if($("#other_charges_input").val()!=null && $("#other_charges_input").val()!=''){
             
              other_charges_tax_id =$('option:selected', '#other_charges_tax_id').attr('data-tax');
             other_charges_input=$("#other_charges_input").val();
             if(other_charges_tax_id>0){

               other_charges_per_amt=(other_charges_tax_id * other_charges_input)/100;
             }
             
             taxable=parseFloat(other_charges_per_amt)+parseFloat(other_charges_input);//Other charges input
             other_charges_total_amt=parseFloat(other_charges_per_amt)+parseFloat(other_charges_input);
           }
           else{
             //$("#other_charges_amt").html('0.00');
           }
           
         
           var tax_amt=0;
           var actual_taxable=0;
           var total_quantity=0;
         
           for(i=1;i<=rowcount;i++){
         
             if(document.getElementById("td_data_"+i+"_3")){
               //supplier_id must exist
               if($("#td_data_"+i+"_3").val()!=null && $("#td_data_"+i+"_3").val()!=''){
                    actual_taxable=actual_taxable+ + +(parseFloat($("#td_data_"+i+"_13").val()).toFixed(2) * parseFloat($("#td_data_"+i+"_3").val()));
                    subtotal=subtotal+ + +parseFloat($("#td_data_"+i+"_9").val()).toFixed(2);
                    if($("#td_data_"+i+"_7").val()>=0){
                      tax_amt=tax_amt+ + +$("#td_data_"+i+"_7").val();
                    }   
                    total_quantity +=parseFloat($("#td_data_"+i+"_3").val().trim());
                }
                   
             }//if end
           }//for end
           
          
          //Show total Purchase Quantitys
           $(".total_quantity").html(total_quantity);

           //Apply Output on screen
           //subtotal
           if((subtotal!=null || subtotal!='') && (subtotal!=0)){
             
             //subtotal
             $("#subtotal_amt").html(subtotal.toFixed(2));
             
             //other charges total amount
             $("#other_charges_amt").html(parseFloat(other_charges_total_amt).toFixed(2));
             
             //other charges total amount
            

             taxable=taxable+subtotal;
             
             //discount_to_all_amt
            // if($("#discount_to_all_input").val()!=null && $("#discount_to_all_input").val()!=''){
                 var discount_input=parseFloat($("#discount_to_all_input").val());
                 discount_input = isNaN(discount_input) ? 0 : discount_input;
                 var discount=0;
                 if(discount_input>0){
                     var discount_type=$("#discount_to_all_type").val();
                     if(discount_type=='in_fixed'){
                       taxable-=discount_input;
                       discount=discount_input;
                       //Minus
                     }
                     else if(discount_type=='in_percentage'){
                         discount=(taxable*discount_input)/100;
                        taxable-=discount;
             
                     }
                 }
                 else{
                    //discount += $("#")
                 }
                   discount=parseFloat(discount).toFixed(2);
                   
                    $("#discount_to_all_amt").html(discount);  
                    $("#hidden_discount_to_all_amt").val(discount);  
             //}
             //subtotal_round=Math.round(taxable);
             subtotal_round=round_off(taxable);//round_off() method custom defined
             subtotal_diff=subtotal_round-taxable;
         
             $("#round_off_amt").html(parseFloat(subtotal_diff).toFixed(2)); 
             $("#total_amt").html(parseFloat(subtotal_round).toFixed(2)); 
             $("#hidden_total_amt").val(parseFloat(subtotal_round).toFixed(2)); 
           }
           else{
             $("#subtotal_amt").html('0.00'); 
             
             $("#tax_amt").html('0.00'); 
           }
           
          // adjust_payments();
          //alert("final_total() end");
         }
         /* ---------- Final Description of amount end ------------*/
          
         function removerow(id){//id=Rowid
           
         $("#row_"+id).remove();
         final_total();
         failed.currentTime = 0;
        failed.play();
         }
               
     

    function enable_or_disable_item_discount(){
      var discount_input=parseFloat($("#discount_to_all_input").val());
      discount_input = isNaN(discount_input) ? 0 : discount_input;
      if(discount_input>0){
        $(".item_discount").attr({
          'readonly': true,
          'style': 'border-color:red;cursor:no-drop',
        });
      }
      else{
        $(".item_discount").attr({
          'readonly': false,
          'style': '',
        });
      }

      var rowcount=$("#hidden_rowcount").val();
      for(k=1;k<=rowcount;k++){
       if(document.getElementById("tr_item_id_"+k)){
         console.log("Hello="+k);
         calculate_tax(k);
       }//if end
     }//for end

      //final_total();
    }


    //Purchase Items Modal Operations Start
    function show_purchase_item_modal(row_id){
      $('#purchase_item').modal('toggle');
      $("#popup_tax_id").select2();

      //Find the item details
      var item_name = $("#td_data_"+row_id+"_1").html();
      var tax_type = $("#tr_tax_type_"+row_id).val();
      var tax_id = $("#tr_tax_id_"+row_id).val();

      //Set to Popup
      $("#popup_item_name").html(item_name);
      $("#popup_tax_type").val(tax_type).select2();
      $("#popup_tax_id").val(tax_id).select2();
      $("#popup_row_id").val(row_id);
    }

    function set_info(){
      var row_id = $("#popup_row_id").val();
      var tax_type = $("#popup_tax_type").val();
      var tax_id = $("#popup_tax_id").val();
      var tax_name = ($('option:selected', "#popup_tax_id").attr('data-tax-value'));
      var tax = parseFloat($('option:selected', "#popup_tax_id").attr('data-tax'));

      //Set it into row 
      $("#tr_tax_type_"+row_id).val(tax_type);
      $("#tr_tax_id_"+row_id).val(tax_id);
      $("#tr_tax_value_"+row_id).val(tax);//%
      $("#td_data_"+row_id+"_15").html(tax_name);
      
      calculate_tax(row_id);
      $('#purchase_item').modal('toggle');
    }
    function set_tax_value(row_id){
      //get the purchase price of the item
      var tax_type = $("#tr_tax_type_"+row_id).val();
      var tax = $("#tr_tax_value_"+row_id).val(); //%
      var qty=$("#td_data_"+row_id+"_3").val().trim();
          qty = (isNaN(qty)) ? 0 :qty;
      var purchase_price = parseFloat($("#td_data_"+row_id+"_4").val());
          purchase_price = (isNaN(purchase_price)) ? 0 :purchase_price;
          purchase_price = purchase_price * qty;

      var tax_amount = (tax_type=='Inclusive') ? calculate_inclusive(purchase_price,tax) : calculate_exclusive(purchase_price,tax);
      console.log("tax_amount="+tax_amount);
      $("#td_data_"+row_id+"_5").val(tax_amount);
    }
    //Purchase Items Modal Operations End
</script>
      <!-- UPDATE OPERATIONS -->
      <script type="text/javascript">
         <?php if(isset($purchase_id)){ ?> 
             $(document).ready(function(){
                var base_url='<?= base_url();?>';
                var purchase_id='<?= $purchase_id;?>';
                $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
                $.post(base_url+"purchase/return_purchase_list/"+purchase_id,{},function(result){
                  //alert(result);
                  $('#purchase_table tbody').append(result);
                  $("#hidden_rowcount").val(parseFloat(<?=$items_count;?>)+1);
                  success.currentTime = 0;
                  success.play();
                  enable_or_disable_item_discount();
                  $(".overlay").remove();
              }); 
             });
         <?php }?>
      </script>
      <!-- UPDATE OPERATIONS end-->

      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
</body>
</html>
