<?php

// Include config file
require_once "config.php";
$config = parse_ini_file("config.ini", true) ;
$baseURL = $config['base']['URL'];

// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
//     print_r($_SESSION); 
    header("location: " .$baseURL ."/indexBT5.php");
    exit;
}
 
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Bitte Benutzernamen eingeben.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Bitte Passwort eingeben.";
    } else{
        $password = trim($_POST["password"]);
    }
/*
describe User
+------------------+--------------+------+-----+-------------------+-------------------+
| Field            | Type         | Null | Key | Default           | Extra             |
+------------------+--------------+------+-----+-------------------+-------------------+
| userId           | int unsigned | NO   | PRI | NULL              | auto_increment    |
| userName         | varchar(32)  | NO   |     | NULL              |                   |
| userPassword     | varchar(255) | NO   |     | NULL              |                   |
| userTitle        | varchar(32)  | YES  |     | NULL              |                   |
| userLastName     | varchar(255) | NO   | MUL | NULL              |                   |
| userFirstName    | varchar(255) | NO   |     | NULL              |                   |
| userEmail        | varchar(255) | NO   |     | NULL              |                   |
| userStatus  	   | smallint	  | YES  |     |                   |                   |
| userLastActivity | timestamp    | NO   |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+------------------+--------------+------+-----+-------------------+-------------------+
*/
     
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT userId, userName, userPassword, userTitle, userFirstName, userLastName, userEmail, userStatus FROM User WHERE userName = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            
            // Set parameters
            $param_username = $username;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);
                
                // Check if username exists, if yes then verify password
                if($num=mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password, $title, $firstname, $lastname, $email, $status);
                    if(mysqli_stmt_fetch($stmt)){
			
                        if(password_verify($password, $hashed_password)){
			    if ($status != 0)  {
			    // Account is not yert confirmed
                            	$login_err = "Benutzerkonto ist noch nicht freigeschaltet. Bitte schalten Sie den Zugang frei. Klicken Sie dazu auf den Link in der von Ihnen erhaltenen E-Mail (ggf. Spamordner prüfen)";
			      } else {   
				// Password is correct, so start a new session
                              	session_start();
                            	// Store data in session variables
                            	$_SESSION["loggedin"] 	= true;
                            	$_SESSION["id"] 		= $id;
                            	$_SESSION["username"] 	= $username;                            
			    	$_SESSION["title"] 		= $title;
			    	$_SESSION["firstname"]      = $firstname;
			    	$_SESSION["lastname"]       = $lastname;
			    	$_SESSION["email"]          = $email;
			    	$_SESSION["status"]   	= $status; 
				 print_r($_SESSION); 
                            	// Redirect user to welcome page
                            	header("location: ../indexBT5.php");
			      }
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Benutzername oder Passwort nicht korrekt.";
                        }
                    }
                } else {
                    // Username doesn't exist, display a generic error message
		    $login_err = "Benutzername existiert nicht. Bitte registrieren Sie sich.";
                }
            } else{
                echo "Oops! Da ging etwas schief. Bitte versuchen Sie es später noch einmal.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css">
    <link href="../css/bibb.css" media="all" rel="stylesheet" type="text/css">

    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 360px; padding: 20px; }
    </style>

    <script type="javascript">
// 	a = document.getElementById("loginPlaceholder") ;
	document.onload = hideElement("loginPlaceholder");  
    </script>

</head>
<body>

    <?php include "../templates/headerLogout.php"; ?>

    <div id="loginScreen" class="wrapper pb-3 shadow p-3 ml-5 bg-body rounded align-items-center">
        <h2>Login</h2>
        <p>Bitte Anmelde-Daten eingeben.</p>

        <?php 
        if(!empty($login_err)){
            echo '<div class="alert alert-danger">' . $login_err . '</div>';
        }        
        ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group">
                <label>Benutzername</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>    
            <div class="form-group">
                <label>Passwort</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Anmelden">
            </div>
	     <p>Kein Konto vorhanden? <a href="register.php">Bitte registrieren</a>.</p>
	     <p>Passwort vergessen? <a href="forgotten.php">Passwort vergessen</a>.</p>
        </form>
    </div>
</body>
</html>
