<?php
/*****************************************************************************
 * Member.php
 * Contains key class Member, derived from User.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class Member extends User
{
	private function __construct($data)
	{
		foreach ($data as $key => $value)
			$this->$key = $value;

		$this->is_logged = true;
		$this->is_guest = false;
		$this->is_admin = $this->is_admin == 1;
	}

	public static function fromId($id_user)
	{
		$row = Registry::get('db')->queryAssoc('
			SELECT *
			FROM users
			WHERE id_user = {int:id_user}',
			[
				'id_user' => $id_user,
			]);

		// This should never happen.
		if (empty($row))
			throw new NotFoundException('Cannot create Member object; user not found in db!');

		return new Member($row);
	}

	public static function fromSlug($slug)
	{
		$row = Registry::get('db')->queryAssoc('
			SELECT *
			FROM users
			WHERE slug = {string:slug}',
			[
				'slug' => $slug,
			]);

		// This shouldn't happen.
		if (empty($row))
			throw new NotFoundException('Cannot create Member object; user not found in db!');

		return new Member($row);
	}

	/**
	 * Creates a new member from the data provided.
	 * @param data
	 */
	public static function createNew(array $data)
	{
		$error = false;
		$new_user = [
			'first_name' => !empty($data['first_name']) ? $data['first_name'] : $error |= true,
			'surname' => !empty($data['surname']) ? $data['surname'] : $error |= true,
			'slug' => !empty($data['slug']) ? $data['slug'] : $error |= true,
			'emailaddress' => !empty($data['emailaddress']) ? $data['emailaddress'] : $error |= true,
			'password_hash' => !empty($data['password']) ? Authentication::computeHash($data['password']) : $error |= true,
			'creation_time' => time(),
			'ip_address' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
			'is_admin' => empty($data['is_admin']) ? 0 : 1,
		];

		if ($error)
			return false;

		$db = Registry::get('db');
		$bool = $db->insert('insert', 'users', [
			'first_name' => 'string-30',
			'surname' => 'string-60',
			'slug' => 'string-90',
			'emailaddress' => 'string-255',
			'password_hash' => 'string-255',
			'creation_time' => 'int',
			'ip_address' => 'string-45',
			'is_admin' => 'int',
		], $new_user, ['id_user']);

		if (!$bool)
			return false;

		$new_user['id_user'] = $db->insert_id();
		$member = new Member($new_user);

		return $member;
	}

	/**
	 * Updates the member using the data provided.
	 * @param data
	 */
	public function update(array $new_data)
	{
		foreach ($new_data as $key => $value)
		{
			if (in_array($key, ['first_name', 'surname', 'slug', 'emailaddress']))
				$this->$key = $value;
			elseif ($key === 'password')
				$this->password_hash = Authentication::computeHash($value);
			elseif ($key === 'is_admin')
				$this->is_admin = $value == 1 ? 1 : 0;
		}

		$params = get_object_vars($this);
		$params['is_admin'] = $this->is_admin ? 1 : 0;

		return Registry::get('db')->query('
			UPDATE users
			SET
				first_name = {string:first_name},
				surname = {string:surname},
				slug = {string:slug},
				emailaddress = {string:emailaddress},
				password_hash = {string:password_hash},
				is_admin = {int:is_admin}
			WHERE id_user = {int:id_user}',
			$params);
	}

	/**
	 * Deletes the member.
	 * @param data
	 */
	public function delete()
	{
		return Registry::get('db')->query('
			DELETE FROM users
			WHERE id_user = {int:id_user}',
			['id_user' => $this->id_user]);
	}

	/**
	 * Checks whether an email address is already linked to an account.
	 * @param emailaddress to check
	 * @return false if account does not exist
	 * @return user id if user does exist
	 */
	public static function exists($emailaddress)
	{
		$res = Registry::get('db')->queryValue('
			SELECT id_user
			FROM users
			WHERE emailaddress = {string:emailaddress}',
			[
				'emailaddress' => $emailaddress,
			]);

		if (empty($res))
			return false;

		return $res;
	}

	public function updateAccessTime()
	{
		return Registry::get('db')->query('
			UPDATE users
			SET
				last_action_time = {int:now},
				ip_address = {string:ip}
			WHERE id_user = {int:id}',
			[
				'now' => time(),
				'id' => $this->id_user,
				'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '',
			]);
	}

	public function getUrl()
	{
		return BASEURL . '/author/' . $this->slug . '/';
	}

	public static function getCount()
	{
		return Registry::get('db')->queryValue('
			SELECT COUNT(*)
			FROM users');
	}

	public function getProps()
	{
		// We should probably phase out the use of this function, or refactor the access levels of member properties...
		return get_object_vars($this);
	}

	public static function getMemberMap()
	{
		return Registry::get('db')->queryPair('
			SELECT id_user, CONCAT(first_name, {string:blank}, surname) AS full_name
			FROM users
			ORDER BY first_name, surname',
			[
				'blank' => ' ',
			]);
	}
}