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



 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
        $billtype =        2 ; //  htmlspecialchars (strtoupper($_POST['billstatus']));
        $startdate =         htmlspecialchars (strtoupper($_POST['startdate'])); $startdate = date("Y-m-d", strtotime($startdate));
        $enddate =           htmlspecialchars (strtoupper($_POST['enddate']));   $enddate = date("Y-m-d", strtotime($enddate));
        $partner =           htmlspecialchars (strtoupper($_POST['partner']));
        $memo   =            htmlspecialchars (strtoupper($_POST['memo']));              
        $description =       htmlspecialchars (strtoupper($_POST['description']));     
       // $split =  1 ;      
       // $amount =  0.00 ;      
       // $cr =  0;      
       // $dr =  29 ;   
                  
        $subtotal   =    htmlspecialchars (strtoupper($_POST['g_subtotal']));        
        $tax   =         htmlspecialchars (strtoupper($_POST['g_vat']));        
        $total   =       htmlspecialchars (strtoupper($_POST['g_total']));

        $item =              $_POST['coa'];
        $name =              $_POST['name'];
        $uom =              $_POST['uom'];
        $unit =              $_POST['unit'];
        $price =             $_POST['price'];
        $vat =               $_POST['vat'];
        $vamount =           $_POST['vatamount'];
        $gross =             $_POST['total'];
        $payable =           $_POST['payable'];
        
        $number = count($_POST["coa"]);  
        
      if($number > 0)  
          {  
                  
              $sql = 'INSERT INTO purpo(startdate,enddate,partner,memo,description,subtotal,tax,total,type,uid) VALUES (:startdate,:enddate,:partner,:memo,:description,:subtotal,:tax,:total,:type,:uid)';     
              $stmt = $conn->prepare($sql)->execute(['startdate'=>$startdate,'enddate'=>$enddate,'partner' =>$partner, 'memo' => $memo  ,'description'=>$description,'subtotal'=> $subtotal,'tax'=> $tax,'total'=> $total,'type'=>$billtype,'uid'=>$uid  ]); 
              $lastid = $conn->lastInsertId(); 
          
              for($i=0; $i<$number; $i++)  
                {  
                  
                  $sql = 'INSERT INTO purpoitem (transactionid,item,name,uom,unit,price,gross,tax,taxamount,total)
                                          VALUES(:tid,:item,:name,:uom,:unit,:price,:gross,:trate,:tamount,:total)'; 
                  $stmt = $conn->prepare($sql)->execute(['tid' => $lastid,'item' =>$item[$i],'name' => $name[$i],'uom'=>$uom[$i],'unit' => $unit[$i] ,
                                                          'price' => $price[$i],'gross' => $gross[$i], 'trate' => $vat[$i], 
                                                          'tamount' => $vamount[$i], 'total' => $payable[$i] ]);

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



?>

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

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

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

    <!-- Header Navbar -->
    <?php include_once('inc/navbar.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/menu.php');   ?>
    <!-- /.sidebar -->
  </aside>

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

    <section class="content-header">
      <h1>  <i class="fa fa-plus-circle" >  </i> Add Sales Quote    </h1>
        <ol class="breadcrumb">
          <li><a href="#"><i class="fa fa-dashboard"></i> </a></li>
          <li><a href="#"> </a></li>
          <li class="active"> </li>
          <li><a href="crmsquotel.php" class="btn btn-default btn-sm"> <i class="fa fa-bars"></i> View All Sales Quote </a></li>
        </ol>
    </section>

  <!-- Main content -->
  <section class="content container-fluid">
 
      <div class="box box-success box-xs">
              <div class="box-body">
                  <div class="row">             
                    <form class="form-horizontal "  action="" method="post"  >
                    
                                  <div class=" " style="" > 
                                                     
                                        <!-- CURRENT DATE  --->
                                              <!-- <div class="col-md-2">
                                                    <label>  Bill/Expense Status *   </label>
                                                      <select class="form-control  js-example-basic-single "  required="" name="billstatus" style="" >
                                                        <option value='6'> Paid  </option>
                                                        <option value='7'> Credit </option>
                                                      </select>     
                                                </div> -->

                                                <div class="col-md-2">
                                                    <label > Start Date  </label>
                                                    <input type="text" class="form-control datepicker " autocomplete="off" name="startdate">    
                                                </div>                                                                                
                                                <div class="col-md-2">
                                                      <label > Due Date   </label>
                                                      <input type="text" class="form-control datepicker " autocomplete="off" name="enddate" required=""> 
                                                </div>
                                                <div class="col-md-2">
                                                      <label> Supplier* </label>
                                                        <select class="form-control  js-example-basic-single "  required="" name="partner" style="" >
                                                        <?php $stmt = $conn->prepare("SELECT * FROM bppartner where type=1  ");
                                                              $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-2">
                                                   <label>  Memo/ Reference No  </label>
                                                   <input type="text" class="form-control" name="memo" required='' autocomplete="off">
                                                </div> 
                                                <div class="col-md-4">
                                                    <label>  Description   </label>
                                                    <input type="text" name="description"  class="form-control" autocomplete="off">
                                                </div>
                                               
                                                
                                    </div>                                

                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                                  <!---  QUOTE HEADER  --->                               
                                                    <div class="col-xs-12">
                                                        <div class="" style="margin-top:5px;">
                                                            <table class="table table-bordered table-condesed table-sm table-condensed bg-success  item_table " id="item_table" >
                                                                      <tr class="default">
                                                                      <th style="width:15%;">   Item</th>
                                                                      <th style="width:20%;">   Details   </th>
                                                                      <th style="width:13%;">   Uom  </th>
                                                                      <th style="width:13%;">   Unit  </th>
                                                                      <th style="width:13%;">   Price </th>
                                                                      <th style="width:15%;">   Tax </th>
                                                                      <th style="width:15%;" >  Total </th>
                                                                      <th style="width:2%;" >      
                                                                          <button  type="button" class="btn btn-success btn-xs btn-block add" name="add">  <i class=" fa fa-plus-circle fa-sm"></i> Add </button>
                                                                      </th>
                                                                    </tr>
                                                              </table>
                                                        </div>
                                                    </div>
                                                    <!---  QUOTE HEADER  ---> 
                                                
                                  
                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                              <div class="col-sm-12 bg-default "  >   
                                                <div class="col-md-6">
                                                
                                                </div>
                                                <div class="col-md-6">
                                                    
                                                    <div class="col-md-4">
                                                      <label> Subtotal: </label>
                                                      <input type="text"  value=""  name="g_subtotal" class="form-control"  style="border:none;" >
                                                    </div>  
                                                    <div class="col-md-4">
                                                      <label> Vat: </label>
                                                      <input type="text"  value="" name="g_vat"class="form-control" style="border:none;" >
                                                      <!-- <input type="text"  value=""  name="g_subtotal" class="form-control"  style="border:none;" > -->
                                                    </div>  
                                                    <div class="col-md-4">
                                                      <label> Total </label>
                                                      <input type="text"   value="" name="g_total"  id="quotepay"class="form-control totalsum" style="border:none;" >
                                                    </div>
                                                
                                                </div>
                                                                                                     
                                        </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="btn btn-success col-xs-4">
                                                <i class="fa fa-plus-circle "></i> Add Sales Quote   </button>
                                                </div>
                                    </div>
                            
                        
                    </form>
                        
                    
                </div>
            </div>
      
   </section>
</div>
  <!-- /.content-wrapper -->
  
  <!-- Main Footer -->
  <footer class="main-footer">
    <?php  include_once('inc/footer.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->
<?php include_once('inc/linkjs.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="coa[]" class="form-control item_coa js-example-basic-single "><option value="">Select </option><?php echo sale($conn); ?></select></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" /></td>';
   html += '<td><input type="" name="price[]" id="price_'+i+'" class="form-control item_price"  /></td>';
   html += '<td><select name="vat[]"  id="vat_'+i+'" class="form-control item_vat js-example-basic-single "><option value="2">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();  
              
      }); 
     
  //  INITIALIZE SELECT 2 ON DYNAMIC TABLE 
     
              $('.js-example-basic-single').select2({
                placeholder:'SELECT',
                width: 'resolve'        
            });
     
// 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) ;    
                                                                                         alert(vat_rate)   ;                                                                              
                                                                                     }
                                                           });  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) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();  
                                                                 });
// 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) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();                    
          }); 
// 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) ;             
                      calculateTotal (); calculatePayable (); calculateVat ();                    
          }); 

     
     
 });
       
                                      
                        
                                    function calculateTotal () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='total[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='g_subtotal']").val(sum);
                                                                                                    });  
                                                                                      });
                                                             }
          
                                   function calculatePayable () { $(".item_table").each(function () {  
                                                     var sum = 0; 
                                                      $("input[name='payable[]']").each(function () {
                                                      if (!isNaN(this.value) && this.value.length != 0) 
                                                             { sum += parseFloat(this.value);  }
                                                                       $("input[name='g_total']").val(sum);
                                                                       $("input[name='invamount']").val(sum);
                                                                                                    });  
                                                                                      });
                                                                 }
                        
                                     function calculateVat () { $(".item_table").each(function () {  
                                                         var sum = 0; 
                                                          $("input[name='vatamount[]']").each(function () {
                                                          if (!isNaN(this.value) && this.value.length != 0) 
                                                                 { sum += parseFloat(this.value);  }
                                                                      $("input[name='g_vat']").val(sum);
                                                                      
                                                                                                        });  
                                                                  });
                                                              }
                                                       
                                                  

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

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