<?php
/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

print sly_Helper_Message::renderFlashMessage();

$user      = sly_Util_User::getCurrentUser();
$isAdmin   = $user->isAdmin();
$canAdd    = $isAdmin || $user->hasRight('user', 'add');
$canEdit   = $isAdmin || $user->hasRight('user', 'edit');
$canDelete = $isAdmin || $user->hasRight('user', 'delete');

if ($canAdd) {
	$link  = $_router->getPlainUrl(null, 'add');
	$title = t('add_user');
	$id    = 'sly-user-add';
}
else {
	$link  = '';
	$title = '';
	$id    = '';
}

$table = new sly_Table('users');
$table->addColumn(sly_Table_Column::sprite($id, $link, $title, 'sly-col-icon'));
$table->addColumn(sly_Table_Column::factory(t('name'), 'sly-col-name'));
$table->addColumn(sly_Table_Column::factory(t('username'), 'sly-col-username'));
$table->addColumn(sly_Table_Column::factory(t('last_login'), 'sly-col-last-login'));

if ($canDelete) {
	$table->addColumn(sly_Table_Column::factory(t('function'), 'sly-col-func'));
}

$table->enableSearching(true, array('page' => 'user'));
$table->setIsEmpty(empty($users));
$table->setEmptyNotice(t('no_users_found'));
$table->openBuffer();

$tdIcon    = '';
$user      = sly_Util_User::getCurrentUser();
$currentID = $user->getId();
$action    = $canEdit ? 'edit' : 'view';

foreach ($users as $user) {
	$id    = (int) $user->getId();
	$name  = $user->getName();
	$login = $user->getLogin();
	$try   = $user->getLastTryDate();

	if (empty($name)) {
		$name = $login;
	}

	$try = ($try === 0 || $try === null) ? t('never') : sly_Util_String::formatDatetime($try);

	?>
	<tr>
		<td class="sly-col-icon sly-icon">
			<a href="<?php echo $_router->getUrl(null, $action, array('id' => $id)) ?>">
				<img src="assets/empty.png" class="sly-icon sly-sprite sly-sprite-sly-user" alt="" title="<?php echo t($canEdit ? 'edit' : 'show') ?>" />
			</a>
		</td>
		<td class="sly-col-name"><a href="<?php echo $_router->getUrl(null, $action, array('id' => $id)) ?>"><?php echo sly_html($name) ?></a></td>
		<td class="sly-col-username"><?php echo sly_html($user->getLogin()) ?></td>
		<td class="sly-col-last-login"><?php echo $try ?></td>

		<?php if ($canDelete && ($id === $currentID || (!$isAdmin && $user->isAdmin()))): ?>
		<td class="sly-col-func"><span class="sly-na"><?php echo t('delete') ?></span></td>
		<?php elseif ($canDelete): ?>
		<td class="sly-col-func"><a class="sly-action sly-delete sly-postlink" href="<?php echo $_router->getUrl(null, 'delete', array('id' => $id)) ?>"><?php echo t('delete') ?></a></td>
		<?php endif ?>
	</tr>
	<?php
}

$table->closeBuffer();
print $table->render($total);
