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

// Initialize the session
session_start();
// User account not yet verified => set loggedin to false
$_SESSION["loggedin"] == false;


if(empty($passwordreset_err)) {
		// Prepare a select statement
		$sql = "SELECT userId, userStatus, userLastname, userFirstname FROM User WHERE userStatus = 99 AND userToken =  ? ";
		if($stmt = mysqli_prepare($link, $sql)){

		// Bind variables to the prepared statement as parameters
    		mysqli_stmt_bind_param($stmt, 's', $param_token);
   
  		// Set parameters
    		$param_token = trim($_GET['token']);

		// echo $sql .$param_token; exit;
 
		// Attempt to execute the prepared statement
    		if(mysqli_stmt_execute($stmt)){
			/* store result */
			mysqli_stmt_store_result($stmt);
			// Check if token  exists.
			$a = mysqli_stmt_num_rows($stmt);  
		// 	echo $a; exit;
			if($a != 1){
    				$passwordreset_err = "Passwortänderung nicht möglich (Tokenfehler).<br>" .$a ." " .$param_token ." " .$status;
	       	          } else {
				mysqli_stmt_bind_result($stmt, $userid, $status, $lastname, $firstname);
                    		if(mysqli_stmt_fetch($stmt)) {
					$passwordreset_err = '';			    			
	    			}
			  }
    		     } else {
					echo "Oops! Da ist etwas schief gegangen. Bitte versuchen Sie es später noch einmal.";
		  }
                        // Close statement
		    		mysqli_stmt_close($stmt);
		}
	
		// Validate password                
    		if(empty(trim($_POST["password"]))){
        		$password_err = "Bitte Passwort eingeben.";
    		} else {
        		$password_err = '';
        		$password = trim($_POST["password"]);
    		}

    		if (empty($password_err)) {
        		$pattern = '~^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_+\-=\[\]{}|;\':\\",./<>?])(?=.*\S).{8,}$~u';
        		if  (!preg_match($pattern, trim($_POST["password"]))) {
            			$password_err = "Passwort muss mindestens acht Zeichen lang sein, wenigstens aus einem Gross- und Kleinbuchstaben, sowie Sonderzeichen bestehen.";
        		}
    		}

    		// Validate confirm password
    		if(empty(trim($_POST["confirm_password"]))){
        		$confirm_password_err = "Bitte Passwort bestätigen.";
    		} else {
        		$confirm_password = trim($_POST["confirm_password"]);
        		if(empty($password_err) && strcmp($password, $confirm_password) !=0) {
            			$confirm_password_err = "Passworte stimmen nicht überein.";
        		} else {
            			$confirm_password = trim($_POST["confirm_password"]);
            			$confirm_password_err = '';
        		}
    		}

		if(empty($passwordreset_err) &&  empty($password_err) && empty($confirm_password_err) ){

			$timestamp = time(); 
			$timestamp = date("Y-m-d H:i:s", $timestamp);
			$passwordEncrypted = password_hash($password, PASSWORD_DEFAULT);   
			$userToken = ''; ; 
			$query  = "UPDATE User SET userPassword = '" .$passwordEncrypted ."', userLastActivity = '" .$timestamp ."', userToken = '', userStatus = 0  WHERE userId ="  .$userid ; 
			
		if (mysqli_query($link, $query)) {
			// store variables in Session
			$_SESSION["loggedin"] 	= false;
		    	$_SESSION["title"] 	= $title;
		    	$_SESSION["firstname"]  = $firstname;
		    	$_SESSION["lastname"]   = $lastname;
		    	$_SESSION["email"]      = $email;
			$_SESSION["userToken"]   = $userToken; 
			header("location: confirmpasswordreset.php");
			exit;
		   } else {
  			die ("Error: " . $query . "-" . mysqli_error($link));
		}
                header("location: confirmpasswordreset.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>Neues Passwort vergeben</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;
        }

        .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="passwordresetScreen" class="wrapper pb-3 shadow p-3 ms-5 bg-light rounded align-items-center bg-box">
    	    <h4>Neues Passwort vergeben</h4>

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

    	    <div class="row">Bitte ausfüllen, um sich ein neues Passwort zu vergeben.</div>
	    <!-- <div class="row">Konto bereits vorhanden?&nbsp; <a href="login.php" style="color:#14416b;">Hier anmelden</a>.</div> -->
	    <div class="row"></div>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ."?token=" .$param_token; ?>" method="post" novalidate>
	   	<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">
                        <label for="confirm_password" class="form-label">Passwort bestätigen</label>
                        <div class="input-group">
                                <input type="password" name="confirm_password" id="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">
                                <button class="btn btn-outline-secondary togglePassword" type="button" id="toggleConfirmPassword">
                                        <i class="bi bi-eye" id="eyeConfirmIcon"></i>
                                </button>
                        <div class="invalid-feedback"><?php echo $confirm_password_err; ?></div>
                </div>

            	<div class="mb-3">
              	    <input type="submit" class="btn btn-success" value="Passwort zurücksetzen">
            	</div>
            </form>
    	</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>

<script>
        const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
        const confirm_password = document.getElementById('confirm_password');
        const eyeConfirmIcon = document.getElementById('eyeConfirmIcon');

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

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

 
</body>
</html>
