	<?php

require 'connection.php';

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

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

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

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