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


     $lastinv = $conn->query("SELECT COALESCE(invnumber,0) invnumber   FROM  acctransactions  where transtype=10 order by id desc ")->fetch();
     $docnumber =  $lastinv['invnumber'] + 1 ;


 if (filter_has_var(INPUT_POST, "submit")) 
  try{  
      
        $transtype =         10 ; 
        $transaction =       1 ; 
        $transmode =         1 ; 


        $date =              htmlspecialchars (strtoupper($_POST['date'])); 
        $date =                date("Y-m-d", strtotime($date));
        $enddate =           htmlspecialchars (strtoupper($_POST['enddate']));
        $enddate =           date("Y-m-d", strtotime($enddate));

        $branch =            htmlspecialchars (strtoupper($_POST['branch']));
        $partner =            htmlspecialchars (strtoupper($_POST['partner']));
        $invnum  =            htmlspecialchars ($_POST['invnum']);              
        $memo =               htmlspecialchars ($_POST['description']);     
        $memo2 =              '';     
        $notes =              '';  
        $description =            htmlspecialchars ($_POST['description']);  
      

        $currency =       currency($conn,$partner); 
        $erate =        erate($conn,$partner);

       // footer details 
       $subtotal       =         htmlspecialchars (strtoupper($_POST['g_subtotal']));  
    
       $vatall   =         htmlspecialchars (strtoupper($_POST['g_vat']));  
       $totalvat   =    $vatall *  $erate;       
       $amount   =       htmlspecialchars (strtoupper($_POST['g_total']));
       $total =  $amount *  $erate ;

       // footer details 

       $item =              $_POST['item'];
       $salecoa =              $_POST['salecoa'];
       $stockcoa =              $_POST['stockcoa'];
       $cogscoa =              $_POST['cogscoa'];
    
        $name =              $_POST['name'];
        $uom =              $_POST['uom'];
        $uombase =           $_POST['uombase'];
        $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)  
 {  

       
    $sql1 = 'INSERT INTO acctransactions(date,enddate,invnumber,memo,voucher,notes,description,transtype,transaction,transmode,transuid,storeID) VALUES (:date,:enddate,:invnumber,:memo,:voucher,:notes,:description,:transtype,:transaction,:transmode,:transuid,:storeID)';     
    $stmt = $conn->prepare($sql1)->execute(['date'=>$date,'enddate'=>$enddate,'invnumber'=>$invnumber,'memo'=>$memo,'voucher'=>$memo2,'notes'=>$notes,'description'=>$description,'transtype' =>$transtype,'transaction'=>$transaction,'transmode' =>$transmode,'transuid'=>$uid, 'storeID'=>$storeID  ]); 
     $lastid = $conn->lastInsertId(); 

   
    // Inserting into Detailes / Items debeting 
    for($i=0; $i<$number; $i++)  
       {  
          $sql = 'INSERT INTO acctransactionsdetails(transid,docid,branch,warehouse,partner,currency,erate,coa,stockcoa,cogscoa,item,itemdetails,itemuom,itemuombase,itemuomrate,
                                                    itemunit,itemunitbase,itemout,itemprice,
                                                    itemsubtotal,itemtaxrate,itemtax,itemtotal,total,transmove )
                  VALUES( :transid,:docid,:branch,:warehouse,:partner,:currency,:erate,:coa,:stockcoa,:cogscoa,:item,:itemd,:itemuom,
                          :itemuombase,:itemuomrate,:itemunit,:itemunitbase,:itemout,:itemprice,
                          :itemsubtotal,:itemtaxrate,:itemtax,:itemtotal,:total,:transmove )'; 

           $stmt = $conn->prepare($sql)->execute([
                               'transid' => $lastid,'docid' =>$invnum,'branch' =>$branch,'warehouse'=>$branch,'partner' =>$partner,'currency'=>$currency,
                               'erate'=>$erate,'coa' =>$salecoa[$i],'stockcoa' =>$stockcoa[$i],'cogscoa' =>$cogscoa[$i],'item' =>$item[$i],'itemd' => $name[$i],
                               'itemuom' => $uom[$i],'itemuombase' => $uombase[$i],'itemuomrate' => $uomrate[$i],
                               'itemunit'=>$unit[$i],'itemunitbase' => $uombase[$i],'itemout'=>$unit[$i], 
                               'itemprice' => $price[$i],'itemsubtotal' => $gross[$i],'itemtaxrate' => $vat[$i], 'itemtax' => $vamount[$i],
                               'itemtotal' => $payable[$i],'total' => ($payable[$i]*$erate),'transmove' =>1  ]);
       }  
        // crediting     
        $sql = 'INSERT INTO acctransactionsdetails(transid,docid,branch,partner,currency,erate,coa,itemtotal,total,transmove ) 
                VALUES(:transid,:docid,:branch,:partner,:currency,:erate,:coa,:itemtotal,:total,:tmove )';

        // subtotal,vat,total
          $conn->prepare($sql)->execute(['transid'=>$lastid,'docid' =>$invnum,'branch'=>0,'partner'=>0,'currency'=>0,'erate'=>0,'coa'=>0,'itemtotal'=>$subtotal,'total'=>0 , 'tmove' =>3  ]);
          $conn->prepare($sql)->execute(['transid'=>$lastid,'docid' =>$invnum,'branch'=>$branch,'partner'=>$partner,'currency'=>$currency,'erate'=>$erate,'coa'=>7,'itemtotal'=>$vatall,'total'=>$totalvat , 'tmove' =>4  ]);
          $conn->prepare($sql)->execute(['transid'=>$lastid,'docid' =>$invnum,'branch'=>$branch,'partner'=>$partner, 'currency'=>$currency,'erate'=>$erate,'coa'=>2,'itemtotal'=>$amount,'total'=>$total , 'tmove' =>5  ]);


 } else{}
            
 // Call ATF    
 audittrail($conn,$lastid,$transtype,$transaction,$transmode,$uid,$storeID);
 
        header("location:invoice.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;">
    <p style="color:green; font-size:20px; font-weight:bold; " > <i class="fa fa-plus-circle" ></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" style="border:solid;border-color:green;border-width:thin;" >
              <div class="box-body">
                  <div class="row" >             
                    <form class="form-horizontal "  action="" method="post"  >
                    
                                 
                                                     
                                        <!-- CURRENT DATE  --->                                          
                                              
                                                <div class="col-md-3">
                                                    <label > Start Date  </label>
                                                    <input type="text" class="form-control datepicker " autocomplete="off" name="date">    
                                                    <input type="hidden" class="form-control  " name="storeid" autocomplete="off" value="<?php echo "$storeID"; ?>">    
                                                </div>                                                                                
                                                <div class="col-md-3">
                                                      <label > Due Date   </label>
                                                      <input type="text" class="form-control datepicker " autocomplete="off" name="enddate" required=""> 
                                                </div>
                                                 
                                             
                                                <div class="col-md-3">
                                                      <label> Customer* </label>
                                                        <select class="form-control  js-example-basic-single "  required="" name="partner"  >
                                                        <?php $stmt = $conn->prepare("SELECT * FROM (SELECT * FROM bppartner where type=1 ) b 
                                                                                       where b.branch='$storeID' or b.branch=0   ");
                                                              $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>  INVOICE NUMBER  </label>
                                                   <input type="text" class="form-control" name="invnum" required=''  readonly="" autocomplete="off" value="<?php echo "$docnumber";  ?>">
                                                </div> 
                                                                          
                                                 
                                                <div class="col-md-3">
                                                      <label> Branch* </label>
                                                        <select class="form-control  js-example-basic-single "  required="" name="branch"  >
                                                        <?php $stmt = $conn->prepare(" SELECT * FROM admbranch a where a.status=1 and a.id='$storeID'  ");
                                                              $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-9">
                                                    <label>  Description*   </label>
                                                    <input type="text" name="description" required=""  class="form-control" autocomplete="off">
                                                </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 compact  item_table " id="item_table" >
                                                                      <tr>
                                                                      <th style="width:13%;">   Item</th>
                                                                      <th style="width:20%;">   Details   </th>
                                                                      <th style="width:10%;">   Uom  </th>
                                                                      <th style="width:10%;">   Availableunit  </th>
                                                                      <th style="width:10%;">   Unit  </th>
                                                                      <th style="width:13%;">   Price (<span id="bcode" style="color:green; font-size:18px; "></span> ) </th>
                                                                      <th style="width:13%;">   Tax </th>
                                                                      <th style="width:17%;">  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"  >
                                                                  </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"  >
                                                                   
                                                             </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=" subbtn btn btn-success 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/sfooter.php'); ?>
  </footer>
  
</div>
                         
<!-- ./wrapper -->

<!-- REQUIRED JS SCRIPTS -->
<?php include_once('../inc/slinkjs.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': "../functions/ajax/partnerdetails.php",
                              'data': { partner:partner  },
                              'success': function (data) {  
                                                            var ob=jQuery.parseJSON(data); 
                                                              code = ob.bcode ;   
                                                              $("#bcode").text(code);                                                                         
                                                          }
                                });               
                         
                     });
 


    
$(document).ready(function(){

// initaialise branch  
 
     // Load system
        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 item($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="cogscoa[]" id="cogscoa_'+i+'"  class="form-control cogscoa " /></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  "><option value="">Select </option><?php echo uom($conn); ?></select><input type="hidden" name="uombase[]" id="uombase_'+i+'"  class="form-control uombase " /><input type="hidden" name="uomrate[]" id="uomrate_'+i+'"  class="form-control uomrate " /></td>';
         html += '<td><input type="text" name="aunit[]" value="0"  id="aunit_'+i+'" class="form-control table-condesed aunit" autocomplete="off" readonly="true" /></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
           $("#item_table").on('change', '.item_coa', function()
                    {
                        var branch = $("input[name='storeid']").val();  
                        // alert(branch);
                        var  item =      $(this).closest('tr').find('.item_coa').val();
                                            $.ajax({
                                                    async: false, 
                                                    'type': "POST",                                          
                                                    'url': "../functions/ajax/itemcurrent.php",
                                                    'data': { item:item,branch:branch },
                                                    'success': function (data) {  
                                                                                  var ob=jQuery.parseJSON(data); 
                                                                                  aitem = parseInt(ob.currentitem) ; 
                                                                                  salecoa = parseInt(ob.salecoa); 
                                                                                  stockcoa = parseInt(ob.stockcoa); 
                                                                                  cogscoa = parseInt(ob.cogscoa); 
                                                                                  
                                                                                                                                                                            
                                                                              }
                                                    });  
                                        
                        $(this).parents("tr").find(".aunit").val(aitem);                      
                        $(this).parents("tr").find(".salecoa").val(salecoa);                      
                        $(this).parents("tr").find(".stockcoa").val(stockcoa);                      
                        $(this).parents("tr").find(".cogscoa").val(cogscoa);                      
                    });
                              
        // Get uom details 
              $("#item_table").on('change', '.item_uom', function()
                    {
                         var  uom =      $(this).closest('tr').find('.item_uom').val();
                                            $.ajax({
                                                    async: false, 
                                                    'type': "POST",                                          
                                                    'url': "../functions/ajax/itemuom.php",
                                                    'data': { uom:uom },
                                                    'success': function (data) {  
                                                                                  var ob=jQuery.parseJSON(data); 
                                                                                  uombase = parseInt(ob.uombase); 
                                                                                  uomrate = parseInt(ob.uomrate);                                                      
                                                                                                                                                                           
                                                                              }
                                                    });  
                                        
                        $(this).parents("tr").find(".uombase").val(uombase);                      
                        $(this).parents("tr").find(".uomrate").val(uomrate);                      
                                             
                    });
                         

        // 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': "../functions/ajax/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': "../functions/ajax/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': "../functions/ajax/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 ();                    
                }); 

            
            
        });

     // end dynamic system
                            
                        
   
    

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