<?php
include '../db/db.php';
session_start();
$log= htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
if (empty($log)) {
	 
  $redirectUrl = "../index.php";
  echo "<script type=\"text/javascript\">";
  echo "window.location.href = '$redirectUrl'";
  echo "</script>";
	 
}else{

  $sqlu="SELECT * FROM details_of_users WHERE user='$log' and val='1'";
  $resultu=mysqli_query($conn, $sqlu);
  $countu=mysqli_num_rows($resultu);
  
	if($countu==1){
	
	  $sqlc="SELECT * FROM details_of_users where user='$log'";
	  $resultc=mysqli_query($conn, $sqlc);
	  while ($rowc = mysqli_fetch_array($resultc)){
	  $name=$rowc['id'];
	  }
		
		$sup_id = htmlspecialchars(trim($_POST['sup_id']), ENT_QUOTES, 'UTF-8');
		$inv_no = htmlspecialchars(trim($_POST['inv_no']), ENT_QUOTES, 'UTF-8');
		$item = htmlspecialchars(trim($_POST['item']), ENT_QUOTES, 'UTF-8');
		$qty = htmlspecialchars(trim($_POST['quantity']), ENT_QUOTES, 'UTF-8');
		
		$row_bal = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(`dr_qty`) - SUM(`cr_qty`) AS bal FROM `stock` WHERE stock_card='$item'"));
		$bal = $row_bal['bal'];
		
		if($bal < $qty) {
			echo "<script>alert('No Available Balance')</script>";
			$redirectUrl = "../add_supReturn_details.php?inv_no=$inv_no&&sup=$sup_id";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";
			echo "</script>";		
		
		} else {
	
			mysqli_query($conn, "INSERT INTO srn_tkn_stock SET inv_no='$inv_no',sup_id='$sup_id',item='$item',qty='$qty'");

			$redirectUrl = "../add_supReturn_details.php?inv_no=$inv_no&&sup=$sup_id";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";
			echo "</script>"; 
		}

	
	} else{
	  $redirectUrl = "../index.php";
	  echo "<script type=\"text/javascript\">";
	  echo "window.location.href = '$redirectUrl'";
	  echo "</script>";
	
	}
}

?>