<?php


/**
 * file: user_authentication.php
 *
 * Copyright Miller Electric Mfg. Co. as an unpublished work.
 * All rights reserved.
 *
 * The information contained herein is confidential property of
 * Miller Electric Mfg. Co.  The use of, copying, transfer or
 * disclosure of such information is prohibited except by express
 * written agreement with Miller Electric.
 */


/**
 * Defines a class used for managing user authentication.
 * It is recommended to use this class as purely static.
 * This class also serves as the single source of truth for all data related to
 * user authentication, such as file paths, and json and data structures.
 * It is recommended to use this class rather than accessing $_SESSION info
 * about user authentication directly.
 */
class UserAuthentication {
	private static $passwordFilePath = '/Insight/devicePagesData.json';
	private static $passwordJsonKey = 'Password';
	private static $isUserLoggedInKey = 'isUserLoggedIn';


	// Public functions

	
	/**
	 * Logs in the user in the current session, only if the given password is
	 * valid/correct.
	 * @param string The password to validate.
	 * @return bool True if the user was logged in, otherwise false.
	 */
	public static function logInUser($password) {
		$result = self::validatePassword($password);

		if($result) {
			$result = self::isASessionActive();
		}

		if($result) {
			$_SESSION[self::$isUserLoggedInKey] = true;
		}

		return $result;
	}


	/**
	 * Logs out the user from the session.
	 */
	public static function logOutUser() {
		if(self::isUserLoggedIn()) {
			$_SESSION[self::$isUserLoggedInKey] = false;
		}
	}


	/**
	 * Checks whether a password has been set for this device.
	 * @return bool True if a password has been set and is currently stored
	 * in the designated file, otherwise false.
	 */
	public static function isDevicePasswordSet() {
		$result = false;

		if(file_exists(self::$passwordFilePath)) {
			$jsonString = file_get_contents(self::$passwordFilePath);
    		$jsonArray = json_decode($jsonString, true);

			if(array_key_exists(self::$passwordJsonKey, $jsonArray)) {
				$result = $jsonArray[self::$passwordJsonKey] != '';
			}
		}

		return $result;
	}


	/**
	 * Validates the given password, chcking it against this device's current
	 * set password.
	 * @param string The password to check against the one set on this device.
	 * @return bool True if the password matches the one that was set,
	 * otherwise false.
	 */
	public static function validatePassword($password) {
		$result = false;
		if(self::isDevicePasswordSet()) {
			$result = password_verify($password, self::getSavedPassword());
		}

		return $result;
	}


	/**
	 * Saves the given password to the designated file on this device.
	 * Note that this will overwrite the previously set password.
	 * Note that this function encrypts the password before storing it.
	 * @param string The password to set.
	 * @return mixed The same as file_put_contents().
	 */
	public static function savePassword($password) {
		$result = -1;
		$jsonString = '';
		$jsonArray = array();
		$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

		// Load the file if it already exists.
		if(file_exists(self::$passwordFilePath)) {
			$jsonString = file_get_contents(self::$passwordFilePath);
			$jsonArray = json_decode($jsonString, true);
		}

		// Set the password.
		$jsonArray[self::$passwordJsonKey] = $hashedPassword;

		// Save the json data with the new password to the file.
		$jsonString = json_encode($jsonArray, JSON_PRETTY_PRINT);
		$result = file_put_contents(self::$passwordFilePath, $jsonString);

		return $result;
	}


	/**
	 * Checks if the user is currently logged in to the session.
	 * @return bool True if the user is logged in, otherwise false.
	 */
	public static function isUserLoggedIn() {
		$result = false;
		if(isset($_SESSION[self::$isUserLoggedInKey])) {
			if($_SESSION[self::$isUserLoggedInKey]) {
				$result = true;
			}
		}

		return $result;
	}
	

	// Private functions


	/**
	 * Gets the saved password from the designated file.
	 * Note that the password will be as was saved.
	 * @return string The password that was set on this device.
	 */
	private static function getSavedPassword() {
		$result = '';

		if(file_exists(self::$passwordFilePath)) {
			$jsonString = file_get_contents(self::$passwordFilePath);
    		$jsonArray = json_decode($jsonString, true);

			if(array_key_exists(self::$passwordJsonKey, $jsonArray)) {
				$result = $jsonArray[self::$passwordJsonKey];
			}
		}

		return $result;
	}


	/**
	 * Checks if a php session is currently active.
	 * @return bool True if a session is active, otherwise false.
	 */
	private static function isASessionActive() {
		return session_status() == PHP_SESSION_ACTIVE;
	}
}