<?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'];
	  }
		
		$supplier = htmlspecialchars(trim($_POST['sup']), ENT_QUOTES, 'UTF-8');
		$order_no = htmlspecialchars(trim($_POST['invoice_no']), ENT_QUOTES, 'UTF-8');
		$date = htmlspecialchars(trim($_POST['date']), ENT_QUOTES, 'UTF-8');
		
		$query = mysqli_query($conn, "SELECT order_no FROM grn_tkn_order WHERE order_no='$order_no'");
		
		if (mysqli_num_rows($query)!= 0){
			echo "<script>alert('Invoice No Already Exist!')</script>";
			$redirectUrl = "../add_GRN.php";
			echo "<script type=\"text/javascript\">";
			echo "window.location.href = '$redirectUrl'";
			echo "</script>";  	 

		} else {

			$sql6 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT purchase FROM invoice_no_tbl"));
			$purchase2 = $sql6['purchase'];
			$purchase = $purchase2 + 1;
			
			$purchase = htmlspecialchars(trim($purchase), ENT_QUOTES, 'UTF-8');
			$inv_no = $purchase;

			mysqli_query($conn, "UPDATE invoice_no_tbl SET purchase='$purchase'");			
			mysqli_query($conn, "INSERT INTO grn_tkn_order SET order_no='$order_no',sup_id='$supplier',date='$date',inv_no='$inv_no'");

			$redirectUrl = "../add_GRN_details.php?inv_no=$inv_no&&sup=$supplier";
			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>";
	
	}
}

?>