} else {
     $hospital = '';
     $notify = '';
 //proceed with creating and storing the new user
 //create a default password based on: User's firstname and last 4 digits of their phone number
 $password = trim(strtolower($fname)) . trim(substr($phone, -4));
 $password = getHashValue($password);
 $newUserProfile = new UserProfile($userCategories[$userType], 0, $username, $email, $password, 0, $title, $fname, $lname, $phone, 0, $title, $fname, $lname, $hospital, $phone, $notify);
 //insert user profile
 $insertProfile = insert_UserProfile($newUserProfile);
 //if user profile insertion is successful, then the corresponding user profile tables need to be updated as well
 if ($insertProfile) {
     //get the userprofile id for the newly inserted user
     //can this be done more efficiently, instead of retrieving all the info? using last_insert_id maybe?
     $retrievedUser = retrieve_UserByAuth($username);
     if ($retrievedUser) {
         //if a user is retrieved, store the detailed information in the corresponding profile table
         if ($retrievedUser['UserCategory'] == $userCategories['socialworker']) {
             //if the user is a social worker, insert the detail info in the social worker table
             $insertDetailProfile = insert_SocialWorkerProfile($newUserProfile);
         } else {
             //else the user is an rmh staff, so insert detailed profile in the rmhstaff table
             $insertDetailProfile = insert_RmhStaffProfile($newUserProfile);
         //check for errors
         if ($insertDetailProfile) {
             //$messages['user_creation_successful'] = "The user ".$username. " was successfully created.";
             setSessionMessage("The user {$username} was created successfully");
             $data = array();
if (isset($_POST['form_token'])) {
    try {
        //form validation rules
        $accountSettingsRules = array('title' => array('alpha', 'allow' => array('.')), 'old_pass' => array('password'), 'new_pass' => array('password'), 'verify_pass' => array('password', 'notempty'), 'submit' => array('ignore'));
        $validator = new DataValidator($_POST, $accountSettingsRules);
        $data = $validator->getData();
        if ($validator->isValid()) {
            //validation successful
            $newPass = getHashValue($data['new_pass']);
            $verifyPass = getHashValue($data['verify_pass']);
            $oldPass = getHashValue($data['old_pass']);
            $title = $data['title'];
            $username = getCurrentUser();
            //TODO we could add this check in the validator?
            if ($newPass === $verifyPass) {
                if (retrieve_UserByAuth($username, $oldPass)) {
                    //verify password and new password match AND the user with the old password exists
                    //retrieve user profile:
                    $userProfile = retrieveCurrentUserProfile();
                    if ($userProfile) {
                        //change the password
                        //TODO set the user title too. But isn't that included in profile change?
                        //update the user profile table
                        if (update_UserProfile($userProfile)) {
                            //set session message
                            setSessionMessage("Your password has been successfully changed. You should log out and log in again for security reasons.");
                            $data = array();
                            $dataErrors = array();
                            //TODO Logout the user here
                        } else {
    $classAdd = 'contentLogin';
//Access Level (Should match UserCategory in DB):
$accessLevel = array('Family' => 0, 'Social Worker' => 1, 'RMH Staff Approver' => 2, 'RMH Administrator' => 3);
$error = array();
//variable that stores all the errors that occur in the login process
//if data is submitted then do the following:
//validate the token
//if token validates, check for user and add session variables
if (isset($_POST['form_token']) && validateTokenField($_POST)) {
    //sanitize all these data before they get to the database !! IMPORTANT
    $db_pass = getHashValue($_POST['password']);
    $db_username = sanitize($_POST['username']);
    include_once ROOT_DIR . '/database/dbUserProfile.php';
    //Retrieve the user category using the username and password
    $currentUser = retrieve_UserByAuth($db_username, $db_pass);
    if ($currentUser) {
        //if the usercategory is returned, log the user in and assign session variables
        $_SESSION['logged_in'] = true;
        $_SESSION['access_level'] = $accessLevel[$currentUser['UserCategory']];
        $_SESSION['_username'] = $db_username;
        $_SESSION['_id'] = $currentUser['UserProfileID'];
        //check if the user is still using the default password
        echo "<script type=\"text/javascript\">window.location = \"index.php\";</script>";
    } else {
        //if no user category was found, then the credentials were wrong
        $error['invalid_username'] = "******";
} else {
$title = "Reset Password";
//This should be the title for the page, included in the <title></title>
include 'header.php';
//including this will further include (globalFunctions.php and config.php)
include ROOT_DIR . '/database/dbUserProfile.php';
$error = array();
//an array that holds the
$testData = array('test0' => '', 'test1' => 'activation');
if (isset($_POST['form_token']) && validateTokenField($_POST)) {
    //the security validation was successful, perform required operation here below.
    //*** NOTE *** The validateTokenField DOES NOT filter/sanitize/clean the data fields.
    //A separate function sanitize() should be called to clean the data so that it is html/db safe
    //handle POST data for reset password (the default form)
    if (isset($_POST['resetPassword'])) {
        $username = isset($_POST['username']) ? sanitize($_POST['username']) : '';
        $userRetrieved = retrieve_UserByAuth($username);
        //check the database, if the username exists or not
        if ($userRetrieved) {
            //the user exists, create a random string as an activation code and send an email
            //store the activation code in the DB
            //check the activation table for the user's info and expiry,
            //if it is already there notify the user to check their email again
            if (!empty($testData[$username]) && true) {
                //maybe let them resend the email again?
                $message = 'A password reset information has already been sent to your email. Please check your email for more information.';
            } else {
                //if the user has never requested a password reset before, go ahead and proceed with creating the activation key
                $activation_code = generateRandomString();
                $_SESSION['_activation'] = array($username => $activation_code);
                //stored in the session for test purpose -- to check the post data
                //store this code in the database