<?php
    session_start();
    $error='';

    if (isset($_REQUEST['submit'])) {
        if (empty($_REQUEST['username']) || empty($_REQUEST['password'])) {
            $error = "Username or Password is invalid";
        }
    } else {
        $_submissions = [
            'username' => $_REQUEST['username'],
            'password' => $_REQUEST['password']
        ];

        include 'db_conn.php';

        $query = "SELECT * FROM Users WHERE username=:user";

        $statement = $db->prepare($query);
        try {
            $statement->execute(array(
                "user" => $_submissions['username'],
            ));
        } catch (PDOException $ex2) {
            echo $query . "<br>" . $ex2;
            http_response_code(401);
            die("Error connecting to SQL server (login).");
        }

        $result = $statement->fetch(PDO::FETCH_ASSOC);

        /* Use password_hash to store hash in database. */
        $password_correct = password_verify($_submissions['password'], $result['password_hash']);
        $user_active = $result['status_user_id'] != 1;

	if (!$user_active)
	{
		http_response_code(401);
		die("User is inactive.");
	}

        if ($password_correct && $user_active) {
            $_SESSION['user_object'] = $result;
            $_SESSION['logged_in'] = true;
            $_SESSION['user_id'] = $result['user_id'];
            $_SESSION['privilege_id'] = $result['privilege_id'];
            $_SESSION['username'] = $result['username'];
            $_SESSION['email'] = $result['email'];
        } else {
            $error = $query . "<br>" . "No user with this username / password combination or user inactive.";
            http_response_code(401);
            die('Incorrect user/pass combo');
        }

        echo "You've been logged in.";
    }
?>
