<?php 

require 'connection.php';

for($count = 0; $count<count($_POST['hidden_itemid']); $count++)
{
	
 	$srno= $_POST['hidden_srno'][$count];
 	$itemid= $_POST['hidden_itemid'][$count];
 	$qty= $_POST['hidden_qty'][$count];
 	$qty2= $_POST['hidden_qty'][$count];
 	$rate= $_POST['hidden_rate'][$count];
 	$accid= $_POST['hidden_accid'][$count];
 	$dated= $_POST['hidden_dated'][$count];
 	$vno= $_POST['hidden_vno'][$count];
 	$vno3= $_POST['hidden_vno'][$count];
    
$qryclsstock = "SELECT sum(stockin)-sum(stockout) as clsstock FROM stockledger where itemid = $itemid";
   $runclsstock = mysqli_query($connect, $qryclsstock) or die(mysqli_error($connect));
   $rowclsstock = mysqli_fetch_array($runclsstock);
   $clsstk=$rowclsstock['clsstock'];

   // start check closing stock
if($clsstk>=$qty){
   $qry = "SELECT posted FROM sales where saleid = $vno and posted='posted'";  
   $run = mysqli_query($connect, $qry) or die(mysqli_error($connect));
   $rowposted = mysqli_fetch_array($run);

// if($rowposted['posted']=='posted' or $qty=="" or $rate==""){
   if ($run->num_rows > 0) {
  
$msg= "Invoice already saved operation failed! or some field empty!";
die($msg);
}
else {

$amount=$rate * $qty;


// ************************************SALES TABLE INSERT*****************************************

// Check if Sales no exist or not
$chkprid= $vno;
  $qry = "SELECT saleid FROM sales  where saleid = '$chkprid'";
   $run = mysqli_query($connect, $qry) or die(mysqli_error($connect));
   $count1 = mysqli_num_rows($run);
		if($count1==1){

			// Total amount create
	$qry2 = "SELECT netamt FROM sales  where saleid = '$chkprid'";
   $run2 = mysqli_query($connect, $qry2) or die(mysqli_error($connect));
   $row2 = mysqli_fetch_array($run2);
   $prtotalamt= $row2['netamt'];

   $totalaount= ($prtotalamt)+($amount);
	$qry1 = "UPDATE `sales` SET dated='$dated',billno='$vno',accid='$accid' ,netamt='$totalaount' where saleid=$vno";
	$run = mysqli_query($connect, $qry1) or die(mysqli_error($connect));

 	}
 	else{
// Insert into Sales table
 $query="INSERT INTO `sales`(`saleid`, `dated`, `billno`, `accid`, `netamt`) VALUES('$vno','$dated','$vno','$accid','$amount')";
	$result=mysqli_query($connect,$query) or die(mysqli_error($connect));
 	}

// ***********************************END SALES TABLE INSERT******************************************

// ********************************START SET RATE TABLE INSERT****************************************

// Insert into Set Rate table
 $query="INSERT INTO `setrate`(`accid`, `itemid`, `srate`) VALUES('$accid','$itemid','$rate')";
	$result=mysqli_query($connect,$query) or die(mysqli_error($connect));

// ************************END SET RATE TABLE INSERT************************************

// *********************START VALUATION********************************




$qtyvaluation = "SELECT refno, stockin, ratein, invoiceno from stockledger where itemid='$itemid'";
   $runvaluation = mysqli_query($connect, $qtyvaluation) or die(mysqli_error($connect));
    while ($rowvaluation=mysqli_fetch_array($runvaluation)) {
    		$val_refno=$rowvaluation['refno'];
    		$val_stockin=$rowvaluation['stockin'];
    		$val_ratein=$rowvaluation['ratein'];
    		$val_invoiceno=$rowvaluation['invoiceno'];

   $qryclsstock2 = "SELECT sum(stockout) as clsstock FROM stockledger where itemid = $itemid and refno1='$val_refno' and invoiceno1='$val_invoiceno'";
   $runclsstock2 = mysqli_query($connect, $qryclsstock2) or die(mysqli_error($connect));
   $rowclsstock2 = mysqli_fetch_array($runclsstock2);
   $val_stockout=$rowclsstock2['clsstock'];

   $val_stkbal=$val_stockin-$val_stockout;


   if($val_stkbal>0){
   	
   if($qty2>0){


   if($val_stkbal>=$qty2){

// ***********************SRTART STOCK LEDGER TABLE INSERT***************************
	// Insert into stoctLedger table
	$prvalue= $qty2* $val_ratein;
	$pramount= $qty2* $rate;
	$types= 'Med-SL';
	$query1="INSERT INTO `stockledger`(`srno`, `def`, `dated`, `accid`, `vno`, `refno`, `invoiceno`, `itemid`, `stockout`, `rateout`, `costout`, `prvalue`, `refno1`, `invoiceno1`) VALUES('$srno', '4', '$dated','$accid','$vno','$vno','$types','$itemid','$qty2','$rate','$pramount','$prvalue','$val_refno', '$val_invoiceno')";
	$result1=mysqli_query($connect,$query1) or die(mysqli_error($connect));

// *************************END STOCK LEDGER TABLE INSERT****************************
	$qty2=0;
   }

   else{
   $prvalue= $val_stkbal* $val_ratein;
	$pramount= $val_stkbal* $rate;
	$types= 'Med-SL';
	$query1="INSERT INTO `stockledger`(`srno`, `def`, `dated`, `accid`, `vno`, `refno`, `invoiceno`, `itemid`, `stockout`, `rateout`, `costout`, `prvalue`, `refno1`, `invoiceno1`) VALUES('$srno', '4', '$dated','$accid','$vno','$vno','$types','$itemid','$val_stkbal','$rate','$pramount','$prvalue','$val_refno', '$val_invoiceno')";
	$result1=mysqli_query($connect,$query1) or die(mysqli_error($connect));

// *************************END STOCK LEDGER TABLE INSERT****************************
	$qty2=$qty2-$val_stkbal;
   }


      }
      }

        }

// *********************END START VALUATION********************************


// *****************************START LEDGER DETAIL TABLE INSERT*************************************

	// Insert into ledger
	$desc= 'Sales # '. $vno;
$insrtledger="INSERT INTO `ledger`(`smid`, `dated`, `accid`, `vno`, `refno`, `entrytype`, `description`, `itemid`, `qty`, `rate`) VALUES('4', '$dated','$accid','$vno','$vno','$types','$desc','$itemid','$qty','$rate')";
	$resultledger=mysqli_query($connect,$insrtledger) or die(mysqli_error($connect));
// **********************END LEDGER DETAIL TABLE INSERT***************************
}


// end check closing stock
}



// end for loop
}

// ****************POST BUTTON**************************

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 !";
}


 ?>