<?php
// Include config file
$config = parse_ini_file("config.ini", true) ;
$sessionSavePath = $config['session']['sessionPath'];
$baseURL = $config['base']['URL']; 

// Initialize the session
session_start();

require_once "sanitize.php";
include "config.php"; 

// Processing form data when form is submitted

if($_SERVER["REQUEST_METHOD"] == "POST"){

	// Validate user email
	
	if (empty(trim($_POST["email"])))  {
       		$email_err = "Bitte E-Mail-Adresse eingeben.";
  	   	} elseif (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['email'])){
           		$email_err = "E-Mail-Adresse enthält ungültige Zeichen";
              	} else {
           		$email = trim($_POST["email"]);
           		$email_err = ''; 
			// check, if email is registered
			// Prepare a select statement
                	$sql = "SELECT userId, userFirstname, userLastname FROM User WHERE userEmail = ?";
			//echo $sql; exit;
                	if($stmt = mysqli_prepare($link, $sql)){
                	// Bind variables to the prepared statement as parameters
                	mysqli_stmt_bind_param($stmt, "s", $email);
                	// Set parameters
                	$email = trim($_POST["email"]);
			//echo $email; exit;
                	// Attempt to execute the prepared statement
                	if(mysqli_stmt_execute($stmt)){
                	/* store result */
                    		mysqli_stmt_store_result($stmt);
				//echo mysqli_stmt_num_rows($stmt); exit;
                    		if(mysqli_stmt_num_rows($stmt) != 1){
                        		$email_err = 'E-Mail kann nicht versendet werden. Bitte wenden Sie sich an das VET Repository Team über unser <a href="https://www.bibb.de/dienst/kontakt/de/kontaktformular.php?maid=4841" target="_blank" rel="noopener noreferrer" >Kontaktformular</a>.';
                      		} else {
					// Bind result variables
        				mysqli_stmt_bind_result($stmt, $userId, $userfirstname, $userlastname);
					if(mysqli_stmt_fetch($stmt)){
                               			$email_err = '';
					}
                     		}
                   	    } else{
                   		echo "Oops! Da ist etwas schief gegangen. Bitte versuchen Sie es später noch einmal.";
                 	    }
                 		// Close statement
                 		mysqli_stmt_close($stmt);
              		}


	      		if(empty($email_err)){
		  		$timestamp = time(); 
		  		$timestamp = date("Y-m-d H:i:s", $timestamp);
	 	  		// set temporary password
		  		$passwordEncrypted = password_hash(bin2hex(random_bytes(16)), PASSWORD_DEFAULT);   
		  		$userToken = bin2hex(random_bytes(32)); 
		  		$query  = "UPDATE User SET userStatus = 99, userPassword = '" .$passwordEncrypted ."', userToken = '" .$userToken ."', userLastActivity = '" .$timestamp ."' WHERE userEmail = '" .$email ."'";

				if (mysqli_query($link, $query)) {
				// store variables in Session
					$_SESSION["loggedin"] 	= false;
		    			$_SESSION["title"] 	= '';
		    			$_SESSION["firstname"]  = $userfirstname;
		    			$_SESSION["lastname"]   = $userlastname;
		    			$_SESSION["email"]      = $email;
					$_SESSION["userToken"]   = $userToken; 
					header("location: sendpasswordforgottenmail.php");
					exit;
		   		    } else {
  					die ("Error: " . $query . "-" . mysqli_error($link));
				}
                		header("location: sendpasswordforgottenmail.php");
				exit;
			} 
    			// 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>Passwort vergessen</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">
    
    <style>
        html, body {
            height: 100%;
        }

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

        .content {
            flex: 1;
        }
    </style>
</head>

<body>
    
<?php include "templates/headerLogin.php"; ?>
<div class="stickywrapper">
    <!-- Hauptinhalt der Seite -->
        <div class="content">
            <div class="container my-5">
    		<div id="passwordforgottenScreen" class="wrapper pb-3 shadow p-3 ms-5 bg-light rounded align-items-center bg-box">
    		    <h4>Passwort vergessen</h4>
      		    <div class="row">Bitte ausfüllen, damit wir Ihr Passwort zurücksetzen können.</div>
        	    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" novalidate>
	   		<div class="mb-3 pt-33 pt-33 pt-3">
                	    <label for="email" class="form-label">E-Mail</label>
                	    <input type="email" 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">
              		    <input type="submit" class="btn btn-success" value="Passwort zurücksetzen">
            		</div>
        	    </form>
    		</div>    
	     </div>
	</div>
</div>

<?php include "templates/stickyfooter.php" ?>

</body>
</html>
