<?php

/**
 * class user
 *
 * Description for class user
 *
 * @author:
*/
namespace core;

use core\password;

class user {
	public static function init() {
		if(!isset($_SESSION["__user"])) {
			$_SESSION["__user"] = array(
				"authorization" => false,
				"user_id" => "",
				"name" => "",
				"email" => "",
				"role" => ""
				);
		}
	}

	public static function auth($role = "") {
		$lock = false;
		
		if(!self::is_authorization()) {
			$lock = true;
		}

		if(!empty($role) && array_search(self::role(), explode(",", $role)) === false) {
			$lock = true;
		}
		
		return $lock;
	}

	public static function authorization($user_id, $name, $email, $role) {
		$_SESSION["__user"]["authorization"] = true;
		$_SESSION["__user"]["user_id"] = $user_id;
		$_SESSION["__user"]["name"] = $name;
		$_SESSION["__user"]["email"] = $email;
		$_SESSION["__user"]["role"] = $role;
	}

	public function logout() {
		$_SESSION["__user"]["authorization"] = false;
		$_SESSION["__user"]["user_id"] = "";
		$_SESSION["__user"]["name"] = "";
		$_SESSION["__user"]["email"] = "";
		$_SESSION["__user"]["role"] = "";
	}

	public static function is_authorization() {
		return $_SESSION["__user"]["authorization"];
	}

	public static function identifier() {
		return $_SESSION["__user"]["user_id"];
	}

	public static function name() {
		return $_SESSION["__user"]["name"];
	}

	public static function email() {
		return $_SESSION["__user"]["email"];
	}

	public static function role() {
		return $_SESSION["__user"]["role"];
	}

	public static function updateName($name, $userId = null) {
		global $__database;

		if(empty($userId)) {
			$userId = user::identifier();
		}

		$query = $__database->prepare("UPDATE `users` SET `name`=:name WHERE `user_id`=:user_id");
		$query->bindParam(":name", $name);
		$query->bindParam(":user_id", $userId);
		if($query->execute()) {
			$_SESSION["__user"]["name"] = $name;
			return true;
		}

		return false;
	}

	public static function updatePassword($password, $userId = null) {
		global $__database;

		if(empty($userId)) {
			$userId = user::identifier();
		}

		$password = password::hash($password);
		
		$query = $__database->prepare("UPDATE `users` SET `password`=:password WHERE `user_id`=:user_id");
		$query->bindParam(":password", $password);
		$query->bindParam(":user_id", $userId);
		if($query->execute()) {
			return true;
		}

		return false;
	}
}
?>