<?php

// Debug Infos ausgeben
//error_reporting(E_ALL);
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);

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


// Initialize the session
session_start();
//print_r($_SESSION);

isset ($_SESSION['loginAttempt']) && $_SESSION['loginAttempt'] == true ? $loginAttempt = true : $loginAttempt = false; 

// Define variables and initialize with empty values
$email = $password = "";
//$email_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    if(isset($_POST["email"]))  {
    	// Check if email is empty
    	if(empty(trim($_POST["email"]))){
	    if ($loginAttempt === true) 
        	$email_err = "Bitte E-Mail-Adresse eingeben.";
    	} else {
        	$email = trim($_POST["email"]);
    	}
    }
    
    // Check if password is empty
    if (isset ($_POST["password"]))  {
        if(empty(trim($_POST["password"]))){
	    if ($loginAttempt === true)
        	$password_err = "Bitte Passwort eingeben.";
	
        } else {
            $password = trim($_POST["password"]);
	    $_SESSION['loginAttempt'] = true;
	    $loginAttempt = true;
	}
    }


// print_r($_SESSION); exit; 

     
    // Validate credentials
    if(empty($email_err) && empty($password_err && $loginAttempt == true)){
        // Prepare a select statement
        $sql = "SELECT userId, userPassword, userTitle, userFirstName, userLastName, userEmail, userStatus FROM User WHERE userEmail = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_email);
            
            // Set parameters
            $param_email = $email;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);
                
                // Check if email exists, if yes then verify password
                if($num=mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $hashed_password, $title, $firstname, $lastname, $email, $status);
                    if(mysqli_stmt_fetch($stmt)){
			
                        if(password_verify($password, $hashed_password)){
			   // print_r($_SESSION); exit;  
			    if ($status != 0)  {
			    // Account is not yet 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). (Code: " .$status .")";
			      } else {   
				// Password is correct, so start a new session
                              	session_start();
                            	// Store data in session variables
                            	$_SESSION["loggedin"] 	= true;
                            	$_SESSION["id"]		= $id;
			    	$_SESSION["title"]	= $title;
			    	$_SESSION["firstname"]  = $firstname;
			    	$_SESSION["lastname"]   = $lastname;
			    	$_SESSION["email"]      = $email;
			    	$_SESSION["status"]   	= $status; 
				$_SESSION["loginAttempt"] = false; 
				mysqli_stmt_close($stmt);

				// Timestamp "userLastActivity" aktualisieren
				$timestamp = date("Y-m-d H:i:s");
				$sql = "UPDATE User SET userLastActivity = ? WHERE userId = ?";

				if($stmt = mysqli_prepare($link, $sql)){
				    mysqli_stmt_bind_param($stmt, "si", $timestamp, $id);
				    if(!mysqli_stmt_execute($stmt)){
        				die("SQL Fehler: " . mysqli_stmt_error($stmt));
    				    }
				    mysqli_stmt_close($stmt);
				}

                            	// Redirect user to welcome page
				$_SESSION['loginAttempt'] =  $loginAttempt = false;
				//echo "location: " .$baseURL ."publizieren/indexBT5.php"; exit; 
				header("location: " .$baseURL ."/indexBT5.php");
			      }
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "E-Mail-Adresse oder Passwort nicht korrekt.";
                        }
                    }
		    $_SESSION['loginAttempt'] =  $loginAttempt = true; 
                } else {
                    // Email doesn't exist, display a generic error message
		    if ($_SESSION['loginAttempt'] === true) {
		    	$login_err = "E-Mail-Adresse existiert nicht. Bitte registrieren Sie sich.";
		    }
                }
		$_SESSION['loginAttempt'] == true;
            } 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">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login</title>
    
    <!-- Bootstrap 5 CSS && Bootstrap Icons -->
    <?php include "include/includeJSandCSS.php" ?> 

    <!-- Custom CSS -->
    <link href="css/bibb.css" media="all" rel="stylesheet" type="text/css">

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

    <style>
        html, body {
            height: 100%;
        }

        .stickywrapper {
            min-height: 60vh;
            display: flex;
            flex-direction: column;
        }

        .content {
            flex: 1;
        }

	.togglePassword {
            background-color: white;
            border-top-right-radius: 0.375rem !important;
            border-bottom-right-radius: 0.375rem !important;
        }

    </style>
</head>

<body>

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

<div class="stickywrapper">
    <!-- Hauptinhalt der Seite -->
    <div class="content">
	<div class="container my-5">
    	    <div id="loginScreen" class="wrapper pb-3 shadow p-3 ms-5 bg-light bg-box rounded">
        	<h4>Login</h4>
        	    <p>Bitte Anmeldedaten zum Publikationskonto eingeben.</p>
		    <p>&nbsp;</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" novalidate>
            		<div class="mb-3">
                  	    <label for="email" class="form-label">E-Mail-Adresse</label>
                	    <input type="text" name="email" id="email" class="form-control <?php echo (!empty($email_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $email; ?>">
                	    <div class="invalid-feedback"><?php echo $email_err; ?></div>
            		</div>    
			<div class="mb-3">
	                    <label for="password" class="form-label">Passwort</label>
        	            <div class="input-group">
                	            <input type="password" name="password" id="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">
                        	    <button class="btn btn-outline-secondary togglePassword" type="button" id="togglePassword">
                                	    <i class="bi bi-eye" id="eyeIcon"></i>
                            	    </button>
                            	    <div class="invalid-feedback"><?php echo $password_err; ?></div>
                    	     </div>
                        </div>

            		<div class="mb-3">
                		<input type="submit" class="btn btn-success" value="Anmelden">
            		</div>
	     		<p><a href="forgotten.php">Passwort zurücksetzen</a>.</p>
			<p><a href="register.php">Neu registrieren</a>.</p>
        	    </form>
    		    </div>
		</div>
	    </div>
	</div>
	
<?php include "templates/stickyfooter.php" ?>

<script>
        const togglePassword = document.getElementById('togglePassword');
        const password = document.getElementById('password');
        const eyeIcon = document.getElementById('eyeIcon');

        togglePassword.addEventListener('click', function() {
            // Typ des Passwortfeldes umschalten
            const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
            password.setAttribute('type', type);

            // Icon umschalten
            if (type === 'password') {
                eyeIcon.classList.remove('bi-eye-slash');
                eyeIcon.classList.add('bi-eye');
            } else {
                eyeIcon.classList.remove('bi-eye');
                eyeIcon.classList.add('bi-eye-slash');
            }
        });
</script>


</body>
</html>
