<?php include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/_global/dir_root.php'); ?>
<?php include_once($_SERVER['DOCUMENT_ROOT'].'/_ps2020/config/cfg_loggedUser.php'); ?>
<?php include($_SERVER['DOCUMENT_ROOT'] ."/_ps2020/config/connect.php"); ?>


<?php
	$msg = '';

	if(isset($_SESSION['email']) || isset($_SESSION['username'])){

	        $email = $_SESSION['email'];
	        $username = $_SESSION['user'];
	        //Before anything we need to check wether the user account has already been acitvated or not
	        $sql = "SELECT * FROM user_account WHERE email = '$email' OR username = '$username'";
	        $result = $conn->query($sql);
	        $verifyCode = "";
	        if($result){
	            if($result->num_rows == 1){
	                //the while loop will only run once
	                while($row = $result->fetch_assoc()){
	                    $account_status = $row['active'];
	                    $verifyCode = $row['verifyCode'];
	                    if($account_status == 1){
	                        header('location: dashboard.php');
	                    }
	                }
	            }
	        }
	    //We check if user has submitted a request
	    if($_SERVER["REQUEST_METHOD"] == "POST"){

	        //First we check for user email update request
	        if(isset($_POST['update'])){

	            $newEmail = mysqli_real_escape_string($conn, $_POST['email']);
	            $oldEmail = $_SESSION['email'];
	            //Now we check if the new email and old email is the same
	            if(!filter_var($newEmail, FILTER_VALIDATE_EMAIL)){
	                $msg = "Invalid Email!!";
	            }else if($newEmail == ""){
	                //Do nothing
	                $msg = "Email cannot be empty";
	            }else if($newEmail == $oldEmail){
	                //That means user hasn't changed his/her email
	                $msg = 'Please enter new email for verify-code. ';
	            }else{
	                //This would mean that user is trying to update his current email with a new email
	                //SO we update his records with new email
	                $username = $_SESSION['username'];
	                $sql = "UPDATE user_account SET email= '$newEmail' WHERE username = '$username'";
	                $result = $conn->query($sql);
	                if($result){
	                    $msg = "You email has been Updated!";
	                    //we also update the email of session variable to a new one
	                    $_SESSION['email'] = $newEmail;
	                }else{
	                    $msg = "Error updating record: " . $conn->error;
	                }
	                //Now after updating the email we email the verify code again
	                //Send it to his new email
	                $to = $newEmail;
	                $subject = "Account-Verification Code For GEESE";

	                $message = "<b>Welcome to GEESE.</b>";
	                $message .= "<h1>" . $username . "we would like to thank you for joining GEESE</h1>";
	                $message .= "<p>Your Verfication Code is: " . $verifyCode . "</p>";

	                $header = "From:teamgeese1@gmail.com \r\n";
	                $header .= "Cc:teamgeese1@gmail.com \r\n";
	                $header .= "MIME-Version: 1.0\r\n";
	                $header .= "Content-type: text/html\r\n";
	                //This is to send the verify code to the user
	                $retval = mail ($to,$subject,$message,$header);

	                if( $retval == true ) {
	                $msg = $msg . "The code has been emailed to you";
	                }else {
	                $msg = $msg . "Email couldn't be sent";
	                }   
	            }

	        }

	        if(isset($_POST['verify'])){
	            $verify_code = $_POST['verifyCode'];
	            
	            //Now we check wether the code entered is the correct one
	            if($verifyCode == $verify_code){
	                //That means user email is correct and so we set active to 1
	                $email = $_SESSION['email'];
	                $sql = "UPDATE user_account SET active = '1' WHERE email = '$email'";
	                $result = $conn->query($sql);
	                if($result){
	                    //so now the verify code has been verified
	                    $_SESSION['active'] = 1;
	                    header("location: dashboard.php");
	                }else{
	                    $msg = "An error has occured" . $conn->error;
	                }

	            }else{
	                $msg = "The verify code entered is incorrect";
	            }

	        }

	    }
	    
	}else{
	        // header('location:index.php');
	    }

?>


<!DOCTYPE HTML>
<!--
	Hielo by TEMPLATED
	templated.co @templatedco
	Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
-->
<html>
	<head>
		<title>Hielo by TEMPLATED</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />

		<?php include_once(dir_rootPHP.'_global/icon.php'); ?>


		<!-- libs -->
			<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
			<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/fontAwesome/css/font-awesome.min.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/animate.css" /> -->

			<!-- Font Awesome -->
		    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
		    <!-- Google Fonts -->
		    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
		    <!-- Bootstrap core CSS -->
		    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
		    <!-- Material Design Bootstrap -->
		    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">

			<!-- animation -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_bounce.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_fade.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_flip.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_other.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_rotate.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_slide.css" /> -->
				<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>libs/Animate/animate_zoom.css" /> -->

		<!-- css -->
			<link rel="stylesheet" href="<?php echo dir_root; ?>css/template-hielo/main.css" />

		<!-- css (custom) -->
			<link rel="stylesheet" href="<?php echo dir_root; ?>css/henry_style.css" />
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/tanuj_style.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/karl_style.css" /> -->
			<!-- <link rel="stylesheet" href="<?php echo dir_root; ?>css/harsh_style.css" /> -->

			<style>
				.ctm-outer{
		        	background-color: white;
		        	box-shadow: 0 0 15px #dfdfdf;
		        }
		    </style>

	</head>
	<!-- <body class="subpage"> -->
	<body>

		<!-- Header | Nav -->
			<?php include_once(dir_rootPHP.'_global/navbar/navbar.php'); ?>
			<?php include_once(dir_rootPHP.'_global/navbar/navbar-mobile.php'); ?>

		
		<!-- Page-Title -->
			<section id="One" class="wrapper style3" style="padding-top: 9rem;">
				<div class="inner">
					<header class="align-center">
						<p>Greenscape Environmental Experience & Learning Survey Experiments</p>
						<h2>Email Verification</h2>
					</header>
				</div>
			</section>

		<!-- Content -->
			<section id="two" class="wrapper style2" style="padding: 8% 0 6% 0;">
				<div class="inner">

					<div class="row d-flex justify-content-center">

				        <!--Grid column-->
				        <div class="col-md-6">

				            <!-- Default form login -->
				            <form class="text-center border border-light p-5 ctm-outer" name="verifyaccount" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
				                  method="POST">

				                <p class="h4 mb-4">Verify Account</p>

				                <?php 

				                if($msg != ''){?>
				                   <div class='alert alert-warning' role='alert' ><?php echo $msg; ?></div>";
				                <?php
				                }

				                ?>
				                <!-- Email -->
				                <br/>
				                
				                <input type="text" name="email" id="email" class="form-control mb-4"
				                    placeholder="E-mail" value="<?php echo (isset($_SESSION['email']))?$_SESSION['email']:'Email not Found!';?>">
				               
				                <!-- <div class="alert alert-danger" role="alert" id="p-error">Verification </div> -->
				                <input type="text" id="verifyCode" name="verifyCode"
				                    class="form-control mb-4" placeholder="Verification Code">

				                <!-- Sign in button -->
				                <input class="btn btn-info btn-block my-4" type="submit"  name="update" value="Update-Email"/>

				                <input class="btn btn-info btn-block my-4" type="submit"  name="verify" value="Submit-Code">

				            </form>
				            <!-- Default form login -->

				        </div>
				        <!--Grid column-->

				    </div>
				    <!--Grid row-->

				</div>
			</section>
			

		<!-- Footer -->
			<?php include_once(dir_rootPHP.'_global/footer/footer.php'); ?>

		<!-- Scripts -->
			<script src="<?php echo dir_root; ?>js/template-hielo/jquery.min.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/jquery.scrollex.min.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/skel.min.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/util.js"></script>
			<script src="<?php echo dir_root; ?>js/template-hielo/main.js"></script>

		<!--The jquery will be used to check if email exists!!-->
		    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
		    <!-- Bootstrap tooltips -->
		    <script type="text/javascript"
		        src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
		    <!-- Bootstrap core JavaScript -->
		    <script type="text/javascript"
		        src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>
		    <!-- MDB core JavaScript -->
		    <script type="text/javascript"
		        src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js"></script>


		<!-- Scripts (custom) -->
			<script></script>

	</body>
</html>