<?php
session_start();

// Check if the user is already logged in
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true && $_SESSION['username'] !== '') {
    // Redirect to the dashboard page
    header("Location: dashboard.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
	if(!isset($_POST['username'], $_POST['password']) || trim($_POST['username']) =='' || trim($_POST['password']) == '') {
		$login_message = "Missing username or password.";
	}
	else {
		// Get user submitted information
		$username = trim($_POST['username']);
		$password = trim($_POST['password']);

		// Connect to the database
		// $conn=mysqli_connect("localhost","root","","pwd_mgr");
		// // Check connection
		// if (mysqli_connect_errno())	{
		//   echo "Failed to connect to MySQL: " . mysqli_connect_error();
		//   exit();
		// }
		require_once __DIR__ . "/config.php";

		// Authentication with hashed passwords:
		// 1) Fetch the stored hash by username
		// 		SQL injection mitigation: use a prepared statement with bound parameters.
		// 		User input is treated strictly as data, not as part of the SQL syntax.
		// 2) Verify the submitted password with password_verify()
		$stmt = $conn->prepare("SELECT id, password FROM login_users WHERE username = ?");
		if ($stmt === false) {
			// Fail closed (do not leak details in production).
			die("Prepare failed.");
		}

		$stmt->bind_param("s", $username);
		$stmt->execute();

		$result = $stmt->get_result();  // Requires mysqlnd (usually enabled)
		unset($_POST['username']);
		unset($_POST['password']);

		if ($result && $result->num_rows === 1) {
			$row = $result->fetch_assoc();
			$stored_hash = $row["password"];

			// Verify password against the stored hash.
			if (password_verify($password, $stored_hash)) {
				// Regenerate session ID to prevent session fixation!
				//session_regenerate_id(true);

				// Successfully logged in
				$_SESSION['username'] = $username;
				$_SESSION['loggedin'] = true;

				$stmt->close();
				$conn->close();

				header("Location: dashboard.php");
				exit;
			} else {
				$login_message = "Invalid username or password";
			}
		} else {
			$login_message = "Invalid username or password";
		}

		$stmt->close();
		$conn->close();
	}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login Form</title>
</head>

<body>
    <h3>Password Manager</h3>
    <form method="POST" action="">
        <input type="text" name="username" placeholder="Username" required><br />
        <input type="password" name="password" placeholder="Password"><br />
        <button type="submit">Login</button>
    </form>
	<br />
    <?php if (!empty($login_message)) { echo "<font color=red>$login_message</font>"; } ?>
	<p/>
    <a href="register.php">Register new user</a>
	<p/>
	<a href="index.html">Home page</a>
</body>
</html>