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

        $username = $_SESSION['user'];
        $email = $_SESSION['email'];

        $pg_email = 0;
        $msg_type;


        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"])){  //'New email' is submitted (submit-button)

                //so the user is trying to update the email
                $newEmail = mysqli_real_escape_string($conn, $_POST['email']);

                // check if the email doesn't have invalid sign/format
                if(!filter_var($newEmail, FILTER_VALIDATE_EMAIL)){
                    $msg = "Invalid Email! Please enter a valid email!";
                }
                else{

                    // check if the email is not registered by other users (but acceptable to be the same as this user's previous email)
                    $result = $conn->query("SELECT email FROM user_account WHERE username !='$username' AND email = '$newEmail'");

                    if($result->num_rows > 0){  //email already exist
                        $msg = "Try Again!!<br>This email is already registered to another account!!";
                        $pg_email = 1;
                        $msg_type = 1;
                    }
                    else{  //update new email into database
                        $result = $conn->query("UPDATE user_account SET email= '$newEmail' WHERE username = '$username'");

                            if($result){
                                $msg = "Your email has been Updated!";
                                //we also update the email of session variable to a new one
                                $_SESSION['email'] = $newEmail;
                                $pg_email = 0;
                                $msg_type = 2;
                            }
                            else{
                                $msg = "Error updating record: " . $conn->error;
                                $msg_type = 1;
                            }

                        // generate 'random code'
                            function getRandomCode() {
                                $n=10;
                                $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                                $randomCode = '';
                              
                                for ($i = 0; $i < $n; $i++) {
                                    $index = rand(0, strlen($characters) - 1);
                                    $randomCode .= $characters[$index];
                                }
                              
                                return $randomCode;
                            }

                        // check if 'Verify-Code' exist
                            $result = $conn->query("SELECT verifyCode FROM user_account WHERE username = '$username'");
                            if ($result->num_rows > 0) {
                                // output data of each row
                                while($row = $result->fetch_assoc()) {
                                    $verifyCode = $row["verifyCode"];
                                }
                            }
                            else{  //generate code
                                $verifyCode = getRandomCode();
                                $conn->query("UPDATE user_account SET verifyCode = '$verifyCode' WHERE username = '$username'");
                            }

                        if ( isset($verifyCode) ){
                            //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 = "<h4>Welcome to GEESE.</h4>";
                            $message .= "<h4>Hi '" . $username . "'', we would like to thank you for joining GEESE</h4>";
                            $message .= "<span>Your Verfication Code is: <h1>" . $verifyCode . "</h1></span>";

                            $header = "From:no-reply@gmail.com \r\n";
                            $header .= "Cc: \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 . "<br>The code has been emailed to you";
                                $msg_type = 2;
                            }else {
                                $msg = $msg . "<br>Email couldn't be sent";
                                $msg_type = 1;
                            }
                        }
                        else{
                            $msg = "<br>Error updating record: "."unable to generate/detect V-Code";
                            $msg_type = 1;
                        }
                    }
                }
            }
        
            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"]);

                $result = $conn->query("SELECT * FROM user_account WHERE username = '$username'");

                    if($result->num_rows == 1){
                        while($row = $result->fetch_assoc()){

                            if( $row["verifyCode"] == $userCode ){
                                $msg = "Your usercode is valid";

                                // V-Code is 'valid' | account is now 'active' = 1 | set V-Code = 0
                                if($conn->query("UPDATE user_account SET active = '1', verifyCode = 0 WHERE username = '$username'") === TRUE){
                                    
                                    $msg = "Your account status has been updated!!";
                                    $msg_type = 2;
                                    header('location: '.dir_root.'account/dashboard.php');

                                }else{
                                    $msg = "There's an 'error' to activate your account!!";
                                    $msg_type = 1;
                                }

                            }else{
                                $msg = "The 'Verify-Code' is incorrect!!";
                                $msg_type = 1;
                            }
                        }

                    }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>
                .mb-4{
                    margin-bottom: .7rem !important;
                }

                .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">

                            <?php
                                if ($pg_email == 0){
                                    $code_hide = '';
                                    $email_hide = 'ctm-hide';
                                }
                                else{
                                    $code_hide = 'ctm-hide';
                                    $email_hide = '';
                                }

                                if (isset($msg_type)){
                                    if ($msg_type < 2){
                                        $style_msg = 'alert-danger';
                                    }
                                    else
                                        $style_msg = 'alert-success';
                                }
                            ?>
                            <!-- V-Code (form) -->
                                <form class="animated fadeInUp text-center border border-light p-5 ctm-outer <?php echo $code_hide; ?>" id="verifyAccount" name="verifyAccount" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateForm_vCode();" method="POST">

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

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

                                    <div class="alert alert-info" role="alert" id="email-info">
                                        <span>A verification code has been sent to your email address: </span><h4 class="alert-heading"><?php echo $_SESSION["email"]; ?></h4>
                                        <hr>
                                        <span class="mb-0">Please check your Spam/Junk Email, if you do not see the email.</span>
                                    </div>

                                    <!-- v-code -->
                                    <div>
                                        <!-- error -->
                                        <div class="alert alert-danger ctm-hide" role="alert" id="vcode-error">Please enter the verification code.</div>
                                        <!-- txtfield -->
                                        <input type="text" id="code" name="code" class="form-control mb-4" placeholder="Verification Code" onblur="checkVerifyCode()">
                                    </div>

                                    <div style="text-align: left; color: green; text-decoration: underline;">
                                        <span style="cursor: pointer;" onclick="toEmail()">Didn't receive a code? / Re-enter email?</span>
                                    </div>

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

                                </form>

                            <!-- Update-Email (form) -->
                                <form class="animated fadeInUp text-center border border-light p-5 ctm-outer <?php echo $email_hide; ?>" id="updateEmail" name="updateEmail" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" onsubmit="return validateForm_email();" method="POST">

                                    <h3 class="h2 mb-4" id="form-header">Re-enter email</h3>

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

                                    <!-- email -->
                                    <div>
                                        <!-- error -->
                                        <div class="alert alert-danger ctm-hide" role="alert" id="email-error">Please enter a valid email.</div>
                                        <!-- txtfield -->
                                        <input type="text" name="email" id="email" class="form-control mb-4" placeholder="E-mail" value="" onblur="checkEmail()">
                                    </div>

                                    <div id="email-verify-buttons">
                                        <input class="btn btn-info btn-block my-4" type="submit" name="submitEmail" value="Confirm">
                                        <input class="btn btn-info btn-block my-4" type="button" value="Cancel" onclick="toVCode()" />
                                    </div>

                                </form>

                        </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>


        <!-- ==========  <- Pop-Notification ->  ========== -->
            <?php
                if (isset($msg_type)){
                    if ($msg_type == 1){  //fail
                        include_once(dir_rootPHP.'_global/tools/popNotif.php');

                        echo '<script>
                                $icon = 2;
                                $msg = "'.$msg.'";
                                popNotif_show($icon,$msg);
                            </script>';
                    }
                    else if ($msg_type == 2){  //success
                        include_once(dir_rootPHP.'_global/tools/popNotif.php');

                        echo '<script>
                                $icon = 1;
                                $msg = "'.$msg.'";
                                popNotif_show($icon,$msg);
                            </script>';
                    }
                }
            ?>


        <!-- Scripts (custom) -->
            <script>
                function toEmail(){
                    $('#verifyAccount').addClass('ctm-hide');
                    $('#updateEmail').removeClass('ctm-hide');
                }
                function toVCode(){
                    $('#verifyAccount').removeClass('ctm-hide');
                    $('#updateEmail').addClass('ctm-hide');
                }

                function checkVerifyCode(){
                    if ($('#code').val().length == 0){
                        $('#vcode-error').removeClass('ctm-hide');
                        return false;
                    }
                    else{
                        $('#vcode-error').addClass('ctm-hide');
                        return true;
                    }
                }

                function validateForm_vCode(){
                    if (checkVerifyCode()){
                        return true;
                    }
                    else
                        event.preventDefault();
                }

                function checkEmail(){
                    
                    $email = $('#email').val();
                    var reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

                    if ( reg.test($email) && $email.length > 0 ){  // email is correct && length > 0
                        $('#email-error').addClass('ctm-hide');  // error 'hide'
                        return true;
                    }
                    else{
                        $('#email-error').removeClass('ctm-hide');  // error 'show'
                        return false;
                    }

                }

                function validateForm_email(){

                    if (checkEmail()){
                        return true;
                    }
                    else
                        event.preventDefault();
                }

            </script>

    </body>
</html>

