<?php

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


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

if(empty($confirmation_err) ){
        // Prepare a select statement
        $sql = "SELECT userStatus, userLastname, userFirstname FROM User WHERE 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 = $_GET['token'];

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if token  exists.
		// echo mysqli_stmt_num_rows($stmt) ; exit; 
                if($num=mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $status, $lastname, $firstname);
		    // echo $status ." - " .$lastname ." - "  .$firstname ."\n"; exit; 
                    if(mysqli_stmt_fetch($stmt)){
                        if($status == 0){
                            // Account is already confirmed
                                $confirmation_err = "Benutzerkonto ist bereits freigeschaltet.";
                              } else {
                                // token available in database and status != 0 
				// update status and set token to ''; 
				$sql = "UPDATE User set userStatus = 0, userToken = '' where userToken = ?";
				if($stmt = mysqli_prepare($link, $sql)){
			            	// Bind variables to the prepared statement as parameters
            			    	mysqli_stmt_bind_param($stmt, "s", $param_token);
            				// Attempt to execute the prepared statement
            				if(! mysqli_stmt_execute($stmt)){
						$confirmation_err= "<div class='row'>Oops! Da ging etwas schief. Bitte versuchen Sie es später noch einmal.</div>";
					}
					// Close statement
					sendmailToRepositoryTeam($lastname, $firstname); 
				        mysqli_stmt_close($stmt);
        			}
			   }
		    }
		  } else {
			 $confirmation_err = '<div class="pb-2">Es wurde kein Datensatz für eine Freischaltung gefunden.</div><div>Das kann an der Verwendung einer alten Freischaltungs-Email liegen, bei der der verwendete Token bereits verwendet wurde oder aber an einem Fehler auf unserer Seite.</div><div class="pb-2">Bei Fragen wenden Sie sich bitte über unser <span style="font-weight:bold"><a href"=https://www.bibb.de/dienst/kontakt/de/kontaktformular.php?maid=4841" target="_blank" rel="noopener noreferrer" >Kontaktformular</a></span> an das Team des VET Repository.</div>'; 
		  }
	    }
	}
}

function sendmailToRepositoryTeam($lastname, $firstname) {
    $replyTo = "noreply@bibb-service.de";
    $to      = "repository@bibb.de";

    $subject = '=?UTF-8?B?' . base64_encode('Registrierung im VET Repository') . '?=';

    $message = "BenutzerIn $firstname $lastname hat ihre/ seine Mailadresse nun bestätigt.";

    $headers  = "From: $to\r\n";
    $headers .= "Reply-To: $replyTo\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";

    mail($to, $subject, $message, $headers);
}

?>
 
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Konto Freischaltung</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="verifcationScreen" class="wrapperconfirmation pb-3 shadow p-3 ms-5 bg-light bg-box rounded align-items-center">
            <h4>Freischaltung Ihres Publikationskontos im VET Repository</h4>
	    <?php 

	    $_SESSION["loggedin"] 	= true;
    	    $_SESSION["firstname"]  = $firstname;
    	    $_SESSION["lastname"]   = $lastname;

	    if ($confirmation_err == '')  {
		echo '
	            <div class="row">
		    	Hallo '; 
			echo $firstname ." " .$lastname ."," ;
			echo '
		    </div>
		    <div class="row">
			danke für die Bestätigung Ihrer E-Mail-Adresse. Sie können sich zum Publizieren mit Ihren zuvor vergebenen Logindaten anmelden.
		    </div>
		    <div class="row"></div>';
       			echo 
			    '<form action="'; 
			        echo $baseURL ."/login.php";
				echo	'" method="post">
            			<div class="mb-3">
                			<input type="submit" class="btn btn-success" value="Zum Login">
            			</div>
				<p><a href="'; 
				echo $baseURL ."/forgotten.php" ;
				echo '">Passwort vergessen</a>.</p>
        		    </form> '; 
			} else {
			    echo '
				<div class="row"> ';
				echo $confirmation_err; 
			    echo '	</div>' ; 
			}
	    ?>
    	    </div>
	</div>
    </div>
</div>

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

</body>
</html>
