<?php
session_start();
if(!file_exists("db.php")){
	$_SESSION["bootstrapAdmin"]=true;
	$_SESSION["dbSetup"]=true;
	header("Location: dbSetup.php");
	exit;
} else {
	require("db.php");
}
require_once("base.php");
require("db.php");
$stmt=$pdo->prepare("SELECT * FROM users LIMIT 1");
$stmt->execute([]);

if(isset($_SESSION["userId"])){ header("Location: ./"); exit; }
if($stmt->rowCount()==0){
	$_SESSION["bootstrapAdmin"] = true;
	//print("ERROR. No users found in db. <a href=\"/storage/people/add.php\">Enter setup</a> and create a user.");
    header("Location: /storage/people/add.php");
    exit;
}
else {
    $error = "";
    if($_SERVER["REQUEST_METHOD"]==="POST"){
        // require_once("db.php");
		$username = htmlspecialchars(trim($_POST["name"]));
		$password = htmlspecialchars(trim($_POST["pass"]));
		$stmt=$pdo->prepare("SELECT id,password,displayName,person FROM users WHERE username = ?");
		$stmt->execute([$username]);
		$result=$stmt->fetch();
		if($result){
			if(password_verify($password, $result["password"])){
				$_SESSION["userId"]=$result["id"];
				$_SESSION["userName"]=$username;
				$_SESSION["userDisplayName"]=$result["displayName"];
				$_SESSION["personId"]=$result["person"];
				header("Location: ./");
				exit();
			}
		}
        $error = "Invaild username or password.";
		http_response_code(401);
    }
head("Logowanie");
?>
<main class="d-flex nowrap align-items-center py-4" style="justify-content: center" data-bs-theme="dark">
<form method="POST" style="padding-bottom: 50px">
<!-- <i class="bi bi-database" style="font-size: 50px"></i> -->
    <h1 class="h3 mb-3 fw-normal">Please sign in</h1>
    <div class="form-floating"> <input type="text" class="form-control" id="floatingInput" name="name" placeholder="Username">
        <label for="floatingInput">Username</label>
    </div>
    <div class="form-floating">
        <input type="password" class="form-control" id="floatingPassword" name="pass" placeholder="Password">
        <label for="floatingPassword">Password</label>
    </div>
    <div class="form-check text-start my-3">
        <a style="color: red"><?= $error ?></a>
        <!-- <input class="form-check-input" type="checkbox" value="remember-me" id="checkDefault">
        <label class="form-check-label" for="checkDefault">Remember me</label> -->
    </div>
    <button class="btn btn-primary w-100 py-2" type="submit">Sign in</button>
</form>
<?php
footer();
}
?>
