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 
 
 
 
 
 
 
 
 
 
 
 
4bd2f4a
 
 
 
 
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系統後台管理 - 英文單字小學堂</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <style>
        .admin-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 15px;
            margin-bottom: 30px;
        }
        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid var(--border-color);
        }
        .form-section:last-child {
            border-bottom: none;
        }
        .form-section h3 {
            margin-top: 0;
            color: var(--primary-color);
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .form-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 15px;
        }
        .form-group {
            display: flex;
            flex-direction: column;
        }
        .form-group label {
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 0.95rem;
        }
        .form-control {
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.2s;
        }
        .form-control:focus {
            border-color: var(--primary-color);
        }
        .unit-checkbox-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            gap: 10px;
            max-height: 200px;
            overflow-y: auto;
            padding: 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background-color: var(--bg-color);
        }
        .unit-checkbox-label {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            font-size: 0.95rem;
            user-select: none;
        }
        .checkbox-input {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
        .switch-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 26px;
        }
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #cbd5e1;
            transition: .3s;
            border-radius: 34px;
        }
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .3s;
            border-radius: 50%;
        }
        input:checked + .slider {
            background-color: var(--primary-color);
        }
        input:checked + .slider:before {
            transform: translateX(24px);
        }
        .msg-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 9999;
            transform: translateY(-20px);
            opacity: 0;
            transition: all 0.3s ease;
        }
        .msg-toast.show {
            transform: translateY(0);
            opacity: 1;
        }
        .msg-toast.success { background-color: var(--success); }
        .msg-toast.error { background-color: var(--error); }
    </style>
</head>
<body>
    <div class="container">
        <!-- Toast Notification -->
        <div id="toast" class="msg-toast"></div>

        <header class="card">
            <div>
                <h1>⚙️ 系統後台管理</h1>
                <p style="color: var(--text-muted); margin-top: 5px;">配置單字系統、複習進度表與發信設定</p>
            </div>
            <div class="controls">
                <a href="/" class="btn btn-secondary">🏠 首頁</a>
                <a href="{{ url_for('admin_logout') }}" class="btn btn-secondary" style="border-color: var(--error); color: var(--error);">登出</a>
            </div>
        </header>

        <div class="card" style="padding: 32px;">
            <div class="admin-header">
                <h2 style="margin: 0; border: none; padding: 0;">🔧 系統參數設定</h2>
                <button onclick="saveAllSettings()" class="btn btn-primary">💾 儲存所有設定</button>
            </div>

            <!-- 1. 複習表設定 -->
            <div class="form-section">
                <h3>📅 複習進度表設定</h3>
                <div class="switch-container">
                    <label class="switch">
                        <input type="checkbox" id="reviewEnable">
                        <span class="slider"></span>
                    </label>
                    <span style="font-weight: 600; font-size: 1rem;">啟用複習進度表功能 (關閉時不顯示首頁頁簽)</span>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="startDate">複習開始日期</label>
                        <input type="date" id="startDate" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="endDate">複習結束日期</label>
                        <input type="date" id="endDate" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="requiredDays">規定複習次數 (天數)</label>
                        <input type="number" id="requiredDays" class="form-control" min="1" max="60" value="2" required>
                    </div>
                </div>

                <div class="form-group" style="margin-top: 15px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <label style="margin: 0;">要納入複習的單元</label>
                        <div style="display: flex; gap: 8px;">
                            <button type="button" onclick="selectAllUnits(true)" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.8rem; border-radius: 6px;">全選</button>
                            <button type="button" onclick="selectAllUnits(false)" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.8rem; border-radius: 6px;">全不選</button>
                        </div>
                    </div>
                    <div class="unit-checkbox-container" id="unitCheckboxes">
                        <!-- JS 動態插入單元 -->
                    </div>
                </div>
            </div>

            <!-- 2. Email 設定 -->
            <div class="form-section">
                <h3>✉️ 郵件通知設定</h3>
                <div class="switch-container">
                    <label class="switch">
                        <input type="checkbox" id="emailEnable">
                        <span class="slider"></span>
                    </label>
                    <span style="font-weight: 600; font-size: 1rem;">啟用測驗完成 Email 通知</span>
                </div>

                <div class="form-group" style="margin-top: 10px;">
                    <label for="receivers">收件者信箱 (多個請用逗號隔開)</label>
                    <input type="text" id="receivers" class="form-control" placeholder="parent1@example.com, parent2@example.com">
                </div>
            </div>

            <!-- 3. 密碼修改設定 -->
            <div class="form-section">
                <h3>🔐 修改管理員密碼</h3>
                <p style="color: var(--text-muted); font-size: 0.85rem; margin-top: -5px; margin-bottom: 15px;">
                    注意:若您有設定環境變數 `ADMIN_PASSWORD`,系統密碼將被強制寫死在環境變數中,後台密碼修改將不生效。
                </p>
                <div class="form-row">
                    <div class="form-group">
                        <label for="oldPassword">舊密碼</label>
                        <input type="password" id="oldPassword" class="form-control" placeholder="請輸入原密碼">
                    </div>
                    <div class="form-group">
                        <label for="newPassword">新密碼</label>
                        <input type="password" id="newPassword" class="form-control" placeholder="請輸入新密碼">
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">確認新密碼</label>
                        <input type="password" id="confirmPassword" class="form-control" placeholder="請再次輸入新密碼">
                    </div>
                </div>
                <button onclick="updatePassword()" class="btn btn-secondary" style="align-self: flex-start; margin-top: 5px;">🔑 變更密碼</button>
            </div>

            <!-- 4. 危險區域 -->
            <div class="form-section" style="border-bottom: none; margin-top: 20px;">
                <h3 style="color: var(--error);">⚠️ 危險區域</h3>
                <p style="color: var(--text-muted); font-size: 0.85rem; margin-top: -5px; margin-bottom: 15px;">
                    注意:此操作將永久清除資料庫中的所有學生複習進度紀錄 (quiz_results 表格中的資料),此動作無法復原。
                </p>
                <button id="clearQuizBtn" onclick="confirmClearQuiz()" class="btn btn-secondary" style="border-color: var(--error); color: var(--error); font-weight: 600; background-color: transparent; transition: all 0.3s ease;">
                    🗑️ 清除所有複習進度紀錄
                </button>
            </div>

            <div style="display: flex; justify-content: flex-end; margin-top: 30px; border-top: 2px solid var(--border-color); padding-top: 20px;">
                <button onclick="saveAllSettings()" class="btn btn-primary" style="padding: 12px 30px; font-size: 1rem;">💾 儲存所有設定</button>
            </div>
        </div>
    </div>

    <script>
        let availableUnits = [];

        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            toast.innerText = message;
            toast.className = `msg-toast ${type} show`;
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        function selectAllUnits(status) {
            document.querySelectorAll('.unit-check').forEach(cb => {
                cb.checked = status;
            });
        }

        async function loadSettings() {
            try {
                const res = await fetch('/api/admin/config');
                const data = await res.json();

                if (!data.success) {
                    showToast(data.message || '讀取設定失敗', 'error');
                    return;
                }

                const config = data.config;
                availableUnits = data.available_units || [];

                // 填入複習設定
                const rSettings = config.review_settings || {};
                document.getElementById('startDate').value = rSettings.start_date || '2026-07-01';
                document.getElementById('endDate').value = rSettings.end_date || '2026-08-31';
                document.getElementById('requiredDays').value = rSettings.required_days || 2;
                document.getElementById('reviewEnable').checked = rSettings.enable_review !== false;

                // 填入單元選單 (若未設定 selected_units 則預設全選)
                const hasConfiguredUnits = Array.isArray(rSettings.selected_units);
                const selectedUnits = rSettings.selected_units || [];
                const container = document.getElementById('unitCheckboxes');
                container.innerHTML = '';
                if (availableUnits.length === 0) {
                    container.innerHTML = '<span style="color: var(--text-muted);">系統中尚無單元單字</span>';
                } else {
                    availableUnits.forEach(unit => {
                        const isChecked = hasConfiguredUnits ? selectedUnits.includes(unit) : true;
                        const label = document.createElement('label');
                        label.className = 'unit-checkbox-label';
                        label.innerHTML = `
                            <input type="checkbox" class="checkbox-input unit-check" value="${unit}" ${isChecked ? 'checked' : ''}>
                            <span>${unit}</span>
                        `;
                        container.appendChild(label);
                    });
                }

                // 填入 Email 設定
                const eSettings = config.email_settings || {};
                document.getElementById('emailEnable').checked = eSettings.enable || false;
                document.getElementById('receivers').value = (eSettings.receivers || []).join(', ');

            } catch (e) {
                console.error(e);
                showToast('伺服器連接錯誤,請稍後再試', 'error');
            }
        }

        async function saveAllSettings() {
            // 收集單元勾選結果
            const checkedUnits = [];
            document.querySelectorAll('.unit-check:checked').forEach(cb => {
                checkedUnits.push(cb.value);
            });

            const review_settings = {
                start_date: document.getElementById('startDate').value,
                end_date: document.getElementById('endDate').value,
                required_days: parseInt(document.getElementById('requiredDays').value) || 2,
                selected_units: checkedUnits,
                enable_review: document.getElementById('reviewEnable').checked
            };

            const receiversRaw = document.getElementById('receivers').value;
            const receivers = receiversRaw.split(',')
                .map(r => r.trim())
                .filter(r => r !== '');

            const email_settings = {
                enable: document.getElementById('emailEnable').checked,
                receivers: receivers
            };

            try {
                const res = await fetch('/api/admin/config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ review_settings, email_settings })
                });
                const result = await res.json();

                if (result.success) {
                    showToast('設定已成功儲存至 Supabase 雲端!');
                    loadSettings(); // 重新載入以維持一致性
                } else {
                    showToast(result.message || '儲存失敗', 'error');
                }
            } catch (e) {
                console.error(e);
                showToast('儲存失敗,請檢查網路連線', 'error');
            }
        }

        async function updatePassword() {
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            if (!oldPassword || !newPassword) {
                showToast('請填寫完整密碼欄位', 'error');
                return;
            }

            if (newPassword !== confirmPassword) {
                showToast('新密碼與確認新密碼不符', 'error');
                return;
            }

            try {
                const res = await fetch('/api/admin/password', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
                });
                const result = await res.json();

                if (result.success) {
                    showToast('密碼已成功更新!');
                    document.getElementById('oldPassword').value = '';
                    document.getElementById('newPassword').value = '';
                    document.getElementById('confirmPassword').value = '';
                } else {
                    showToast(result.message || '更變密碼失敗', 'error');
                }
            } catch (e) {
                console.error(e);
                showToast('變更密碼發生錯誤', 'error');
            }
        }

        let clearConfirmCount = 0;
        let clearTimer = null;

        function confirmClearQuiz() {
            const btn = document.getElementById('clearQuizBtn');
            clearConfirmCount++;

            if (clearTimer) clearTimeout(clearTimer);
            clearTimer = setTimeout(() => {
                clearConfirmCount = 0;
                btn.className = 'btn btn-secondary';
                btn.style.borderColor = 'var(--error)';
                btn.style.color = 'var(--error)';
                btn.style.backgroundColor = 'transparent';
                btn.innerText = '🗑️ 清除所有複習進度紀錄';
            }, 5000);

            if (clearConfirmCount === 1) {
                btn.innerText = '⚠️ 請再次點擊確認清除 (第 2/3 次確認)';
                btn.style.backgroundColor = '#f97316';
                btn.style.color = 'white';
                btn.style.borderColor = '#f97316';
            } else if (clearConfirmCount === 2) {
                btn.innerText = '🔥 最後一次確認!點擊即永久刪除!(第 3/3 次確認)';
                btn.style.backgroundColor = '#ef4444';
                btn.style.color = 'white';
                btn.style.borderColor = '#ef4444';
            } else if (clearConfirmCount === 3) {
                clearConfirmCount = 0;
                if (clearTimer) clearTimeout(clearTimer);
                clearTimer = null;
                btn.disabled = true;
                btn.innerText = '⏳ 正在清除...';
                
                fetch('/api/admin/clear_quiz_results', {
                    method: 'POST'
                })
                .then(res => res.json())
                .then(data => {
                    btn.disabled = false;
                    btn.className = 'btn btn-secondary';
                    btn.style.borderColor = 'var(--error)';
                    btn.style.color = 'var(--error)';
                    btn.style.backgroundColor = 'transparent';
                    btn.innerText = '🗑️ 清除所有複習進度紀錄';
                    
                    if (data.success) {
                        showToast(data.message || '已成功清除所有複習進度紀錄!');
                    } else {
                        showToast(data.message || '清除失敗', 'error');
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.className = 'btn btn-secondary';
                    btn.style.borderColor = 'var(--error)';
                    btn.style.color = 'var(--error)';
                    btn.style.backgroundColor = 'transparent';
                    btn.innerText = '🗑️ 清除所有複習進度紀錄';
                    console.error(err);
                    showToast('伺服器連線失敗', 'error');
                });
            }
        }

        // 頁面初始化
        loadSettings();
    </script>
</body>
</html>