File size: 18,443 Bytes
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128f124
12f0507
128f124
12f0507
 
128f124
 
 
 
 
 
 
12f0507
 
 
128f124
 
 
 
 
 
 
12f0507
 
 
128f124
 
 
12f0507
 
 
 
128f124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// ===== Admin Panel Module =====

const Admin = {
    currentTab: 'dashboard',

    async render() {
        if (!Auth.isAdmin()) {
            return '<div class="container"><h2>Acesso negado</h2><p>Area restrita a administradores.</p></div>';
        }

        const stats = await this.loadStats();
        return `
            <div class="container">
                <h1 class="page-title">Painel Administrativo</h1>
                <div class="admin-tabs">
                    <button class="admin-tab active" data-tab="dashboard" onclick="Admin.switchTab('dashboard')">Dashboard</button>
                    <button class="admin-tab" data-tab="users" onclick="Admin.switchTab('users')">Usuarios</button>
                    <button class="admin-tab" data-tab="sessions" onclick="Admin.switchTab('sessions')">Sessoes Ativas</button>
                    <button class="admin-tab" data-tab="logs" onclick="Admin.switchTab('logs')">Historico</button>
                </div>
                <div id="admin-content">
                    ${this.renderDashboard(stats)}
                </div>
            </div>

            <!-- Create User Modal -->
            <div class="modal-overlay" id="modal-create-user">
                <div class="modal">
                    <h2>Novo Usuario</h2>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="email" id="new-user-email" placeholder="usuario@email.com">
                    </div>
                    <div class="form-group">
                        <label>Nome</label>
                        <input type="text" id="new-user-name" placeholder="Nome do usuario">
                    </div>
                    <div class="form-group">
                        <label>Senha</label>
                        <input type="password" id="new-user-password" placeholder="Senha">
                    </div>
                    <div class="modal-actions">
                        <button class="btn btn-secondary" onclick="Admin.closeModal('modal-create-user')">Cancelar</button>
                        <button class="btn btn-primary" style="width:auto" onclick="Admin.createUser()">Criar Usuario</button>
                    </div>
                </div>
            </div>

            <!-- Batch Create Modal -->
            <div class="modal-overlay" id="modal-batch-create">
                <div class="modal" style="max-width:600px">
                    <h2>Cadastro em Lote</h2>
                    <div id="batch-form">
                        <div class="form-group">
                            <label>Lista de alunos (um por linha)</label>
                            <textarea id="batch-input" rows="10" placeholder="email@exemplo.com, Nome do Aluno&#10;outro@email.com, Outro Nome&#10;apenas@email.com" style="width:100%;font-family:monospace;font-size:13px;padding:10px;border:1px solid #ddd;border-radius:8px;resize:vertical;"></textarea>
                            <small style="color:var(--text-sec);display:block;margin-top:6px;">Formato: email ou email, nome (um por linha). Senhas serao geradas automaticamente.</small>
                        </div>
                        <div class="modal-actions">
                            <button class="btn btn-secondary" onclick="Admin.closeModal('modal-batch-create')">Cancelar</button>
                            <button class="btn btn-primary" style="width:auto" onclick="Admin.batchCreate()">Criar Usuarios</button>
                        </div>
                    </div>
                    <div id="batch-results" style="display:none">
                        <div id="batch-results-content"></div>
                        <div class="modal-actions">
                            <button class="btn btn-secondary" onclick="Admin.closeBatchResults()">Fechar</button>
                            <button class="btn btn-primary" style="width:auto" onclick="Admin.copyBatchResults()">Copiar Tabela</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Password Result Modal -->
            <div class="modal-overlay" id="modal-password-result">
                <div class="modal">
                    <h2>Senha Redefinida</h2>
                    <div id="password-result-content"></div>
                    <div class="modal-actions">
                        <button class="btn btn-secondary" onclick="Admin.closeModal('modal-password-result')">Fechar</button>
                        <button class="btn btn-primary" style="width:auto" onclick="Admin.copyPasswordResult()">Copiar</button>
                    </div>
                </div>
            </div>
        `;
    },

    async switchTab(tab) {
        this.currentTab = tab;
        document.querySelectorAll('.admin-tab').forEach(t => {
            t.classList.toggle('active', t.dataset.tab === tab);
        });

        const content = document.getElementById('admin-content');
        content.innerHTML = '<div class="loading"><div class="spinner"></div>Carregando...</div>';

        try {
            switch (tab) {
                case 'dashboard':
                    const stats = await this.loadStats();
                    content.innerHTML = this.renderDashboard(stats);
                    break;
                case 'users':
                    const users = await this.loadUsers();
                    content.innerHTML = this.renderUsers(users);
                    break;
                case 'sessions':
                    const sessions = await this.loadSessions();
                    content.innerHTML = this.renderSessions(sessions);
                    break;
                case 'logs':
                    const logs = await this.loadLogs();
                    content.innerHTML = this.renderLogs(logs);
                    break;
            }
        } catch (e) {
            content.innerHTML = `<div class="loading">Erro: ${e.message}</div>`;
        }
    },

    async loadStats() {
        const res = await fetch('/api/admin/stats', { headers: Auth.headers() });
        return await res.json();
    },

    async loadUsers() {
        const res = await fetch('/api/admin/users', { headers: Auth.headers() });
        const data = await res.json();
        return data.users;
    },

    async loadSessions() {
        const res = await fetch('/api/admin/sessions', { headers: Auth.headers() });
        const data = await res.json();
        return data.sessions;
    },

    async loadLogs(page = 1) {
        const res = await fetch(`/api/admin/logs?page=${page}&per_page=30`, { headers: Auth.headers() });
        return await res.json();
    },

    renderDashboard(stats) {
        return `
            <div class="stat-cards">
                <div class="stat-card"><div class="stat-value">${stats.total_users}</div><div class="stat-label">Usuarios Ativos</div></div>
                <div class="stat-card"><div class="stat-value">${stats.active_sessions}</div><div class="stat-label">Sessoes Online</div></div>
                <div class="stat-card"><div class="stat-value">${stats.total_questions.toLocaleString('pt-BR')}</div><div class="stat-label">Questoes</div></div>
                <div class="stat-card"><div class="stat-value">${stats.total_topics}</div><div class="stat-label">Topicos</div></div>
            </div>
        `;
    },

    renderUsers(users) {
        let html = `
            <div style="margin-bottom:16px; display:flex; justify-content:flex-end; gap:8px;">
                <button class="btn btn-secondary" style="width:auto" onclick="Admin.openModal('modal-batch-create')">Cadastro em Lote</button>
                <button class="btn btn-primary" style="width:auto" onclick="Admin.openModal('modal-create-user')">+ Novo Aluno</button>
            </div>
            <table class="data-table">
                <thead><tr><th>Email</th><th>Nome</th><th>Role</th><th>Status</th><th>Sessoes</th><th>Tempo Total</th><th>Ultimo Login</th><th>Acoes</th></tr></thead>
                <tbody>
        `;
        for (const u of users) {
            const totalTime = u.total_time ? this.formatDuration(u.total_time) : 'β€”';
            const lastLogin = u.last_login ? new Date(u.last_login).toLocaleString('pt-BR') : 'β€”';
            html += `
                <tr>
                    <td>${this.esc(u.email)}</td>
                    <td>${this.esc(u.display_name || 'β€”')}</td>
                    <td><span class="badge ${u.role === 'admin' ? 'badge-admin' : ''}">${u.role}</span></td>
                    <td><span class="badge ${u.is_active ? 'badge-active' : 'badge-inactive'}">${u.is_active ? 'Ativo' : 'Inativo'}</span></td>
                    <td>${u.total_sessions || 0}</td>
                    <td>${totalTime}</td>
                    <td>${lastLogin}</td>
                    <td style="display:flex;gap:4px;flex-wrap:wrap;">
                        <button class="btn btn-secondary btn-sm" onclick="Admin.resetPassword(${u.id}, '${u.email.replace(/'/g,"\\'")}')">&#128273; Senha</button>
                        ${u.is_active
                            ? `<button class="btn btn-danger btn-sm" onclick="Admin.toggleUser(${u.id}, false)">Desativar</button>`
                            : `<button class="btn btn-secondary btn-sm" onclick="Admin.toggleUser(${u.id}, true)">Ativar</button>`}
                    </td>
                </tr>`;
        }
        html += '</tbody></table>';
        return html;
    },

    renderSessions(sessions) {
        if (sessions.length === 0) return '<div class="loading">Nenhuma sessao ativa no momento.</div>';
        let html = `<table class="data-table"><thead><tr><th>Usuario</th><th>IP</th><th>Dispositivo</th><th>Login</th><th>Ultimo Heartbeat</th><th>Acoes</th></tr></thead><tbody>`;
        for (const s of sessions) {
            html += `<tr>
                <td><strong>${this.esc(s.email)}</strong>${s.display_name ? `<br><small>${this.esc(s.display_name)}</small>` : ''}</td>
                <td><code>${this.esc(s.ip_address || 'β€”')}</code></td>
                <td><small>${this.esc(s.device_info || 'β€”')}</small></td>
                <td>${new Date(s.login_time).toLocaleString('pt-BR')}</td>
                <td>${new Date(s.last_heartbeat).toLocaleString('pt-BR')}</td>
                <td><button class="btn btn-danger btn-sm" onclick="Admin.kickSession(${s.id})">Encerrar</button></td>
            </tr>`;
        }
        html += '</tbody></table>';
        return html;
    },

    renderLogs(data) {
        const { logs, total } = data;
        if (logs.length === 0) return '<div class="loading">Nenhum registro encontrado.</div>';
        const kickedLabels = { 'self': 'Proprio', 'new_login': 'Novo login', 'timeout': 'Timeout', 'admin_kick': 'Admin', 'admin_deactivated': 'Desativado' };
        let html = `<p style="margin-bottom:12px;color:var(--text-sec)">Total: ${total} registros</p>
            <table class="data-table"><thead><tr><th>Email</th><th>IP</th><th>Dispositivo</th><th>Login</th><th>Logout</th><th>Duracao</th><th>Encerrado por</th></tr></thead><tbody>`;
        for (const l of logs) {
            html += `<tr>
                <td>${this.esc(l.email || 'β€”')}</td>
                <td><code>${this.esc(l.ip_address || 'β€”')}</code></td>
                <td><small>${this.esc(l.device_info || 'β€”')}</small></td>
                <td>${l.login_time ? new Date(l.login_time).toLocaleString('pt-BR') : 'β€”'}</td>
                <td>${l.logout_time ? new Date(l.logout_time).toLocaleString('pt-BR') : 'β€”'}</td>
                <td>${l.duration_seconds ? this.formatDuration(l.duration_seconds) : 'β€”'}</td>
                <td><span class="badge">${kickedLabels[l.kicked_by] || l.kicked_by || 'β€”'}</span></td>
            </tr>`;
        }
        html += '</tbody></table>';
        return html;
    },

    async createUser() {
        const email = document.getElementById('new-user-email').value.trim();
        const name = document.getElementById('new-user-name').value.trim();
        const password = document.getElementById('new-user-password').value;
        if (!email || !password) { alert('Email e senha sao obrigatorios'); return; }
        try {
            const res = await fetch('/api/admin/users', { method: 'POST', headers: Auth.headers(), body: JSON.stringify({ email, password, display_name: name }) });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error);
            alert(data.message);
            this.closeModal('modal-create-user');
            this.switchTab('users');
        } catch (e) { alert('Erro: ' + e.message); }
    },

    async resetPassword(uid, email) {
        if (!confirm(`Redefinir senha de ${email}?\nUma nova senha aleatoria sera gerada.`)) return;
        try {
            const res = await fetch(`/api/admin/users/${uid}/reset-password`, { method: 'POST', headers: Auth.headers() });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error);
            this._lastPasswordResult = `${data.email}: ${data.new_password}`;
            document.getElementById('password-result-content').innerHTML = `
                <p style="margin-bottom:12px">Nova senha gerada para <strong>${this.esc(data.email)}</strong>:</p>
                <code style="display:block;background:#f5f5f5;padding:12px;border-radius:8px;font-size:16px;text-align:center;user-select:all">${this.esc(data.new_password)}</code>
                <p style="margin-top:12px;color:var(--text-sec);font-size:13px">Compartilhe esta senha com o usuario. Ela nao podera ser visualizada novamente.</p>
            `;
            this.openModal('modal-password-result');
        } catch (e) { alert('Erro: ' + e.message); }
    },

    async copyPasswordResult() {
        if (this._lastPasswordResult) {
            await navigator.clipboard.writeText(this._lastPasswordResult);
            alert('Copiado!');
        }
    },

    async toggleUser(uid, activate) {
        if (!confirm(activate ? 'Ativar este usuario?' : 'Desativar este usuario?')) return;
        try {
            const res = await fetch(`/api/admin/users/${uid}/toggle`, { method: 'PUT', headers: Auth.headers() });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Erro ao atualizar');
            this.switchTab('users');
        } catch (e) { alert('Erro: ' + e.message); }
    },

    async batchCreate() {
        const raw = document.getElementById('batch-input').value.trim();
        if (!raw) { alert('Insira pelo menos um email'); return; }

        const lines = raw.split('\n').filter(l => l.trim());
        const users = lines.map(line => {
            const parts = line.split(',').map(p => p.trim());
            return { email: parts[0], name: parts[1] || '' };
        });

        if (users.length === 0) { alert('Nenhum email valido encontrado'); return; }
        if (!confirm(`Criar ${users.length} usuario(s)?`)) return;

        try {
            const res = await fetch('/api/admin/users/batch-create', {
                method: 'POST', headers: Auth.headers(), body: JSON.stringify({ users })
            });
            const data = await res.json();
            if (!res.ok) throw new Error(data.error);

            let html = '';
            if (data.total_created > 0) {
                html += `<p style="margin-bottom:8px;color:var(--correct);font-weight:600">${data.total_created} usuario(s) criado(s)</p>`;
                html += '<table class="data-table" style="font-size:13px"><thead><tr><th>Email</th><th>Nome</th><th>Senha</th></tr></thead><tbody>';
                this._batchResultText = 'Email\tNome\tSenha\n';
                for (const u of data.created) {
                    html += `<tr><td>${this.esc(u.email)}</td><td>${this.esc(u.name || 'β€”')}</td><td><code style="user-select:all">${this.esc(u.password)}</code></td></tr>`;
                    this._batchResultText += `${u.email}\t${u.name || ''}\t${u.password}\n`;
                }
                html += '</tbody></table>';
            }
            if (data.total_errors > 0) {
                html += `<p style="margin-top:12px;margin-bottom:8px;color:var(--wrong);font-weight:600">${data.total_errors} erro(s)</p><ul style="font-size:13px">`;
                for (const e of data.errors) {
                    html += `<li>${this.esc(e.email)}: ${this.esc(e.error)}</li>`;
                }
                html += '</ul>';
            }

            document.getElementById('batch-form').style.display = 'none';
            document.getElementById('batch-results').style.display = 'block';
            document.getElementById('batch-results-content').innerHTML = html;
        } catch (e) { alert('Erro: ' + e.message); }
    },

    async copyBatchResults() {
        if (this._batchResultText) {
            await navigator.clipboard.writeText(this._batchResultText);
            alert('Tabela copiada!');
        }
    },

    closeBatchResults() {
        document.getElementById('batch-form').style.display = 'block';
        document.getElementById('batch-results').style.display = 'none';
        document.getElementById('batch-input').value = '';
        this.closeModal('modal-batch-create');
        this.switchTab('users');
    },

    async kickSession(sid) {
        if (!confirm('Encerrar esta sessao?')) return;
        try {
            const res = await fetch(`/api/admin/sessions/${sid}/kick`, { method: 'POST', headers: Auth.headers() });
            if (!res.ok) throw new Error('Erro ao encerrar sessao');
            this.switchTab('sessions');
        } catch (e) { alert('Erro: ' + e.message); }
    },

    openModal(id) { document.getElementById(id).classList.add('show'); },
    closeModal(id) { document.getElementById(id).classList.remove('show'); document.querySelectorAll(`#${id} input`).forEach(i => i.value = ''); },

    formatDuration(seconds) {
        if (!seconds || seconds < 0) return 'β€”';
        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        if (h > 0) return `${h}h ${m}m`;
        if (m > 0) return `${m}m`;
        return `${seconds}s`;
    },

    esc(str) {
        if (!str) return '';
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }
};