<?php

// ini_set('display_errors', 1); 
// ini_set('display_startup_errors', 1); 
// error_reporting(E_ALL);

$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($_SERVER["REQUEST_METHOD"] == "POST") {
		
    $username = mysqli_real_escape_string($conn,$_POST["email"]);
    $password = hash('sha256', mysqli_real_escape_string($conn,$_POST["password"]), false);

    $result = $conn->query("SELECT * FROM user_account WHERE username = '$username' AND password = '$password'");
    if($result) {
        if($result->num_rows == 1)
        {
            $row = $result->fetch_assoc();
            // if($row['active'] == 1)
            // {
                
                // debug("Session started");
    
                $_SESSION['username'] = $username;
                //the email is loaded to 
                $_SESSION['email'] = $row['email'];
                //$_SESSION['accountType'] = $row['accountType'];
    
                $output['success'] = true;
                //$output['session'] = array("user" => $_SESSION['username'], "accountType" => $_SESSION['accountType']);

                //We need to check wether his/her account has become active or not

                $accountStatus = $row['active'];

                if($accountStatus == 0){
                    header("location: verifyEmail.php");
                }else{
                    header('location:dashboard.php');
                }
                exit;
        }
        else if($result->num_rows > 1)
        {
            //$output['success'] = false;
            $msg = "Duplicate Entries for login details";
        }
        else 
        {
           // $output['success'] = false;
            $msg = "Your Login Name or Password is invalid";
        }
    }
    else {
        //$output['success'] = false;
        error($conn->connect_error);
    }

    //This is the case where we consider that user has tried to login via his/her email
    $result = $conn->query("SELECT * FROM user_account WHERE email = '$username' AND password = '$password'");
    if($result->num_rows == 1)
        {
            $row = $result->fetch_assoc();
    
                $_SESSION['email'] = $username;
                //the email is loaded to 
                $_SESSION['username'] = $row['username'];
                //$_SESSION['accountType'] = $row['accountType'];
    
                $output['success'] = true;
                //$output['session'] = array("user" => $_SESSION['username'], "accountType" => $_SESSION['accountType']);

                //We need to check wether his/her account has become active or not

                $accountStatus = $row['active'];

                if($accountStatus == 0){
                    header("location: verifyEmail.php");
                }else{
                    header('location: dashboard.php');
                }
                exit;
        }
        else if($result->num_rows > 1)
        {
            //$output['success'] = false;
            $msg = "Duplicate Entries for login details";
        }
        else 
        {
           // $output['success'] = false;
            $msg = "Your Login Name or Password is invalid";
        }
    }else {
        //$output['success'] = false;
        error($conn->connect_error);
    }

//sendOutput();
   
$conn->close();

?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Sign-In 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">

    <style>
        #user-error {
            display: none;
        }

        #p-error {
            display: none;
        }

        #user-check {
            display: none;
        }

        #login-check {
            display: none;
        }
    </style>

    <script>

        function checkUsername() {
            var user = document.forms["signin"]["email"].value.trim();

            document.forms["signin"]["email"].value = user;

            if (user.length < 4) {
                document.getElementById("user-error").style.display = "block";
                return false;

            } else {
                document.getElementById("user-error").style.display = "none";
                return true;

            }

        }

        function checkPassword() {
            var pass = document.forms["signin"]["password"].value.trim();

            document.forms["signin"]["password"].value = pass;

            if (pass.length == 0) {
                document.getElementById("p-error").style.display = "block";
                return false;

            } else {
                document.getElementById("p-error").style.display = "none";
                return true;

            }

        }

        function checkSubmission(e){
            var username = checkUsername();
            var password = checkPassword();

            if(username && password){
                return true;
            }else{

                e.preventDefault();

                return false;
            }

        }

        

    </script>

</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="signin" onsubmit="return checkSubmission(this.event);" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
                  method="POST">

                <p class="h4 mb-4">Sign In</p>

                <?php 

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

                ?>
                <!-- Email -->
                <br/>
                <div class="alert alert-danger" role="alert" id="user-error">Email or username is required</div>

                <input type="text" id="defaultLoginFormEmail" name="email" id="email" class="form-control mb-4"
                    placeholder="E-mail or Username" onblur="checkUsername()">
                <!-- <div class="alert alert-warning" role="alert" id="user-check">Email or username does not exists!!</div> -->
                <!-- Password -->
                <div class="alert alert-danger" role="alert" id="p-error">Password is required</div>
                <input type="password" id="defaultLoginFormPassword" id="password" name="password"
                    class="form-control mb-4" placeholder="Password" onblur="checkPassword()">

                <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>
                        <!-- Forgot password -->
                        <a href="">Forgot password?</a>
                    </div>
                </div>

                <!-- Sign in button -->
                <button class="btn btn-info btn-block my-4" type="submit"  id="sign-in">Sign-In</button>

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