<?php
$translate = $this->plugin('translate');
$this->headScript()->appendFile($this->assetUrl('js/site-users.js', 'Omeka'));
$this->htmlElement('body')->appendAttribute('class', 'sites users');
$form->prepare();
$escape = $this->plugin('escapeHtml');
$delete = $translate('Delete');
$restore = $translate('Restore');
$roles = [
    'viewer' => $translate('Viewer'),
    'editor' => $translate('Creator'),
    'admin' => $translate('Manager'),
];
$userRowTemplate = '
<tr class="resource-row">
    <td class="data-value" data-row-key="child-search"></td>
    <td><select name="o:site_permission[__index__][o:role]">';
foreach ($roles as $key => $value) {
    $userRowTemplate .= '<option value="' . $key . '">' . $value . '</option>';
}
$userRowTemplate .= '</select></td>
    <td>
        <ul class="actions">
            <li>' . $this->hyperlink('', '#', ['class' => 'o-icon-delete', 'title' => $delete]) . '</li>
        </ul>
        <input type="hidden" class="resource-id" name="o:site_permission[__index__][o:user][o:id]">
    </td>
</tr>
';
$sitePermissions = $site->sitePermissions();
$users = [];
foreach ($sitePermissions as $sitePermission) {
  $user = $sitePermission->user();
  $users[] = [
    'id' => $user->id(),
    'role' => $sitePermission->role(),
  ];
}
?>

<?php echo $this->pageTitle($translate('User permissions'), 1, $translate('Sites')); ?>

<?php echo $this->form()->openTag($form); ?>
<?php echo $this->formCollection($form, false); ?>

<div id="page-actions">
    <?php echo $this->cancelButton(); ?>
    <button><?php echo $translate('Save'); ?></button>
</div>

<table id="site-user-permissions"  data-row-template="<?php echo $escape($userRowTemplate); ?>" data-existing-rows="<?php echo $this->escapeHtml(json_encode($users)); ?>" class="selector-table tablesaw tablesaw-stack <?php echo (count($sitePermissions) > 0) ? '' : 'empty'; ?>" data-tablesaw-mode="stack">
    <thead>
        <tr>
            <th scope="col"><?php echo $translate('User'); ?></th>
            <th scope="col"><?php echo $translate('Role'); ?></th>
            <th></th>
        </tr>
    </thead>
    <tbody class="resource-rows"></tbody>
</table>
<div class="no-resources">
    <p><?php echo $translate('This site has no users. Add users using the interface to the right.'); ?></p>
</div>
<button id="site-user-selector-button" class="mobile-only"><?php echo $translate('Add new user'); ?></button>
<?php echo $this->userSelector($translate('Click on a user to add them to the site.')); ?>

<?php echo $this->form()->closeTag(); ?>

<script>
  Omeka.initializeSelector('#site-user-permissions', '#user-selector');
</script>
