<?php $pageTitle = t('users'); ?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/dashboard" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('dashboard') ?>
        </a>
        <h1 class="page-title"><?= t('users') ?></h1>
    </div>
    <div style="display:flex;gap:8px">
        <a href="/admin/groups" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
            <?= t('groups') ?>
        </a>
        <button class="btn btn-primary" data-modal-open="createUserModal">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M12 5v14M5 12h14"/></svg>
            <?= t('new_user') ?>
        </button>
    </div>
</div>

<?php if (!empty($success)): ?>
<div class="alert alert-success"><?= Helper::e($success) ?></div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div class="alert alert-error"><?php foreach ($errors as $e): ?><div><?= Helper::e($e) ?></div><?php endforeach; ?></div>
<?php endif; ?>

<form method="GET" class="filter-bar">
    <input type="text" name="search" class="form-input filter-search"
           placeholder="<?= t('search') ?>..." value="<?= Helper::e($search) ?>">
    <button type="submit" class="btn btn-ghost btn-sm"><?= t('search') ?></button>
</form>

<?php
    // Sort-link helper. Toggles direction when re-clicking the active column,
    // otherwise defaults to asc. Preserves the current search filter.
    $_sort    = $sort    ?? 'username';
    $_sortDir = $sortDir ?? 'asc';
    $sortLink = function (string $col, string $label) use ($_sort, $_sortDir, $search): string {
        $nextDir = ($_sort === $col && $_sortDir === 'asc') ? 'desc' : 'asc';
        $arrow   = $_sort === $col ? ($_sortDir === 'asc' ? '↑' : '↓') : '';
        $qs = http_build_query(array_filter(['search' => $search, 'sort' => $col, 'dir' => $nextDir], fn($v) => $v !== '' && $v !== null));
        return '<a href="?' . htmlspecialchars($qs) . '" class="sort-link' . ($_sort === $col ? ' active' : '') . '">'
             . htmlspecialchars($label)
             . ($arrow !== '' ? ' <span class="sort-arrow">' . $arrow . '</span>' : '')
             . '</a>';
    };
?>
<div class="table-card">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= $sortLink('username',   Lang::get('username')) ?></th>
                <th><?= $sortLink('email',      Lang::get('email')) ?></th>
                <th><?= $sortLink('role',       Lang::get('user_role')) ?></th>
                <th><?= $sortLink('group_name', Lang::get('group')) ?></th>
                <th><?= $sortLink('is_active',  Lang::get('status_label')) ?></th>
                <th><?= $sortLink('last_login', Lang::get('last_login')) ?></th>
                <th><?= t('actions') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
        <tr>
            <td>
                <div class="user-cell">
                    <?= Helper::avatar(['username' => $u['username'], 'avatar' => $u['avatar'], 'id' => $u['id']], 28) ?>
                    <?= Helper::e($u['username']) ?>
                </div>
            </td>
            <td><?= Helper::e($u['email']) ?></td>
            <td>
                <span class="badge <?= $u['role'] === 'admin' ? 'badge-primary' : 'badge-secondary' ?>">
                    <?= t('role_' . $u['role']) ?>
                </span>
            </td>
            <td>
                <?php if ($u['group_name']): ?>
                <span style="font-size:.8rem">
                    <?= Helper::e($u['group_name']) ?>
                    <?php if ($u['group_role'] === 'admin'): ?>
                    <span class="badge badge-primary" style="font-size:.65rem;margin-left:4px"><?= t('group_admin') ?></span>
                    <?php endif; ?>
                </span>
                <?php else: ?>
                <span style="color:var(--text-muted);font-size:.8rem">–</span>
                <?php endif; ?>
            </td>
            <td>
                <span class="badge <?= $u['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                    <?= $u['is_active'] ? t('user_active') : t('user_inactive') ?>
                </span>
            </td>
            <td><?= $u['last_login'] ? Helper::formatDateTime($u['last_login']) : t('never') ?></td>
            <td>
                <div class="action-btns">
                    <button class="btn btn-ghost btn-xs" onclick='openEditUser(<?= htmlspecialchars(json_encode(array_intersect_key($u, array_flip(['id','username','email','role','is_active','language','theme']))), ENT_QUOTES, 'UTF-8') ?>)'>
                        <?= t('edit') ?>
                    </button>
                    <button class="btn btn-ghost btn-xs" onclick='openResetPw(<?= $u['id'] ?>)'>
                        <?= t('pw_reset_short') ?>
                    </button>
                    <?php PluginManager::fire('admin_user_actions', $u); ?>
                    <?php if ($u['id'] !== Auth::id()): ?>
                    <form method="POST" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                        <?= Helper::csrf() ?>
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                        <button type="submit" class="btn btn-ghost btn-xs danger"><?= t('delete') ?></button>
                    </form>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Create User Modal -->
<div class="modal" id="createUserModal">
    <div class="modal-backdrop" data-modal-close="createUserModal"></div>
    <div class="modal-box">
        <div class="modal-header">
            <h3><?= t('new_user') ?></h3>
            <button class="modal-close" data-modal-close="createUserModal">×</button>
        </div>
        <form method="POST">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="create">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('username') ?></label>
                    <input type="text" name="username" class="form-input" required minlength="3">
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('email') ?></label>
                    <input type="email" name="email" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('password') ?></label>
                    <input type="password" name="password" class="form-input" required minlength="8">
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('user_role') ?></label>
                    <select name="role" class="form-select">
                        <option value="user"><?= t('role_user') ?></option>
                        <option value="admin"><?= t('role_admin') ?></option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-modal-close="createUserModal"><?= t('cancel') ?></button>
                <button type="submit" class="btn btn-primary"><?= t('create') ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Edit User Modal -->
<div class="modal" id="editUserModal">
    <div class="modal-backdrop" data-modal-close="editUserModal"></div>
    <div class="modal-box">
        <div class="modal-header">
            <h3><?= t('edit') ?></h3>
            <button class="modal-close" data-modal-close="editUserModal">×</button>
        </div>
        <form method="POST" id="editUserForm">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="user_id" id="editUserId">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('username') ?></label>
                    <input type="text" name="username" id="editUsername" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('email') ?></label>
                    <input type="email" name="email" id="editEmail" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('user_role') ?></label>
                    <select name="role" id="editRole" class="form-select">
                        <option value="user"><?= t('role_user') ?></option>
                        <option value="admin"><?= t('role_admin') ?></option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('status_label') ?></label>
                    <select name="is_active" id="editActive" class="form-select">
                        <option value="1"><?= t('user_active') ?></option>
                        <option value="0"><?= t('user_inactive') ?></option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-modal-close="editUserModal"><?= t('cancel') ?></button>
                <button type="submit" class="btn btn-primary"><?= t('save') ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Reset Password Modal -->
<div class="modal" id="resetPwModal">
    <div class="modal-backdrop" data-modal-close="resetPwModal"></div>
    <div class="modal-box">
        <div class="modal-header">
            <h3><?= t('reset_password_title') ?></h3>
            <button class="modal-close" data-modal-close="resetPwModal">×</button>
        </div>
        <form method="POST">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="reset_password">
            <input type="hidden" name="user_id" id="resetPwUserId">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('new_password') ?></label>
                    <input type="password" name="new_password" class="form-input" required minlength="8">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-modal-close="resetPwModal"><?= t('cancel') ?></button>
                <button type="submit" class="btn btn-primary"><?= t('reset_btn') ?></button>
            </div>
        </form>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
function openEditUser(user) {
    document.getElementById('editUserId').value    = user.id;
    document.getElementById('editUsername').value  = user.username;
    document.getElementById('editEmail').value     = user.email;
    document.getElementById('editRole').value      = user.role;
    document.getElementById('editActive').value    = user.is_active;
    openModal('editUserModal');
}
function openResetPw(userId) {
    document.getElementById('resetPwUserId').value = userId;
    openModal('resetPwModal');
}
</script>
<style>
.sort-link { color: inherit; text-decoration: none; display: inline-flex; align-items: center; gap: 4px; }
.sort-link:hover { color: var(--color-primary); }
.sort-link.active { color: var(--color-primary); }
.sort-arrow { font-size: .75em; opacity: .8; }
</style>
