<?php $pageTitle = t('group_management'); ?>

<?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; ?>

<?php if (!$group && $canCreate): ?>
<div class="page-header">
    <div class="page-header-left">
        <h1 class="page-title"><?= t('group_management') ?></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>
<div class="card" style="margin-top:16px">
    <div class="card-body">
        <p class="text-muted"><?= t('no_group_yet') ?></p>
    </div>
</div>
<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_title') ?></h3>
            <button class="modal-close" data-modal-close="createGroupModal">×</button>
        </div>
        <form method="POST">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="create_group">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('group_name_label') ?> <span style="color:var(--color-danger)">*</span></label>
                    <input type="text" name="group_name" class="form-input" required maxlength="80" placeholder="<?= t('group_name_placeholder') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('description') ?> <span class="text-muted">(<?= t('optional') ?>)</span></label>
                    <textarea name="group_description" class="form-input" rows="2" maxlength="200" placeholder="<?= t('group_desc_placeholder') ?>"></textarea>
                </div>
                <p style="font-size:.8rem;color:var(--text-muted);margin:0"><?= t('group_admin_auto') ?></p>
            </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_btn') ?></button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<?php if ($group): ?>
<div class="page-header">
    <div class="page-header-left">
        <?php if (count($managedGroups) > 1): ?>
        <div style="display:flex;align-items:center;gap:8px">
            <h1 class="page-title"><?= t('group_management') ?>:</h1>
            <form method="GET" style="margin:0">
                <select name="group_id" class="form-select" data-auto-submit style="font-size:1rem;font-weight:600">
                    <?php foreach ($managedGroups as $mg): ?>
                    <option value="<?= $mg['id'] ?>" <?= $mg['id'] == $group['id'] ? 'selected' : '' ?>><?= Helper::e($mg['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        </div>
        <?php else: ?>
        <h1 class="page-title"><?= t('group_management') ?>: <?= Helper::e($group['name']) ?></h1>
        <?php endif; ?>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <!-- KI-Toggle -->
        <form method="POST" style="margin:0">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="toggle_ai">
            <input type="hidden" name="ai_disabled" value="<?= $group['ai_disabled'] ? 0 : 1 ?>">
            <?php if ($group['ai_disabled']): ?>
            <button type="submit" class="btn btn-ghost btn-sm" style="color:var(--color-danger);border-color:var(--color-danger)" title="<?= t('ai_blocked_title') ?>">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
                <?= t('ai_blocked_label') ?>
            </button>
            <?php else: ?>
            <button type="submit" class="btn btn-ghost btn-sm" style="color:var(--color-success);border-color:var(--color-success)" title="<?= t('ai_active_title') ?>" data-confirm-click="<?= Helper::e(t('ai_block_confirm')) ?>">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M12 2a10 10 0 100 20A10 10 0 0012 2z"/><path d="M9 12l2 2 4-4"/></svg>
                <?= t('ai_active_label') ?>
            </button>
            <?php endif; ?>
        </form>
        <?php if ($canCreate): ?>
        <button class="btn btn-ghost btn-sm" data-modal-open="createGroupModal">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
            <?= t('new_group') ?>
        </button>
        <?php else: ?>
        <button class="btn btn-ghost btn-sm" disabled title="<?= t('no_permission_hint') ?>" style="opacity:.45;cursor:not-allowed">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
            <?= t('new_group') ?>
        </button>
        <?php endif; ?>
        <?php $otherMembers = array_filter($members, fn($m) => $m['id'] != Auth::id()); ?>
        <?php if (empty($otherMembers)): ?>
        <form method="POST" style="margin:0" data-confirm="<?= Helper::e(t('delete_group_confirm')) ?>">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="delete_group">
            <button type="submit" class="btn btn-ghost btn-sm" style="color:var(--color-danger);border-color:var(--color-danger)">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4h6v2"/></svg>
                <?= t('delete_group') ?>
            </button>
        </form>
        <?php endif; ?>
        <button class="btn btn-ghost btn-sm" data-modal-open="inviteModal">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="15" height="15"><path d="M4 4h16v16H4z"/><polyline points="22,6 12,13 2,6"/></svg>
            <?= t('invite') ?>
            <?php if (!empty($pendingInvitations)): ?>
            <span style="background:var(--color-warning);color:#fff;border-radius:999px;font-size:.65rem;padding:1px 5px;margin-left:2px"><?= count($pendingInvitations) ?></span>
            <?php endif; ?>
        </button>
    </div>
</div>

<?php if (!empty($group['description'])): ?>
<p style="color:var(--text-muted);margin-bottom:16px"><?= Helper::e($group['description']) ?></p>
<?php endif; ?>

<div class="table-card">
    <table class="data-table">
        <thead>
            <tr>
                <th><?= t('username') ?></th>
                <th><?= t('email') ?></th>
                <th><?= t('group_role') ?></th>
                <th><?= t('last_login') ?></th>
                <th><?= t('actions') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($members as $m): ?>
        <tr>
            <td>
                <div class="user-cell">
                    <?= Helper::avatar(['username' => $m['username'], 'avatar' => $m['avatar'], 'id' => $m['id']], 28) ?>
                    <?= Helper::e($m['username']) ?>
                    <?php if ($m['id'] === Auth::id()): ?>
                    <span class="badge badge-secondary" style="margin-left:4px;font-size:.65rem"><?= t('me_badge') ?></span>
                    <?php endif; ?>
                </div>
            </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><?= $m['last_login'] ? Helper::formatDateTime($m['last_login']) : t('never') ?></td>
            <td>
                <div class="action-btns">
                    <?php if ($m['id'] !== Auth::id()): ?>
                    <button class="btn btn-ghost btn-xs" onclick='openEditUser(<?= htmlspecialchars(json_encode($m), ENT_QUOTES) ?>)'>
                        <?= t('edit') ?>
                    </button>
                    <button class="btn btn-ghost btn-xs" onclick='openResetPw(<?= $m['id'] ?>)'>
                        <?= t('pw_reset_short') ?>
                    </button>
                    <form method="POST" style="display:inline" data-confirm="<?= Helper::e(t('confirm_remove_from_group')) ?>">
                        <?= Helper::csrf() ?>
                        <input type="hidden" name="action" value="remove_from_group">
                        <input type="hidden" name="user_id" value="<?= $m['id'] ?>">
                        <button type="submit" class="btn btn-ghost btn-xs danger"><?= t('remove_from_group') ?></button>
                    </form>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($members)): ?>
        <tr><td colspan="6"><div class="empty-state-small"><?= t('no_group_members') ?></div></td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Invite Modal -->
<div class="modal" id="inviteModal">
    <div class="modal-backdrop" data-modal-close="inviteModal"></div>
    <div class="modal-box" style="max-width:540px">
        <div class="modal-header">
            <h3><?= t('invite') ?></h3>
            <button class="modal-close" data-modal-close="inviteModal">×</button>
        </div>
        <div class="modal-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="<?= $group['id'] ?>">
                <div class="form-group" style="margin:0;flex:1;min-width:180px">
                    <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:130px">
                    <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" style="margin-bottom:1px"><?= t('invite') ?></button>
            </form>
            <?php if (!empty($pendingInvitations)): ?>
            <div style="margin-top:20px">
                <p style="font-size:.8rem;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></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 style="font-size:.82rem"><?= 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="<?= $group['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 class="modal-footer">
            <button type="button" class="btn btn-ghost" data-modal-close="inviteModal"><?= t('cancel') ?></button>
        </div>
    </div>
</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('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>
            </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('group_role') ?></label>
                    <select name="group_role" id="editGroupRole" class="form-select">
                        <option value=""><?= t('group_member') ?></option>
                        <option value="admin"><?= t('group_admin') ?></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(u) {
    document.getElementById('editUserId').value    = u.id;
    document.getElementById('editGroupRole').value = u.group_role || '';
    openModal('editUserModal');
}
function openResetPw(userId) {
    document.getElementById('resetPwUserId').value = userId;
    openModal('resetPwModal');
}
</script>

<!-- 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_title') ?></h3>
            <button class="modal-close" data-modal-close="createGroupModal">×</button>
        </div>
        <form method="POST">
            <?= Helper::csrf() ?>
            <input type="hidden" name="action" value="create_group">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label"><?= t('group_name_label') ?> <span style="color:var(--color-danger)">*</span></label>
                    <input type="text" name="group_name" class="form-input" required maxlength="80" placeholder="<?= t('group_name_placeholder') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label"><?= t('description') ?> <span class="text-muted">(<?= t('optional') ?>)</span></label>
                    <textarea name="group_description" class="form-input" rows="2" maxlength="200" placeholder="<?= t('group_desc_placeholder') ?>"></textarea>
                </div>
                <p style="font-size:.8rem;color:var(--text-muted);margin:0"><?= t('group_admin_auto') ?></p>
            </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_btn') ?></button>
            </div>
        </form>
    </div>
</div>
<?php endif; // $group ?>
