	<?php

require 'connection.php';

    $posted="";
   $qrysl = "SELECT saleid FROM sales where  posted='$posted'";
   $runsl = mysqli_query($connect, $qrysl) or die(mysqli_error($connect));
   while($rowsl = mysqli_fetch_array($runsl)){
    $vno=$rowsl['saleid']; 
    $tamount=0;
    
   $qry = "SELECT costout FROM stockledger where vno = $vno and def='4'";
   $run = mysqli_query($connect, $qry) or die(mysqli_error($connect));
   while($row = mysqli_fetch_array($run)){
    $tamount= $tamount+  $row['costout'];
}

 			// Get account ID grom Sales table
      $qry = "SELECT * FROM sales where saleid='$vno'";
      $run = mysqli_query($connect, $qry) or die(mysqli_error($connect));
   		$row = mysqli_fetch_array($run);
   	$accid= $row['accid'];
		$dated= $row['dated'];
		$Invono= $row['billno'];
		$accid= $row['accid'];
    $dated= $row['dated'];
    $posted='posted';
  //       // For Sales Update Posted
    $purqry = "UPDATE `sales` SET netamt='$tamount',dated='$dated',billno='$Invono',accid='$accid' ,posted='$posted' where saleid=$vno";
		$purrun = mysqli_query($connect, $purqry) or die(mysqli_error($connect));

 // For Ledger Instert Party Account
    $desc= 'Sales # '.$vno;
 $ledgerqry="INSERT INTO `ledger`(`smid`, `dated`, `accid`, `description`, `vno`, `refno`, `entrytype`, `debit`) VALUES('4', '$dated','$accid','$desc','$vno','$vno','Med-SL','$tamount')";
  $ledgerrun=mysqli_query($connect,$ledgerqry) or die(mysqli_error($connect));
  
// For Ledger Instert Sales Account
    $desc= 'Sales # '.$vno;
 $purqry="INSERT INTO `ledger`(`smid`, `dated`, `accid`, `description`, `vno`, `refno`, `entrytype`, `credit`) VALUES('4', '$dated','2','$desc','$vno','$vno','Med-SL','$tamount')";
  $purrun=mysqli_query($connect,$purqry) or die(mysqli_error($connect));
}

if($runsl){
  echo "Invoice Posted successfully !";
}
?>