<?php    include_once('../config/db.php');  include_once('../config/check.php'); include_once('../functions/item/price.php');


 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
        
      $billtype =       9 ; 
      $startdate =         htmlspecialchars (strtoupper($_POST['startdate']));
      $date =         date("Y-m-d", strtotime($startdate));
      
      $currency =           htmlspecialchars (strtoupper($_POST['currency']));
      $pricegroup =           htmlspecialchars (strtoupper($_POST['pricegroup']));
      $memo   =            htmlspecialchars ( $_POST['memo']);   
                
      $item =              $_POST['item'];
      $variant =   0;  
      $unit =               $_POST['unit'];
      $uom =               $_POST['uom'];
      $bp =                 $_POST['bp'];
      $price =              $_POST['price'];
      $vat =               $_POST['vat'];
     
      $number = count($_POST["item"]); 
        
      if($number > 0)  
          {  
            for($i=0; $i<$number; $i++)  
            {    
              $sql = 'INSERT INTO itemprice(date,currency,pricegroup,item,uom,variant,unit,itembp,itemprice,itemtaxrate,memo)
                                    VALUES (:date,:currency,:pricegroup,:item,:uom,:variant,:unit,:itembp,:itemprice,:itemtaxrate,:memo)'; 
              $stmt = $conn->prepare($sql)->execute(['date' =>$date,'currency'=>$currency,'pricegroup'=>$pricegroup,'item' =>$item[$i],'uom' =>$uom[$i],
                                                     'variant' =>$variant,'unit' => $unit[$i],'itembp' =>$bp[$i],
                                                     'itemprice'=>$price[$i],'itemtaxrate' => $vat[$i], 'memo' => $memo[$i]  ]);
            }

            // inserting into footer 

           
          } else{}
            
        header("location:price.php"); 
} catch(Exception $e) { echo 'Message: ' .$e->getMessage();}
       
?>

<!DOCTYPE html>
<html>
<head>
<?php include_once('../inc/slink.php');   ?>  
</head>
<body <?php include_once('../inc/snav.php');  ?>
<div class="wrapper">

  <!-- Main Header -->
    <header class="main-header">

    <!-- Logo -->
       <?php include_once('../inc/sbrand.php');   ?>

    <!-- Header Navbar -->
    <?php include_once('../inc/snavbar.php');   ?>

  </header>
 
  <!-- Left side column. contains the logo and sidebar -->
    <aside class="main-sidebar">

    <!-- sidebar: style can be found in sidebar.less -->
     <?php include_once('../inc/smenu.php');   ?>
    <!-- /.sidebar -->
  </aside>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
 

  <section class="content-header" style="padding-bottom:0px;">
    <div class="row">
      <div class="">
         <div class="col-md-4">
             <p class="listheader" > <i class="fa fa-plus-circle" ></i>ADD PRICE </p>
                
     
         </div>
         <div class="col-md-4">
              <span id="currency">  </span> 
         </div>
         <div class="col-md-4">
                     <a  href="prices" class="listbtn btn-primary btn-sm pull-right  " > <i class="fa fa-bars"></i> VIEW ALL PRICES  </a>
          
         </div>
      </div>
   
    </div>
   
  </section>

  
   

  <!-- Main content -->
  <section class="content container-fluid" style="padding-top:0px;">
 
      <div class="box box-default box-xs">
              <div class="box-body">
                  <div class="row">             
                    <form class="form-horizontal "  action="" method="post"  >
                                                <div class="col-md-3 ">
                                                    <label > Date  </label>
                                                    <input type="text" class="form-control datepicker " autocomplete="off" name="startdate">    
                                                </div>                                                                                
                                                                                                
                                                <div class="col-sm-3">  
                                                        <label> Price Currency </label>  
                                                        <select class="form-control js-example-basic-single"   name="currency" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM acccurrency   ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <option></option>
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                                        </select>        
                                                </div> 
                                                <div class="col-sm-3">  
                                                        <label> Price Group </label>  
                                                        <select class="form-control js-example-basic-single"   name="pricegroup" style="width:100%" >
                                                            <?php $stmt = $conn->prepare("SELECT * FROM admpricegroup   ");
                                                            $stmt->execute(); foreach ($stmt as $row) {?>
                                                                    <option></option>
                                                                    <option value="<?php echo $row['id']; ?>"><?php
                                                                        echo $row['name']; ?></option> <?php } ?>
                                                        </select>        
                                                </div> 
                                                                             
                                                <div class="col-md-3">
                                                   <label>  Memo Reference   </label>
                                                   <input type="text" class="form-control" name="memo" required='' autocomplete="off">
                                                </div> 
                                             
                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                                  <!---  QUOTE HEADER  --->                               
                                                
                                                        <div class="col-xs-12" style="margin-top:2px;">
                                                            <table class="table table-bordered table-condesed table-stripped table-sm table-condensed bg-default  item_table " id="item_table" >
                                                                      <tr class="">
                                                                      <th style="width:20%;">   Item</th>
                                                                      <!-- <th style="width:18%;">   Details   </th> -->
                                                                      <th style="width:10%;">   Uom  </th>
                                                                      <th style="width:10%;">   Unit  </th>
                                                                      <th style="width:12.5%;">   Buying Price  (<span id="bcode" style="color:white; font-size:16px; "></span> )  </th>
                                                                      <th style="width:15%;">   Selling Price  (<span id="bcode" style="color:white; font-size:16px; "></span> )  </th>
                                                                      <th style="width:12.5%;">   Tax obligation </th>
                                                                      <th style="width:10%;">  Price After Tax </th>
                                                                      <th style="width:10%;" >      
                                                                          <button  type="button" class="btn btn-default btn-xs btn-block add" name="add">  <i class=" fa fa-plus-circle fa-sm"></i> Add </button>
                                                                      </th>
                                                                    </tr>
                                                              </table>
                                                        </div>
                                                    
                                                    <!---  QUOTE HEADER  --->                                                      
                                          </div> 

                                          <div class="col-sm-12  "  >   
                                                                                          
                                          </div>  
                                        
                                        
                                          <!-- submit button -->
                                        <div class="form-group " >
                                          <div class="col-sm-offset-4 col-xs-10" style="padding-top:10px;">                             
                                            <button type="submit"name="submit" class=" subbtn btn btn-primary col-xs-4">
                                                <i class="fa fa-plus-circle "></i> ADD NEW PRODUCT PRICE </button>
                                                </div>
                                    </div>
                            
                        
                    </form>
                        
                    
                </div>
            </div>
      
   </section>
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('../inc/sfooter.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->
<?php include_once('../inc/slinkjs.php') ?>

</body>
</html>

<!-- dynamic rows start here -->
<script>
    
$(document).ready(function(){

    var i=0; 
 
 $(document).on('click', '.add', function(){
    i++;  
  var html = '';
   html += '<tr id="row'+i+'">';
   html += '<td><select name="item[]" id="item_'+i+'" required="" class="form-control item js-example-basic-single "><option value="">Select </option><?php echo item($conn); ?></select><input type="hidden" name="coa[]" id="coa_'+i+'"  class="form-control coa " /></td>';
   //html += '<td><input type="text" name="name[]" id="name_'+i+'" class="form-control table-condesed item_name" autocomplete="off"  required="" /></td>';
   html += '<td> <select name="uom[]"  id="uom_'+i+'" class="form-control item_uom js-example-basic-single  "><?php echo uom($conn); ?></select></td>';
   html += '<td><input type="text" name="unit[]" value="1"  id="unit_'+i+'" class="form-control table-condesed item_unit" autocomplete="off" readonly="true" /></td>';
   html += '<td><input type="" name="bp[]" id="bp_'+i+'" class="form-control item_bp" required="" /></td>';
   html += '<td><input type="" name="price[]" id="price_'+i+'" class="form-control item_price" required="" /></td>';
   html += '<td><select name="vat[]"   required="" id="vat_'+i+'" class="form-control item_vat js-example-basic-single "><option value="1"> ZERO RATED </option><?php echo vat($conn); ?></select></td>';  
     
   html += '<td><input type="hidden" name="vatamount[]" id="vatamount_'+i+'" value="0" class="form-control item_vatamount " /> <input type="hidden" name="total[]" id="total_'+i+'" value="0" class="form-control item_total " /><input type="text" name="payable[]" id="payable_'+i+'"  class="form-control item_payable " /></td>';  
   html += '<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn-block remove"> <i class="fa fa-trash"></i> </button></td></tr>';
      
  $('#item_table').append(html);
                                      
     
  // DELETE A ROW 
          $(document).on('click', '.remove', function(){  
           var button_id = $(this).attr("id");   
         //  $('#row'+button_id+'').remove();  
         if( button_id > 1)
               {
                   $('#row'+button_id+'').remove(); 
                }else{}
         
           ///calculateTotal (); calculatePayable (); calculateVat ();  
              
      }); 
     
  //  INITIALIZE SELECT 2 ON DYNAMIC TABLE 
     
              $('.js-example-basic-single').select2({
                placeholder:'',
                width: 'resolve'        
            });

// SELECTED ITEM CHANGE 
        $("#item_table").on('change', '.item', function()
            {
               var item =      $(this).closest('tr').find('.item').val();
               var stockcoa = function () { var stockcoa = 0 ;
                                    $.ajax({
                                            async: false, 
                                            'type': "POST",                                          
                                            'url': "../zajax/aj.item.php",
                                            'data': { item:item  },
                                            'success': function (data) {  
                                                                          var ob=jQuery.parseJSON(data); 
                                                                          stockcoa = parseInt(ob.stockcoa) ;                                                                              
                                                                          // alert(stockcoa) ;                                                                            
                                                                      }
                                            });  return  stockcoa;
                                  }();
               $(this).parents("tr").find(".coa").val(stockcoa);   
                                                  
            });

     
// PRICE CHANGE 
            $("#item_table").on('change', '.item_price', function(){

                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
                      
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "../aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                        var ob=jQuery.parseJSON(data); 
                                                                                         vat_rate = parseInt(ob.value) ;    
                                                                                                                                                                    
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                     
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                     
                                                                 });
// UNIT CHNAGE 
$("#item_table").on('change', ".item_unit", function()
         {                     
                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "../aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                        var ob=jQuery.parseJSON(data); 
                                                                                         vat_rate = parseInt(ob.value) ;                                                                                     
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                                         
          }); 
// VAT CHANGE 
$("#item_table").on('change', ".item_vat", function()
         {                     
                      var unit =      $(this).closest('tr').find('.item_unit').val();
                      var price =     $(this).closest('tr').find('.item_price').val();                      
                      var vat =       $(this).closest('tr').find(' .item_vat :selected').val();
                      var vat_rate = function () { var vat_rate = 0 ;
                                                   $.ajax({
                                                          async: false, 
                                                          'type': "POST",                                          
                                                          'url': "../aj.taxrate.php",
                                                          'data': { vat: vat  },
                                                          'success': function (data) {  
                                                                                       var ob=jQuery.parseJSON(data); 
                                                                                         vat_rate = parseInt(ob.value) ;                                                                                 
                                                                                     }
                                                           });  return   vat_rate;
                                                 }();
                      var total = unit * price ;                          
                      var myvat = total * vat_rate /100 ;
                      var payable = myvat + total; 
                      $(this).parents("tr").find(".item_total").val(total);  
                      $(this).parents("tr").find(".item_vatamount").val(myvat) ; 
                      $(this).parents("tr").find(".item_payable").val(payable) ;             
                                         
          }); 


 

     
     
 });
       
                                                                               
                                                  

                   });
</script>
<!-- DYANAMIC ROWS LISTING HERE --->

<!-- DYNAMIC ROWS ENDS HERE --->