<?php
//index.php


function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

function get_items_as_array($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $output = json_encode($result);
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
  <script src="../jquery.min.js"></script>
  <link rel="stylesheet" href="../bootstrap.min.css" />
  <script src="../bootstrap.min.js"></script>
  <script src="../jsviews.min.js"></script>
  
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
   <br />
   <h4 align="center">Enter Item Details</h4>
   <br />
   <form method="post" id="insert_form">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
     
     </table>
     <input name="code" type="hidden" id="code" value="wt23532re6436436346dst">
     <div align="center">
       <input type="submit" name="submit" class="btn btn-info" value="Insert" />
   </div>
    </div>
   </form>
  </div>
 </body>
</html>


<script id="productTmpl" type="text/x-jsrender">
    <thead>      
        <tr>
            <th>Price</th>
            <th>Enter Quantity</th>
            <th>Select Product</th>
            <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
        </tr>
    </thead>
    <tbody>
    {^{for selected_products}}
        <tr>
            <td><input type="text" name="item_name[]" readonly data-link="price" class="form-control item_name" /></td>
            <td><input type="text" name="item_quantity[]"  data-link="quantity" class="form-control item_quantity" id="quantity_input" /></td>
            <td><select name="item_unit[]" class="form-control item_unit" id="item_selector"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>
            <td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td>
         </tr>
    {{/for}}
    </tbody>
    <tfoot>
        <tr>
            <td colspan=3>Total</td>
            <td colspan=1 data-link="total"></td>
        </tr>
    </tfoot>
</script>

<script>


 
  
$(document).ready(function(){
    
    /*-----------------------DO NOT TOUCH-------------------------------------*/
    
    var calculateTotal = function(products){
        return products.reduce(function(p, c){
            return p + (c.price * c.quantity)
        }, 0)
    }
    
    var products = <? echo get_items_as_array($connect); ?>;
    var selected_products = []
    var total = 0;
    
    var productTemplate = $.templates("#productTmpl");
    var app = {
        products: products,
        selected_products:selected_products,
        total:total
    };
    
    productTemplate.link("#item_table", app);
    
    $(document).on('click', '.add', function(){
        $.observable(selected_products).insert({name: "", price:"", quantity: 0, id:(new Date()).getTime()});
    })
    
    $(document).on('click', '.remove', function(){
        $.observable(selected_products).remove($.inArray($.view(this).data, selected_products))
        $.observable(app).setProperty({total: calculateTotal(selected_products)})
    });
    
    
     $(document).on('blur', '#quantity_input', function(ev){
        var active_data = $.view(this).data;
        $.observable(active_data).setProperty({quantity: this.value}) 
        $.observable(app).setProperty({total: calculateTotal(selected_products)})
     })
    
    $(document).on('change', '#item_selector', function(ev){
        selected_item_name = this.value;
        var item = products.find(function(element) {
            return element.unit_name === selected_item_name;
        });
        if(typeof(item) !== "undefined"){
            var active_data = $.view(this).data;
            $.observable(active_data).setProperty({name:item.name, price:item.price, quantity: 1})      
            $.observable(app).setProperty({total: calculateTotal(selected_products)})
        }else{
            console.error("item", item)
        }
     
    });
    
 /*---------------------------------DO NOT TOUCH------------------------------*/
 
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.item_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_unit').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>