<?php
session_start();
if(isset($_SESSION["userId"])){
	header("Location: ./");
} else {
	if($_SERVER["REQUEST_METHOD"]==="POST"){
		require_once("db.php");
		$username = htmlspecialchars(trim($_POST["name"]));
		$password = htmlspecialchars(trim($_POST["pass"]));
		$stmt=$conn->prepare("SELECT id,password,displayName FROM users WHERE username = ?");
		$stmt->bind_param("s",$username);
		$stmt->execute();
		$result=$stmt->get_result();
		if($row=$result->fetch_assoc()){
			if($row["password"]==$password){
				$_SESSION["userId"]=$row["id"];
				$_SESSION["userName"]=$username;
				$_SESSION["userDisplayName"]=$row["displayName"];
				header("Location: ./");
				exit();
			}
		}
		http_response_code(401);
	} else {
?>
	<!DOCTYPE html>
	<html lang="en">
		<head>
			<meta charset="UTF-8">
		</head>
		<body>
			<form method="POST">
				<input type="text" name="name" placeholder="Username">
				<input type="password" name="pass" placeholder="Password">
				<input type="submit">
			</form>
		</body>
	</html>
<?php
	}
}
?>
