<?php
/*****************************************************************************
 * EditUser.php
 * Contains the edit user controller.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class EditUser extends HTMLController
{
	public function __construct()
	{
		// Ensure it's just admins at this point.
		if (!Registry::get('user')->isAdmin())
			throw new NotAllowedException();

		// Who are we, again?
		$current_user = Registry::get('user');

		$id_user = isset($_GET['id']) ? (int) $_GET['id'] : 0;
		if (empty($id_user) && !isset($_GET['add']))
			throw new UnexpectedValueException('Requested user not found or not requesting a new user.');

		// Adding a user?
		if (isset($_GET['add']))
		{
			$form_title = 'Add a new user';
			parent::__construct($form_title);
			$this->page->addClass('edituser');
		}
		// Deleting one?
		elseif (isset($_GET['delete']))
		{
			// Don't be stupid.
			if ($current_user->getUserId() == $id_user)
				trigger_error('Sorry, I cannot allow you to delete yourself.', E_USER_ERROR);

			// So far so good?
			$user = Member::fromId($id_user);
			if (Session::validateSession('get') && $user->delete())
			{
				header('Location: ' . BASEURL . '/manageusers/');
				exit;
			}
			else
				trigger_error('Cannot delete user: an error occured while processing the request.', E_USER_ERROR);
		}
		// Editing one, then, surely.
		else
		{
			$user = Member::fromId($id_user);
			$form_title = 'Edit user \'' . $user->getFullName() . '\'';
			parent::__construct($form_title);
			$this->page->addClass('edituser');
		}

		// Session checking!
		if (empty($_POST))
			Session::resetSessionToken();
		else
			Session::validateSession();

		if ($id_user && !($current_user->isAdmin() && $current_user->getUserId() == $id_user))
			$after_form = '<a href="' . BASEURL . '/edituser/?id=' . $id_user . '&delete&' . Session::getSessionTokenKey() . '=' . Session::getSessionToken() . '" class="btn btn-danger" onclick="return confirm(\'Are you sure you want to delete this user? You cannot undo this!\');">Delete user</a>';
		elseif (!$id_user)
			$after_form = '<button name="submit_and_new" class="btn">Save and add another</button>';
		else
			$after_form = '';

		$form = new Form([
			'request_url' => BASEURL . '/edituser/?' . ($id_user ? 'id=' . $id_user : 'add'),
			'content_below' => $after_form,
			'fields' => [
				'first_name' => [
					'type' => 'text',
					'label' => 'First name',
					'size' => 50,
					'maxlength' => 255,
				],
				'surname' => [
					'type' => 'text',
					'label' => 'Surname',
					'size' => 50,
					'maxlength' => 255,
				],
				'slug' => [
					'type' => 'text',
					'label' => 'URL slug',
					'size' => 50,
					'maxlength' => 255,
				],
				'emailaddress' => [
					'type' => 'text',
					'label' => 'Email address',
					'size' => 50,
					'maxlength' => 255,
				],
				'password1' => [
					'type' => 'password',
					'label' => 'Password',
					'size' => 50,
					'maxlength' => 255,
					'is_optional' => true,
				],
				'password2' => [
					'type' => 'password',
					'label' => 'Password (repeat)',
					'size' => 50,
					'maxlength' => 255,
					'is_optional' => true,
				],
				'is_admin' => [
					'header' => 'Privileges',
					'type' => 'checkbox',
					'label' => 'This user ' . ($id_user ? 'has' : 'should have') . ' administrative privileges.',
					'is_optional' => true,
				],
			],
		]);

		// Create the form, add in default values.
		$form->setData($id_user ? $user->getProps() : $_POST);
		$formview = new FormView($form, $form_title);
		$this->page->adopt($formview);

		if (!empty($_POST))
		{
			$form->verify($_POST);

			// Anything missing?
			if (!empty($form->getMissing()))
				return $formview->adopt(new Alert('Some data missing', 'Please fill out the following fields: ' . implode(', ', $form->getMissing()), 'danger'));

			$data = $form->getData();

			// Just to be on the safe side.
			$data['first_name'] = htmlentities(trim($data['first_name']));
			$data['surname'] = htmlentities(trim($data['surname']));
			$data['emailaddress'] = trim($data['emailaddress']);

			// Make sure there's a slug.
			if (empty($data['slug']))
				$data['slug'] = $data['first_name'];

			// Quick stripping.
			$data['slug'] = strtr(strtolower($data['slug']), [' ' => '-', '--' => '-', '&' => 'and', '=>' => '', "'" => "", ":"=> "", '/' => '-', '\\' => '-']);

			// Checkboxes, fun!
			$data['is_admin'] = empty($data['is_admin']) ? 0 : 1;

			// If it looks like an e-mail address...
			if (!empty($data['emailaddress']) && !preg_match('~^[^ ]+@[^ ]+\.[a-z]+$~', $data['emailaddress']))
				return $formview->adopt(new Alert('Email addresses invalid', 'The email address you entered is not a valid email address.', 'danger'));
			// Check whether email address is already linked to an account in the database -- just not to the account we happen to be editing, of course.
			elseif (!empty($data['emailaddress']) && Member::exists($data['emailaddress']) && !($id_user && $user->getEmailAddress() == $data['emailaddress']))
				return $formview->adopt(new Alert('Email address already in use', 'Another account is already using the e-mail address you entered.', 'danger'));

			// Setting passwords? We'll need two!
			if (!$id_user || !empty($data['password1']) && !empty($data['password2']))
			{
				if (strlen($data['password1']) < 6 || !preg_match('~[^A-z]~', $data['password1']))
					return $formview->adopt(new Alert('Password not acceptable', 'Please fill in a password that is at least six characters long and contains at least one non-alphabetic character (e.g. a number or symbol).', 'danger'));
				elseif ($data['password1'] !== $data['password2'])
					return $formview->adopt(new Alert('Passwords do not match', 'The passwords you entered do not match. Please try again.', 'danger'));
				else
					$data['password'] = $data['password1'];

				unset($data['password1'], $data['password2']);
			}

			// Creating a new user?
			if (!$id_user)
			{
				$return = Member::createNew($data);
				if ($return === false)
					return $formview->adopt(new Alert('Cannot create this user', 'Something went wrong while creating the user...', 'danger'));

				if (isset($_POST['submit_and_new']))
				{
					header('Location: ' . BASEURL . '/edituser/?add');
					exit;
				}
			}
			// Just updating?
			else
				$user->update($data);

			// Redirect to the user management page.
			header('Location: ' . BASEURL . '/manageusers/');
			exit;
		}
	}
}