<?php

$output['result'] = "";
$output['success'] = "";
$output['debug'] = "";
$output['session'] = "";

session_start();

function debug($string)
{
    $GLOBALS['output']['debug'] .= "[Debug - " . $string . "] ";
}

function error($string)
{
    $GLOBALS['output']['debug'] .= "[Error - " . $string . "] ";
}

function sendOutput()
{
    echo json_encode($GLOBALS['output']);
}

//First we need to connect to the database
$conn = new mysqli("localhost", "ps2020", "ps2020pass");

if ($conn->connect_errno) {
    echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
else {
    debug("Successful Connection");
    // debug($conn->host_info);
}

if($conn->select_db('ps2020')) { debug("Using ps2020"); }
else { error($conn->error); }   

$msg = '';

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

        $email = $_SESSION['email'];
        $username = $_SESSION['username'];
        //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>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Account Verification Page</title>
    <!-- Bootstrap 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">
   
    </head>

<body>

    <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']);?>"
                  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">

                <div class="d-flex justify-content-around">
                    <div>
                        <!-- Remember me -->
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="defaultLoginFormRemember">
                            <label class="custom-control-label" for="defaultLoginFormRemember">Remember me</label>
                        </div>
                    </div>
                   
                </div>

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

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

    <!-- JQuery -->

</body>

</html>