<?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['user'])){

        $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' AND 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');
                    }
                }
            }
        }

        //Since here we have checked wether the account 
        //has alerady become active or not
        //This is if user accidently comes to this page 
        if($_SERVER["REQUEST_METHOD"] == "POST"){

            //Now we need to check wether the user is trying to update email or 
            //Else he is trying to verify the account

            if(isset($_POST["submitEmail"])){
                //so the user is trying to update the email
                $newEmail = mysqli_real_escape_string($conn, $_POST['email']);
                $oldEmail = $_SESSION["email"];

                if($newEmail == $oldEmail){
                    $msg = "New Email cannot be same as the old one";
                }else if(!filter_var($newEmail, FILTER_VALIDATE_EMAIL)){
                    $msg = "Invalid Email! Please enter a valid email!";
                }else{
                    //We fetch the user's username
                    $username = $_SESSION['user'];

                    //We need to make sure that user email is not already taken
                    $sql = "SELECT * FROM user_account WHERE email = '$newEmail'";
                    $result = $conn->query($sql);

                    if($result->num_rows > 0){
                        //this would mean that the email is already registered to another account
                        $msg = "Email is already registered to another account!! Try Again!!";
                    }else{
                        $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;
                        }

                    //So now we need to fetch the verifyCode for the user
                    $sql = "SELECT * FROM user_account WHERE username = '$username'";
                    $result = $conn->query($sql);
                    if ($result->num_rows > 0) {
                        // output data of each row
                        while($row = $result->fetch_assoc()) {
                            $verifyCode = $row["verifyCode"];
                        }
                    }
                    //Check if verifyCode is empty
                    if($verifyCode == ""){
                        echo "Verify Code not Found!";
                    }
                    //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["submitCode"])){

                //Now we need to check if the verify Code is correct or not
                $userCode = mysqli_real_escape_string($conn,$_POST["code"]);
                $username = $_SESSION["user"];
                $sql = "SELECT * FROM user_account WHERE username = '$username'";
                $result = $conn->query($sql);

                if($result->num_rows == 1){

                    while($row = $result->fetch_assoc()){
                        $verifyCode = $row["verifyCode"];
                        if($verifyCode == $userCode){
                            $msg = "Your usercode is valid";

                            //Now that the usercode is valid
                            //Now we change the active column of the user to 1
                            //$sql = "UPDATE user_account SET active = '1' WHERE username = '$username'";
                            $sql = "UPDATE user_account SET active = '1' WHERE username = '$username'";
                            if($conn->query($sql) === TRUE){
                                $msg = "Your account status has been updated!!";
                                $_SESSION['active'] = 1;
                                header('location: '.dir_root.'account/dashboard.php');
                            }else{
                                $msg = "Your account settings cannot be updated!!";
                            }

                        }else{
                            $msg = "The valid code entered is invalid!!";
                        }
                    }

                }else{
                    echo "Duplicate user accounts with same value";
                }

            }

        }
    }else{
        //That is go to the sign-up/login page
        // header("location: index.php");
    }
?>

<!DOCTYPE html>
<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>

                .hide{
                    display: none;
                }

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

    <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" id="verifyForm" name="verifyAccount" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">

                                <h3 class="h2 mb-4" id="form-header">Verify Account</h3>

                                <?php

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

                                ?>

                                <div class="alert alert-warning" role="alert" id="email-info">
                                    <h4 class="alert-heading">Your Login Email: <?php echo $_SESSION["email"];?></h4>
                                    <p>If this is not your valid email. Please select the update-email button to replace the current email
                                        and replace it with your valid email. Than press Update-Email Again
                                    </p>
                                    <hr>
                                    <p class="mb-0">Please check your spam just in case. In case you still not recieve an email.</p>
                                </div>

                                <div class="alert alert-success hide" role="alert" id="code-info">
                                    <h4 class="alert-heading">To Update Email</h4>
                                    <p>To update your email delete the current email in the input box and replace it with a new valid email for
                                        your email for future logins and account verification
                                    </p>
                                    <hr>
                                    <p class="mb-0">Please be sure to make sure that the new email is valid email address. Otherwise it will not be updated.</p>
                                </div>
                                <!-- Email -->
                                <br />
                                <div class="alert alert-danger hide" role="alert" id="email-error">Please enter a valid email.</div>
                                <input type="text"  name="email" id="email" class="form-control mb-4 hide" placeholder="E-mail" value="">
                                <div class="alert alert-danger hide" role="alert" id="vcode-error">Please enter a valid code.</div>
                                <input type="text" id="code" name="code" class="form-control mb-4" placeholder="Verification Code">
                                <div id="code-verify-buttons">
                                    <input class="btn btn-info btn-block my-4" type="button" value="Update-Email" id="updateEmail" />
                                    <input class="btn btn-info btn-block my-4" type="submit" name="submitCode" value="Submit-Code">
                                </div>
                                <div class="hide" id="email-verify-buttons">
                                    <input class="btn btn-info btn-block my-4" type="button" value="Verify-Account" id="verifyByCode" />
                                    <input class="btn btn-info btn-block my-4" type="submit" name="submitEmail" value="Submit-Email">
                                </div>
                                <!-- Register -->
                                <p>Not a member?
                                    <a href="">Register</a>
                                </p>
                                <!-- Social login -->
                                <p>Follow us at:</p>
                                <a href="#" class="mx-2" role="button"><i class="fab fa-facebook-f light-blue-text"></i></a>
                                <a href="#" class="mx-2" role="button"><i class="fab fa-twitter light-blue-text"></i></a>
                                <a href="#" class="mx-2" role="button"><i class="fab fa-linkedin-in light-blue-text"></i></a>
                                <a href="#" class="mx-2" role="button"><i class="fab fa-instagram light-blue-text"></i></a>
                            </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 type = "text/javascript">

    			//Now we need to check the form submission
    			$("form").submit(function(){
    					//For form there are two conditions to check that wether it 
    					//1. update the email
    					//2. It enter the verify Code
    					if($("#code-verify-buttons").css("display") == "none"){
    							//this is when the verify buttons are hidden
    							//So we check for the email update
    							var email = $("#email").val();
    							// alert("The value of email:" + email);
    							var mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    							if (email.match(mailFormat)) {
    									$("#email-error").addClass("hide");
    								//	$("#php-error").removeClass("hide");
    									return true
    							} else {
    									$("#email-error").removeClass("hide");
    									//$("#php-error").addClass("hide");
    									event.preventDefault();
    							}
    					}else{
    							//In this case we verify account
    							var codelength = $("#code").val().length;
    						//alert("The length is: " + codelength);
                if (codelength < 10) {
                    $("#vcode-error").removeClass("hide");
    							//	$("#php-error").addClass("hide");
    								event.preventDefault();
                } else {
                    $("#vcode-error").addClass("hide");
    							//	$("#php-error").removeClass("hide");
    								return true;	
                }
    					}

    			});

    			$("#updateEmail").click(function() {
    			//Now we need to hide certain tags
    					$("#email-error").addClass("hide");
    					$("#vcode-error").addClass("hide");
    					$("#code-verify-buttons").addClass("hide");
    					$("#code").addClass("hide");
    					$("#email-info").addClass("hide");
    					//Now we need to show certains tags
    					$("#email").removeClass("hide");
    					$("#code-info").removeClass("hide");
    					$("#email-verify-buttons").removeClass("hide");
    			});

    			$("#email").blur(function() {
                var email = $("#email").val();
    						// alert("The value of email:" + email);
                var mailFormat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
                if (email.match(mailFormat)) {
                    $("#email-error").addClass("hide");
                } else {
                    $("#email-error").removeClass("hide");
                }
            });

    				$("#code").blur(function() {
                var codelength = $(this).val().length;
    						//alert("The length is: " + codelength);
                if (codelength < 10) {
                    $("#vcode-error").removeClass("hide");
                } else {
                    $("#vcode-error").addClass("hide");
                }

            });

    				$("#verifyByCode").click(function() {

    						//So now we need to check which fields to hide
    						$("#email").addClass("hide");
    						$("#email-error").addClass("hide");
    						$("#vcode-error").addClass("hide");
    						$("#email-verify-buttons").addClass("hide");
    						$("#code-info").addClass("hide");

    						//Now we will show certains fields
    						$("#code-verify-buttons").removeClass("hide");
    						$("#code").removeClass("hide");
    						$("#email-info").removeClass("hide");
    				});

        </script>

    </body>
</html>