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

  $invoicenum= getnewinvoicenum($conn);
 

 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
    $billtype =       10 ; 
    $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 ($_POST['memo']);              
    $description =       htmlspecialchars ($_POST['description']);     
    $notes =       htmlspecialchars (strtoupper($_POST['notes']));   
    $split =  1 ;      
     
    $cr =  0;      
    $type =  10 ;   
    $dr =  68 ; 
    $cogs= 176;  

    $currency =       currency($conn,$partner); 
    $erate =       erate($conn,$partner); 
    $gvatcoa   =    1;      
    $g_vat   =         htmlspecialchars (strtoupper($_POST['g_vat']));  

    $amount   =       htmlspecialchars (strtoupper($_POST['g_total']));
    $glamount =  $amount *  $erate ;
    $item =              $_POST['item'];
    $salecoa =              $_POST['salecoa'];
    $stockcoa =              $_POST['stockcoa'];
    $pcost =              $_POST['pcost'];
    

    $name =              $_POST['name'];
    $uom =              $_POST['uom'];
    $uomrate =              $_POST['uomrate'];
    $unit =              $_POST['unit'];
    $price =             $_POST['price'];
    $vat =               $_POST['vat'];
    $vamount =           $_POST['vatamount'];
    $gross =             $_POST['total'];
    $payable =           $_POST['payable'];
    
    $number = count($_POST["item"]); 
        
      if($number > 0)  
          {  

             $sql = 'INSERT INTO acctransaction(invoicenum,date,enddate,bpartner,split,memo,currency,erate,amount,glamount,dr,description,notes,type,uid)
              VALUES (:invoicenum,:startdate,:enddate,:partner,:split,:memo,:currency,:erate,:amount,:glamount,:dr,:description,:notes,:type,:uid)';     
              $stmt = $conn->prepare($sql)->execute(['invoicenum'=>$memo,'startdate'=>$startdate,'enddate'=>$enddate,'partner' =>$partner,'split'=>$split,
                                                    'memo' => $memo,'currency' => $currency,'erate' => $erate,'amount' => $amount ,'glamount' => $glamount ,'dr' => $dr ,'description' => $description,'notes' => $notes,'type'=>$billtype,'uid'=>$uid  ]); 
              $lastid = $conn->lastInsertId(); 
              // Inserting into Detailes / Items 
              for($i=0; $i<$number; $i++)  
                {  
                   
                  $sql = 'INSERT INTO acctransaction_item (transactionid,coa,item,name,unit,uom,uomrate,uomunit,price,gross,tax,taxamount,gltaxamount,drsale,crsale,cogs,total,glamount)
                                          VALUES(:tid,:coa,:item,:name,:unit,:uom,:uomrate,:uomunit,:price,:gross,:trate,:tamount,:gltamount,:drsale,:crsale,:cogs,:total,:glamount)'; 
                  $stmt = $conn->prepare($sql)->execute(['tid' => $lastid,'coa' =>$salecoa[$i],'item' =>$item[$i],'name' => $name[$i],'unit' => ($unit[$i] * $uomrate[$i] ) ,'uom' => $uom[$i],'uomrate' => $uomrate[$i] ,'uomunit'=>$unit[$i],
                                                          'price' => $price[$i],'gross' => $gross[$i], 'trate' => $vat[$i], 
                                                          'tamount' => $vamount[$i],'gltamount' =>  ( $vamount[$i] * $erate), 'drsale'=>$cogs,'crsale'=>$stockcoa[$i],'cogs'=> ( $pcost[$i]* ($unit[$i] * $uomrate[$i] ) ), 'total' => $payable[$i],'glamount' => ( $gross[$i] * $erate)  ]);
                }  
              
              
          } else{}
            
        header("location:acc_invoice.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" style="padding-bottom:0px;">
    <p style="color:green; font-size:20px; font-weight:bold; " > <i class="fa fa-file-o" ></i> SALES INVOICE </p>
         
        <ol class="breadcrumb">
          
          <li> <a href="acc_invoicel" > <button class="btn  btn-sm btn-default " > <i class="fa fa-bars "></i> View all Sales Invoice </button>    </a></li>
          
         
        </ol>
      </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=" "  > 
                                                     
                                        <!-- CURRENT DATE  --->                                          
                                                <div class="col-md-2">
                                                   <label>  INVOICE NUMBER  </label>
                                                   <input type="text" class="form-control" name="memo" required=''  value=" <?php echo"$invoicenum" ?>" autocomplete="off">
                                                </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> Customer* </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-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:4px;">
                                                            <table class="table table-bordered table-condesed table-sm table-condensed bg-default  item_table " id="item_table" >
                                                                      <tr class="bg-primary">
                                                                      <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 (<span id="bcode" style="color:white; font-size:18px; "></span> ) </th>
                                                                      <th style="width:15%;">   Tax </th>
                                                                      <th style="width:15%;" >  Total </th>                                                                      
                                                                      <th style="width:2%;" >      
                                                                          <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>
                                                    </div>
                                                    <!---  QUOTE HEADER  ---> 
                                                
                                  
                                              <!---  QUOTE PRODUCTS AND DETAILS   --->
                                              <div class="col-sm-12"  >  
                                                <!---  Start End details   --->
                                                <div class="col-sm-4" style="padding-top:10px;">
    
                                                                   <label  class=" control-label"> Amount in words: </label>
                                                                    <textarea class="form-control" name="notes" required=""></textarea>
                                                                  
                                                   
                                                   </div>              
                                                   <div class="col-sm-6 pull-right" style="border:none; border-width:thin; border-color:lightgrey;"  >                                     
                                                       
                                                               
                                                              <label for="inputEmail" class="col-md-6 control-label"> Subtotals: </label>
                                                                 <div class="col-sm-6">    
                                                                    <input type="text"  value=""  name="g_subtotal" class="form-control"  style="" >
                                                                  </div>
 
                                                              <label for="inputEmail" class="col-md-6 control-label"> Tax <span id="taxname">  </span>  </label>
                                                                  <div class="col-sm-6">
                                                                    <input type="text"  value="" name="g_vat"class="form-control" style="margin-top:2px;margin-bottom:2px;" >
                                                                  </div>
                                                                                                                        
                                                             <label for="inputEmail" class="col-md-6 control-label"> Total:  </label>
                                                               <div class="col-sm-6">
                                                                   <input type="text"   value="" name="g_total"  id="quotepay"class="form-control totalsum" style="" >
                                                                   
                                                             </div>
             
                                                             
                                                   </div> 
                                                   <!-- End Totals -->   
 
                                          <!-- 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-primary col-xs-4">
                                                <i class="fa fa-plus-circle "></i> Add sales Invoice   </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>

  // currency and balance for partners 
$("select[name='partner']") .change(function(){        
     var partner = $("select[name='partner']").val();  
                  $.ajax({
                              async: false, 
                              'type': "POST",                                          
                              'url': "zajax/aj.partnerd.php",
                              'data': { partner:partner  },
                              'success': function (data) {  
                                                            var ob=jQuery.parseJSON(data); 
                                                              code = ob.bcode ;   
                                                              $("#bcode").text(code);                                                                         
                                                          }
                                });               
                         
                     });
  // uom conversion
  // $("select[name='uom']") .change(function(){        
  //    var uom = $("select[name='uom']").val();  
  //                 $.ajax({
  //                             async: false, 
  //                             'type': "POST",                                          
  //                             'url': "zajax/aj.uomsale.php",
  //                             'data': { partner:partner  },
  //                             'success': function (data) {  
  //                                                           var ob=jQuery.parseJSON(data); 
  //                                                             code = ob.bcode ;   
  //                                                             $("#bcode").text(code);                                                                         
  //                                                         }
  //                               });               
                         
  //                    });


    
$(document).ready(function(){
    var i=0; 
 
 $(document).on('click', '.add', function(){
    i++;  
  var html = '';
   html += '<tr id="row'+i+'">';
   html += '<td><select name="item[]" class="form-control item_coa js-example-basic-single "><option value="">Select </option><?php echo sale($conn); ?></select><input type="hidden" name="salecoa[]" id="salecoa_'+i+'"  class="form-control salecoa " /><input type="hidden" name="stockcoa[]" id="stockcoa_'+i+'"  class="form-control stockcoa " /><input type="hidden" name="pcost[]" id="pcost_'+i+'"  class="form-control pcost " />  </td>';
   html += '<td><input type="text" name="name[]" id="name_'+i+'" class="form-control table-condesed item_name" autocomplete="off"  required="" /></td>';
   html += '<td><input type="hidden" name="uomrate[]"   id="uomrate_'+i+'" class="form-control table-condesed item_uomrate" autocomplete="off" /> <select name="uom[]"  id="uom_'+i+'" class="form-control item_uom js-example-basic-single  "><option value="">Select </option><?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="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'        
            });

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

 // UOM RATE
 $("#item_table").on('change', '.item_uom', function(){
var uom =      $(this).closest('tr').find('.item_uom').val();
var uom_rate = function () { var uom_rate = 0 ;
                             $.ajax({
                                    async: false, 
                                    'type': "POST",                                          
                                    'url': "zajax/aj.uomsale.php",
                                    'data': { uom:uom },
                                    'success': function (data) {  
                                                                  var ob=jQuery.parseJSON(data); 
                                                                   uom_rate = ob.erate ;    
                                                                  // alert(uom_rate)   ;                                                                              
                                                               }
                                     });  return   uom_rate;
                           }();
 $(this).parents("tr").find(".item_uomrate").val( uom_rate);  
                                           });
// UOM RATE                                 

// 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 --->