<?php $pageTitle = t('groups'); ?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/admin/users" 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('users') ?>
        </a>
        <h1 class="page-title"><?= t('groups') ?></h1>
    </div>
    <button class="btn btn-primary" data-modal-open="createGroupModal">
        <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_group') ?>
    </button>
</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; ?>

<div class="dashboard-grid" style="grid-template-columns: 280px 1fr; align-items: start;">
    <!-- Group list -->
    <div class="card">
        <div class="card-header"><h2 class="card-title"><?= t('groups') ?></h2></div>
        <div class="card-body p-0">
            <?php if (empty($groups)): ?>
            <div class="empty-state-small"><?= t('no_groups') ?></div>
            <?php else: ?>
            <div class="task-list">
                <?php foreach ($groups as $g): ?>
                <a href="/admin/groups?group_id=<?= $g['id'] ?>"
                   class="task-list-item <?= ($selectedGroup && $selectedGroup['id'] == $g['id']) ? 'active' : '' ?>"
                   style="text-decoration:none">
                    <div class="task-list-body">
                        <div class="task-list-title"><?= Helper::e($g['name']) ?></div>
                        <div class="task-list-meta">#<?= $g['id'] ?> · <?= $g['member_count'] ?> <?= t('group_members') ?></div>
                    </div>
                    <div style="display:flex;gap:4px">
                        <button class="btn btn-ghost btn-xs" onclick='event.preventDefault();openEditGroup(<?= htmlspecialchars(json_encode($g), ENT_QUOTES) ?>)'>
                            <?= t('edit') ?>
                        </button>
                        <?php if ($g['member_count'] == 0): ?>
                        <form method="POST" data-confirm="<?= Helper::e(t('confirm_delete')) ?>">
                            <?= Helper::csrf() ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="group_id" value="<?= $g['id'] ?>">
                            <button class="btn btn-ghost btn-xs danger" data-stop-propagation><?= t('delete') ?></button>
                        </form>
                        <?php endif; ?>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Group detail -->
    <div>
        <?php if ($selectedGroup): ?>
        <div class="card" style="margin-bottom:16px">
            <div class="card-header">
                <h2 class="card-title"><?= Helper::e($selectedGroup['name']) ?> – <?= t('group_members') ?></h2>
            </div>
            <div class="card-body p-0">
                <?php if (empty($groupMembers)): ?>
                <div class="empty-state-small"><?= t('no_group_members') ?></div>
                <?php else: ?>
                <table class="data-table">
                    <thead><tr>
                        <th><?= t('username') ?></th>
                        <th><?= t('email') ?></th>
                        <th><?= t('group_role') ?></th>
                        <th><?= t('status_label') ?></th>
                        <th><?= t('actions') ?></th>
                    </tr></thead>
                    <tbody>
                    <?php foreach ($groupMembers as $m): ?>
                    <tr>
                        <td><?= Helper::e($m['username']) ?></td>
                        <td><?= Helper::e($m['email']) ?></td>
                        <td>
                            <?php if ($m['group_role'] === 'admin'): ?>
                            <span class="badge badge-primary"><?= t('group_admin') ?></span>
                            <?php else: ?>
                            <span class="badge badge-secondary"><?= t('group_member') ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge <?= $m['is_active'] ? 'badge-success' : 'badge-danger' ?>">
                                <?= $m['is_active'] ? t('user_active') : t('user_inactive') ?>
                            </span>
                        </td>
                        <td>
                            <form method="POST" style="display:inline">
                                <?= Helper::csrf() ?>
                                <input type="hidden" name="action" value="assign_user">
                                <input type="hidden" name="user_id" value="<?= $m['id'] ?>">
                                <input type="hidden" name="group_id" value="0">
                                <input type="hidden" name="current_group_id" value="<?= $selectedGroup['id'] ?>">
                                <input type="hidden" name="group_role" value="">
                                <button class="btn btn-ghost btn-xs danger" data-confirm-click="<?= Helper::e(t('confirm_delete')) ?>"><?= t('remove') ?></button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>

        <!-- Assign unassigned users -->
        <?php if (!empty($unassigned)): ?>
        <div class="card">
            <div class="card-header"><h2 class="card-title"><?= t('assign_group') ?></h2></div>
            <div class="card-body">
                <form method="POST" action="/admin/groups?group_id=<?= $selectedGroup['id'] ?>" style="display:flex;gap:8px;flex-wrap:wrap;align-items:flex-end">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="action" value="assign_user">
                    <input type="hidden" name="group_id" value="<?= $selectedGroup['id'] ?>">
                    <div class="form-group" style="margin:0;flex:1;min-width:160px">
                        <label class="form-label"><?= t('users') ?></label>
                        <select name="user_id" class="form-select" required>
                            <option value="">– <?= t('users') ?> –</option>
                            <?php foreach ($unassigned as $u): ?>
                            <option value="<?= $u['id'] ?>"><?= Helper::e($u['username']) ?> (<?= Helper::e($u['email']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;min-width:140px">
                        <label class="form-label"><?= t('group_role') ?></label>
                        <select name="group_role" class="form-select">
                            <option value=""><?= t('group_member') ?></option>
                            <option value="admin"><?= t('group_admin') ?></option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><?= t('assign_group') ?></button>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <!-- Invite new user -->
        <div class="card" style="margin-top:16px">
            <div class="card-header"><h2 class="card-title"><?= t('invite') ?></h2></div>
            <div class="card-body">
                <form method="POST" action="/invite/send" style="display:flex;gap:8px;flex-wrap:wrap;align-items:flex-end">
                    <?= Helper::csrf() ?>
                    <input type="hidden" name="group_id" value="<?= $selectedGroup['id'] ?>">
                    <div class="form-group" style="margin:0;flex:1;min-width:200px">
                        <label class="form-label"><?= t('email') ?></label>
                        <input type="email" name="email" class="form-input" required placeholder="name@beispiel.de">
                    </div>
                    <div class="form-group" style="margin:0;min-width:140px">
                        <label class="form-label"><?= t('group_role') ?></label>
                        <select name="group_role" class="form-select">
                            <option value=""><?= t('group_member') ?></option>
                            <option value="admin"><?= t('group_admin') ?></option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><?= t('invite') ?></button>
                </form>
                <?php if (!empty($pendingInvitations)): ?>
                <div style="margin-top:16px">
                    <p style="font-size:.875rem;font-weight:600;color:var(--text-muted);margin-bottom:8px"><?= t('invite_pending') ?></p>
                    <table class="data-table">
                        <thead><tr>
                            <th><?= t('email') ?></th>
                            <th><?= t('group_role') ?></th>
                            <th><?= t('invite_expires') ?></th>
                            <th><?= t('actions') ?></th>
                        </tr></thead>
                        <tbody>
                        <?php foreach ($pendingInvitations as $inv): ?>
                        <tr>
                            <td><?= Helper::e($inv['email']) ?></td>
                            <td><?= $inv['group_role'] === 'admin' ? t('group_admin') : t('group_member') ?></td>
                            <td><?= date('d.m.Y H:i', $inv['expires_at']) ?></td>
                            <td>
                                <form method="POST" action="/invite/send">
                                    <?= Helper::csrf() ?>
                                    <input type="hidden" name="group_id" value="<?= $selectedGroup['id'] ?>">
                                    <input type="hidden" name="action" value="revoke">
                                    <input type="hidden" name="invitation_id" value="<?= $inv['id'] ?>">
                                    <button class="btn btn-ghost btn-xs danger" data-confirm-click="<?= Helper::e(t('confirm_delete')) ?>"><?= t('invite_revoke') ?></button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <?php else: ?>
        <div class="card">
            <div class="card-body">
                <p style="color:var(--text-muted)"><?= t('groups') ?>: <?= t('no_groups') ?> – wähle eine Gruppe aus der Liste oder lege eine neue an.</p>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Create Group Modal -->
<div class="modal" id="createGroupModal">
    <div class="modal-backdrop" data-modal-close="createGroupModal"></div>
    <div class="modal-box">
        <div class="modal-header">
            <h3><?= t('new_group') ?></h3>
            <button class="modal-close" data-modal-close="createGroupModal">×</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('group_name') ?> *</label>
                    <input type="text" name="name" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('group_description') ?></label>
                    <input type="text" name="description" class="form-input">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-modal-close="createGroupModal"><?= t('cancel') ?></button>
                <button type="submit" class="btn btn-primary"><?= t('create') ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Group Modal -->
<div class="modal" id="editGroupModal">
    <div class="modal-backdrop" data-modal-close="editGroupModal"></div>
    <div class="modal-box">
        <div class="modal-header">
            <h3><?= t('edit') ?></h3>
            <button class="modal-close" data-modal-close="editGroupModal">×</button>
        </div>
        <form method="POST">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="group_id" id="editGroupId">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('group_name') ?> *</label>
                    <input type="text" name="name" id="editGroupName" class="form-input" required>
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('group_description') ?></label>
                    <input type="text" name="description" id="editGroupDesc" class="form-input">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-ghost" data-modal-close="editGroupModal"><?= t('cancel') ?></button>
                <button type="submit" class="btn btn-primary"><?= t('save') ?></button>
            </div>
        </form>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
function openEditGroup(g) {
    document.getElementById('editGroupId').value   = g.id;
    document.getElementById('editGroupName').value = g.name;
    document.getElementById('editGroupDesc').value = g.description || '';
    openModal('editGroupModal');
}
</script>
