<?php


session_start();
if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == true) {

    if (isset($_SESSION["last_Active"]) && (time() - $_SESSION["last_Active"] < 18000) || isset($_SESSION["remember_Me"]) && $_SESSION["remember_Me"] == true) {
        header("location: ../Dashboard");
        exit;
    } elseif (isset($_SESSION["last_Active"]) && (time() - $_SESSION["last_Active"] > 18000)) {
        $_SESSION = array();
        session_destroy();
        exit();
    }


}


require_once "../Config/config.php";

$username = $password = "";
$username_err = $password_err = $authentication_err = "";
$check = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    //validation
    if (empty(trim($_POST["username"]))) {
        $username_err = "Enter your username.";
    } else {
        $username = trim($_POST["username"]);
    }

    //validation
    if (empty(trim($_POST["pwd"]))) {
        $password_err = "Enter your password.";
    } else {
        $password = trim($_POST["pwd"]);
    }
    if (isset($_POST['checkbox'])) {
        $check = "1";

    }

    if (empty($username_err) && empty($password_err)) {


        $sql = "SELECT  Staff_ID, password, Security_Level, Terminate_On, Locked FROM users WHERE Staff_ID = ?";

        if ($stmt = mysqli_prepare($link, $sql)) {
            mysqli_stmt_bind_param($stmt, "s", $username);

            // Attempt to execute the prepared statement
            if (mysqli_stmt_execute($stmt)) {

                // Store result
                mysqli_stmt_store_result($stmt);

                // Checks if username exists, if yes then verify password
                if (mysqli_stmt_num_rows($stmt) == 1) {

                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $username, $hashed_password, $securitylvl, $terminateOn, $status);

                    if (mysqli_stmt_fetch($stmt)) {

                        if (strtotime($terminateOn) > time() && $status == 0) {
                            echo $status;

                            if (password_verify($password, $hashed_password)) {


                                // Password is correct, so start a new session
                                session_start();


                                $_SESSION["username"] = $username;
                                $_SESSION["loggedin"] = true;
                                $_SESSION["last_Active"] = time();
                                $_SESSION["security_Level"] = $securitylvl;
                                $_SESSION["terminateOn"] = strtotime($terminateOn);


                                if (isset($_POST['checkbox'])) {
                                    $_SESSION["remember_Me"] = true;


                                } else {
                                    $_SESSION["remember_Me"] = false;
                                }

                                // Redirect user to welcome page
                                header("location: ../Dashboard");
                            } else {
                                // Display an error message if password is not valid
                                $authentication_err = "The username or password you entered isn't valid, please try again.";
                            }
                        } else {
                            $authentication_err = "The Account you are trying to access has been terminated or locked, please contact your network admin if this is a mistake.";
                        }

                    }

                } else {
                    // Display an error message if username doesn't exist
                    $authentication_err = "The username or password you entered isn't valid, please try again.";
                }
            } else {
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);

        }
    }
    // Close connection
    mysqli_close($link);

}


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include "../Templates/Header.php"; ?>

    <title>Login</title>
</head>
<body>

<div id="page-container">

    <div id="content-wrap">

        <div class="jumbotron vertical-center" style="background-color: lightblue;">

            <div class="container-fluid">

                <div class="offset-sm-4 col-sm-4">

                    <h2>Welcome</h2>
                    <h2>Login:</h2>
                    <span><?php echo "<p class='error'>" . $authentication_err . "</p>"; ?></span>
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                        <div class="form-group ">
                            <label for="username">Username:</label>
                            <input type="text"
                                   class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>"
                                   name="username" id="username" placeholder="Username" value="<?php echo $username ?>">
                            <span><?php echo "<p class='error'>" . $username_err . "</p>"; ?></span>
                        </div>
                        <div class="form-group">
                            <label for="pwd">Password:</label>
                            <input type="password"
                                   class="form-control  <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>"
                                   name="pwd" id="pwd" placeholder="Password">
                            <span><?php echo "<p class='error'>" . $password_err . "</p>"; ?></span>
                        </div>
                        <div class="checkbox">
                            <label><input type="checkbox"
                                          name="checkbox" <?php echo (!empty($check)) ? 'checked' : ''; ?> > Remember me</label>
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-danger btn-block" value="Login">
                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

    <footer id="footer">

    </footer>
</div>

</body>
</html>
