<?php
session_name
('NIMAX');
session_start();
require_once 
"db_credentials.php";

// If already logged in, redirect immediately
if (isset($_SESSION["user_id"])) {
    
header("Location: entries.php");
    exit;
}

// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PW, DB_NAME);
if (!
$dbc) {
    die(
"Connection failed: " . mysqli_connect_error());
}

$message = "";

if (
$_SERVER["REQUEST_METHOD"] === "POST") {
    
// Grab and sanitize inputs
    
$username = trim($_POST["username"]);
    
$password = $_POST["password"];

    
// Prepare and execute statement to fetch the stored hash
    
$stmt = mysqli_prepare($dbc, "SELECT idUser, tdUsername, tdPassword FROM NIMAX_Users WHERE tdUsername = ? LIMIT 1");
    
mysqli_stmt_bind_param($stmt, 's', $username);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_store_result($stmt);

    if (
mysqli_stmt_num_rows($stmt) === 1) {
        
mysqli_stmt_bind_result($stmt, $idUser, $dbUsername, $dbHash);
        
mysqli_stmt_fetch($stmt);

        
// Verify the password against the stored hash
        
if (password_verify($password, $dbHash)) {
            
// Password is correct—set up the session
            
$_SESSION["user_id"]  = $idUser;
            
$_SESSION["username"] = $dbUsername;

            
header("Location: entries.php");
            exit;
        }
    }

    
// If we reach here, login failed
    
$message = "Invalid username or password.";
    
mysqli_stmt_close($stmt);
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link rel="stylesheet" href="../styles/login.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
   <div class="login-container">
       <h1>Login</h1>
       <?php if (!empty($message)): ?>
           <p class="error"><?= htmlspecialchars($message) ?></p>
       <?php endif; ?>
       <form method="post" action="login.php">
           <label for="username">Username:</label>
           <input type="text" name="username" id="username" required>
           <br>
           <label for="password">Password:</label>
           <input type="password" name="password" id="password" required>
           <br>
           <input type="submit" value="Login">
       </form>
   </div>
</body>
</html>