<?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['username'];

                    //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>
                .ctm-outer{
                    background-color: white;
                    box-shadow: 0 0 15px #dfdfdf;
                }

                #email-error {
                    display: none;
                }

                #email {
                    display: none;
                }

                #vcode-error {
                    display: none;
                }

                #email-verify-buttons {
                    display: none;
                }

                #code-info{
                    display: none;
                }

                #php-error{
                    display: block;
                }
            </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" name="verifyAccount" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateForm();" method="POST">

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

                                <div id="php-error">
                                <?php

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

                                ?>
                                </div>

                                <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" 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" role="alert" id="email-error">Please enter a valid email.</div>
                                <input type="text" name="email" id="email" class="form-control mb-4" placeholder="E-mail" value="" onblur="checkEmail()">

                                <div class="alert alert-danger" 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" onblur="checkVerifyCode()">

                                <div id="code-verify-buttons">
                                    <input class="btn btn-info btn-block my-4" type="button" value="Update-Email" onclick="updateEmail()"/>
                                    <input class="btn btn-info btn-block my-4" type="submit" name="submitCode" value="Submit-Code">
                                </div>

                                <div id="email-verify-buttons">
                                    <input class="btn btn-info btn-block my-4" type="button" value="Verify-Account" onclick="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>

                function verifyByCode(){

                    document.getElementById("form-header").innerText = "Verify Account";
                    //In this function user will choose verify account button
                    //With this we will hide and show certain things

                    //Firstly we will hide certain tags
                    document.getElementById("email").style.display = "none";
                    document.getElementById("email-error").style.display = "none";
                    document.getElementById("vcode-error").style.display = "none";
                    document.getElementById("email-verify-buttons").style.display = "none";

                    //Now we need to show certain tags
                    document.getElementById("code-info").style.display = "none";
                    document.getElementById("code-verify-buttons").style.display = "block";
                    document.getElementById("code").style.display = "block";
                    document.getElementById("email-info").style.display = "block";

                    document.getElementById("php-error").style.display = "none";

                }

                function updateEmail(){

                    document.getElementById("form-header").innerText = "Update Email"
                    //In this function user will choose update email button
                    //With this we will hide and show certain things

                    //Firstly we will show certain tags
                    document.getElementById("email").style.display = "block";
                    document.getElementById("email-error").style.display = "none";
                    document.getElementById("vcode-error").style.display = "none";
                    document.getElementById("email-verify-buttons").style.display = "block";

                    //Now we need to hide certain tags
                    document.getElementById("code-info").style.display = "block";
                    document.getElementById("code-verify-buttons").style.display = "none";
                    document.getElementById("code").style.display = "none";
                    document.getElementById("email-info").style.display = "none";
                    document.getElementById("php-error").style.display = "none";

                }

                function checkEmail() {
                    
                    var email = document.forms["verifyAccount"]["email"].value.trim();
                    document.forms["verifyAccount"]["email"].value = email;

                    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

                    if (email.match(mailformat)) {
                        document.getElementById("email-error").style.display = "none";
                        return true;
                    }else{
                        document.getElementById("email-error").style.display = "block";
                        return false;
                    }

                }

                    function checkVerifyCode() {

                        var code = document.forms["verifyAccount"]["code"].value.trim();
                        document.forms["verifyAccount"]["code"].value = code;

                        if(code.length < 10){
                            document.getElementById("vcode-error").style.display = "block";
                            return false;
                        }else{
                            document.getElementById("vcode-error").style.display = "none";
                            return true;
                        }
                    }

                    //This function is to validate before we submit something
                    function validateForm() {

                        //For this we check if the display of the respective input
                        //And also the div containing buttons

                        var emailDisplay = document.getElementById("email").style.display;
                        var codeDisplay = document.getElementById("code").style.display;

                        if(emailDisplay == "block"){
                            //User is trying to update the email
                            var email = checkEmail();
                            if(email == true){
                                return true;
                            }else{
                                event.preventDefault();
                            }   
                        }else{
                            //User is trying to verify account;
                            var code = checkVerifyCode();
                            if(code == true){
                                document.getElementById("php-error").style.display = "block";
                                return true;
                            }else{
                                event.preventDefault();
                            }
                        }

                    }

            </script>

    </body>
</html>

