File size: 30,751 Bytes
c65e601
e9f7742
c65e601
 
 
 
 
 
dd7cb5f
7db85a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c65e601
 
7db85a7
 
 
 
 
 
 
 
 
 
 
 
6ef229f
 
dd7cb5f
a377724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f7742
a377724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f7742
 
a377724
e9f7742
dd7cb5f
 
 
 
 
 
 
 
 
 
 
 
e9f7742
6ef229f
 
 
 
 
 
 
 
 
 
 
 
4661923
 
813fe6a
6ef229f
 
 
 
 
 
 
 
 
c65e601
6ef229f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c65e601
6ef229f
 
 
 
 
 
c65e601
 
6ef229f
c65e601
6ef229f
 
 
 
 
 
 
 
 
 
c65e601
 
 
 
 
 
 
 
6ef229f
 
 
e9f7742
 
 
 
 
 
 
a377724
 
 
e9f7742
 
 
 
 
 
a377724
 
 
 
 
 
 
 
93359ec
 
 
 
a377724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93359ec
a377724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4953451
 
 
a377724
4953451
a377724
4953451
 
 
 
 
 
a377724
 
4953451
a377724
 
 
e9f7742
 
 
 
 
 
 
b959f55
e9f7742
 
 
 
 
b959f55
4953451
 
e9f7742
 
 
4953451
b959f55
4953451
 
 
 
 
 
 
 
 
e9f7742
 
4953451
e9f7742
 
 
6ef229f
 
 
 
 
7a04ee7
307a281
 
 
 
 
 
 
7a04ee7
307a281
7a04ee7
 
 
 
 
 
 
 
 
 
 
 
6ef229f
 
 
307a281
6ef229f
c65e601
 
6ef229f
 
e91bb41
 
 
 
 
 
6ef229f
 
7a04ee7
 
 
 
 
 
 
6ef229f
7a04ee7
 
 
 
 
 
4661923
7a04ee7
aa381d8
 
7a04ee7
 
aa381d8
7a04ee7
 
 
 
 
 
 
4661923
 
 
7a04ee7
aa381d8
 
7a04ee7
 
aa381d8
7a04ee7
4661923
813fe6a
7a04ee7
 
 
813fe6a
7a04ee7
6ef229f
7a04ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef229f
 
7a04ee7
6ef229f
 
 
 
7a04ee7
6ef229f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c65e601
6ef229f
 
 
 
 
c65e601
6ef229f
c65e601
 
e9f7742
c65e601
6ef229f
c65e601
6ef229f
 
 
c65e601
6ef229f
 
c65e601
 
6ef229f
c65e601
 
6ef229f
 
c65e601
6ef229f
c65e601
813fe6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef229f
7a04ee7
6ef229f
 
c65e601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f7742
c65e601
 
 
 
 
e9f7742
c65e601
 
 
 
 
4661923
 
 
de731eb
4661923
 
 
 
 
 
 
 
 
de731eb
 
 
 
 
 
 
 
4661923
 
 
 
 
 
 
 
 
 
89b794e
4661923
 
 
89b794e
 
 
 
 
4661923
 
89b794e
4661923
 
 
 
 
 
 
 
89b794e
4661923
89b794e
 
 
 
 
 
 
4661923
89b794e
4661923
 
 
89b794e
4661923
 
 
 
89b794e
 
 
 
 
 
 
 
 
 
 
1d76828
 
dd7cb5f
3978799
 
 
 
 
 
 
 
 
dd7cb5f
 
3978799
 
1d76828
3978799
 
 
 
 
1d76828
3978799
 
 
1d76828
3978799
a0158bf
3978799
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7cb5f
 
 
1d76828
dd7cb5f
 
 
1d76828
 
dd7cb5f
1d76828
 
 
 
 
dd7cb5f
 
1d76828
 
 
 
 
 
dd7cb5f
 
 
1d76828
dd7cb5f
 
 
7db85a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f7742
 
 
7db85a7
e9f7742
c65e601
 
 
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>活動座位管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        #restartContainer {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
            text-align: center;
            background: rgba(0, 0, 0, 0.9);
            padding: 2rem;
            border-radius: 10px;
            color: white;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
        }
        #restartContainer h3 {
            margin-bottom: 1rem;
        }
        #restartContainer p {
            margin-bottom: 1.5rem;
        }
        .sleeping-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
            display: none;
        }
    </style>
</head>
<body>
    <!-- 重啟系統對話框 -->
    <div id="restartContainer">
        <h3><i class="bi bi-moon-stars"></i> 系統休眠中</h3>
        <p>由於一段時間沒有活動,系統進入了休眠狀態。<br>請點擊下方按鈕重新啟動。</p>
        <button onclick="restartSpace()" class="btn btn-primary">
            <i class="bi bi-arrow-clockwise"></i> 重新啟動系統
        </button>
    </div>
    
    <!-- 遮罩層 -->
    <div id="sleepingOverlay" class="sleeping-overlay"></div>

    <div class="container mt-4">
        <h2>管理員後台</h2>
        
                <!-- 桌次設定 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">桌次設定</h5>
                    </div>
                    <div class="card-body">
                        <form id="tableSettingsForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="totalTables" class="form-label">總桌數</label>
                                        <input type="number" class="form-control" id="totalTables" min="1" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="seatsPerTable" class="form-label">每桌人數</label>
                                        <input type="number" class="form-control" id="seatsPerTable" min="1" required>
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">更新設定</button>
                        </form>
                    </div>
                </div>
        
                <!-- 桌次命名設定 -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">桌次命名</h5>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="loadTableNames()">
                            <i class="bi bi-arrow-clockwise"></i> 重新載入
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row" id="tableNameSettings">
                            <!-- 桌次命名表單將由 JavaScript 動態生成 -->
                        </div>
                    </div>
                </div>
        
        <!-- 備份和恢復按鈕 -->
        <div class="row mb-4">
            <div class="col">
                <button class="btn btn-success me-2" onclick="backupData()">
                    <i class="bi bi-cloud-upload"></i> 備份資料到 Sheets
                </button>
                <button class="btn btn-warning" onclick="restoreData()">
                    <i class="bi bi-cloud-download"></i> 從 Sheets 恢復資料
                </button>
            </div>
        </div>
        
        <!-- 參與者列表 -->
        <div class="row">
            <div class="col">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>桌次</th>
                                <th>座位</th>
                                <th>暱稱</th>
                                <th>Email</th>
                                <th>FB連結</th>
                                <th>自我介紹</th>
                                <th>付款狀態</th>
                                <th>備註</th>
                                <th>身份</th>
                                <th>報名時間</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="participantsTable">
                            <!-- 參與者資料會動態插入這裡 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 移動座位的 Modal -->
    <div class="modal fade" id="moveParticipantModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">移動座位</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="moveParticipantForm">
                        <input type="hidden" id="participantId">
                        <div class="mb-3">
                            <label for="newTableSelect" class="form-label">選擇新桌次</label>
                            <select class="form-select" id="newTableSelect">
                                <!-- 桌子選項會動態插入這裡 -->
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="moveParticipant()">確認移動</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看完整自我介紹的 Modal -->
    <div class="modal fade" id="viewIntroModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">自我介紹</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="fullIntroText"></p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>
    <script>
        let participants = [];
        let tables = [];

        // 載入目前設定
        async function loadCurrentSettings() {
            try {
                const response = await fetch('/api/admin/settings');
                const data = await response.json();
                document.getElementById('totalTables').value = data.total_tables;
                document.getElementById('seatsPerTable').value = data.seats_per_table;
                
                // 載入桌次名稱設定
                loadTableNames();
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', '載入設定失敗', 'error');
            }
        }

        // 載入桌次名稱設定
        async function loadTableNames() {
            try {
                const response = await fetch('/api/tables');
                const data = await response.json();
                const container = document.getElementById('tableNameSettings');
                container.innerHTML = '';

                if (!data.tables) {
                    throw new Error('無效的桌次資料');
                }

                data.tables.forEach(table => {
                    const col = document.createElement('div');
                    col.className = 'col-md-4 mb-3';
                    col.innerHTML = `
                        <div class="input-group">
                            <span class="input-group-text">第 ${table.id} 桌</span>
                            <input type="text" class="form-control" 
                                   id="tableName_${table.id}" 
                                   value="${table.name || ''}" 
                                   placeholder="輸入桌次名稱"
                                   onchange="updateTableName(${table.id}, this.value)">
                            <button class="btn btn-outline-secondary" type="button" 
                                    onclick="updateTableName(${table.id}, '')">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    `;
                    container.appendChild(col);
                });
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '載入桌次名稱失敗', 'error');
            }
        }

        // 更新桌次名稱
        async function updateTableName(tableId, name) {
            try {
                const response = await fetch('/api/admin/settings/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        action: 'update_table_name',
                        table_id: tableId,
                        name: name
                    })
                });
                
                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '更新桌次名稱失敗');
                }
                
                // 重新載入桌次名稱設定
                await loadTableNames();
                // 重新載入參與者列表以更新顯示
                await loadParticipants();
                
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '更新桌次名稱失敗', 'error');
            }
        }

        // 更新桌次設定
        document.getElementById('tableSettingsForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const totalTables = document.getElementById('totalTables').value;
            const seatsPerTable = document.getElementById('seatsPerTable').value;
            
            try {
                const response = await fetch('/api/admin/settings/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        action: 'update_tables',
                        total_tables: totalTables,
                        seats_per_table: seatsPerTable
                    })
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    await Swal.fire('成功', '桌次設定已更新', 'success');
                    // 重新載入桌次名稱設定
                    await loadTableNames();
                    // 重新載入參與者列表
                    await loadParticipants();
                } else {
                    Swal.fire('錯誤', result.error || '更新失敗', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', '更新設定失敗', 'error');
            }
        });

        // 載入參與者資料
        async function loadParticipants() {
            try {
                const response = await fetch('/api/admin/participants');
                const data = await response.json();
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                participants = data.participants;
                tables = data.tables;
                
                // 依照桌次和座位號排序
                participants.sort((a, b) => {
                    // 先比較桌次
                    const tableA = parseInt(a.table_id) || 0;
                    const tableB = parseInt(b.table_id) || 0;
                    if (tableA !== tableB) {
                        return tableA - tableB;
                    }
                    // 如果桌次相同,再比較座位號
                    const seatA = parseInt(a.seat_number) || 0;
                    const seatB = parseInt(b.seat_number) || 0;
                    return seatA - seatB;
                });
                
                renderParticipants();
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', '載入參與者資料失敗:' + error.message, 'error');
            }
        }

        // 渲染參與者列表
        function renderParticipants() {
            const tbody = document.getElementById('participantsTable');
            if (!tbody) {
                console.error('找不到參與者列表元素');
                return;
            }
            
            tbody.innerHTML = '';
            
            participants.forEach(participant => {
                const tr = document.createElement('tr');
                tr.className = participant.is_table_leader ? 'table-leader' : '';
                
                // 找到對應的桌子
                const table = tables.find(t => t.id === participant.table_id);
                const tableName = table ? table.name : '未分配';
                
                tr.innerHTML = `
                    <td>${tableName}</td>
                    <td>${participant.seat_number || '-'}</td>
                    <td>${participant.nickname}</td>
                    <td>${participant.email}</td>
                    <td>${participant.fb_link ? `<a href="${participant.fb_link}" target="_blank">FB連結</a>` : '-'}</td>
                    <td>
                        ${participant.introduction ? 
                            `${participant.introduction.length > 5 ? 
                                participant.introduction.substring(0, 5) + '...' : 
                                participant.introduction}
                            <button class="btn btn-link btn-sm" onclick="showFullIntroduction('${participant.introduction.replace(/'/g, "\\'")}')">
                                <i class="bi bi-eye"></i>
                            </button>` 
                            : '-'}
                    </td>
                    <td>
                        <button class="btn ${participant.has_paid ? 'btn-success' : 'btn-danger'} btn-sm" 
                                onclick="togglePayment(${participant.id})">
                            ${participant.has_paid ? '已付款' : '未付款'}
                        </button>
                    </td>
                    <td>
                        ${participant.note ? 
                            `<span class="note-preview d-inline-block text-truncate" style="max-width: 100px;" onclick="editNote(${participant.id}, '${participant.note.replace(/'/g, "\\'")}')">
                                ${participant.note}
                            </span>` 
                            : `<button class="btn btn-outline-secondary btn-sm" onclick="editNote(${participant.id}, '')">
                                <i class="bi bi-pencil"></i>
                            </button>`}
                    </td>
                    <td>
                        <span class="${participant.is_table_leader ? 'badge bg-success' : 'badge bg-secondary'}">
                            ${participant.is_table_leader ? '桌長' : '參與者'}
                        </span>
                    </td>
                    <td>${new Date(participant.created_at).toLocaleString('zh-TW', { timeZone: 'Asia/Taipei' })}</td>
                    <td>
                        <div class="btn-group" role="group">
                            <button class="btn btn-primary btn-sm" onclick="showMoveDialog(${participant.id})">
                                移動座位
                            </button>
                            ${participant.is_table_leader ? 
                                `<button class="btn btn-warning btn-sm" onclick="toggleLeader(${participant.id})">
                                    取消桌長
                                </button>` : 
                                `<button class="btn btn-success btn-sm" onclick="toggleLeader(${participant.id})">
                                    設為桌長
                                </button>`
                            }
                            <button class="btn btn-danger btn-sm" onclick="deleteParticipant(${participant.id})">
                                刪除
                            </button>
                        </div>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 顯示移動座位的 Modal
        function showMoveDialog(participantId) {
            document.getElementById('participantId').value = participantId;
            const select = document.getElementById('newTableSelect');
            select.innerHTML = '';
            
            tables.forEach(table => {
                if (table.current_seats < table.capacity) {
                    const option = document.createElement('option');
                    option.value = table.id;
                    option.textContent = `${table.name} (${table.current_seats}/${table.capacity})`;
                    select.appendChild(option);
                }
            });
            
            new bootstrap.Modal(document.getElementById('moveParticipantModal')).show();
        }

        // 移動參與者座位
        async function moveParticipant() {
            const participantId = document.getElementById('participantId').value;
            const newTableId = document.getElementById('newTableSelect').value;
            
            try {
                const response = await fetch(`/api/admin/participant/${participantId}/move`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ new_table_id: newTableId })
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    Swal.fire('成功', '已移動座位', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('moveParticipantModal')).hide();
                    loadParticipants();
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '移動座位失敗', 'error');
            }
        }

        // 切換桌長狀態
        async function toggleLeader(participantId) {
            try {
                const response = await fetch(`/api/admin/participant/${participantId}/toggle-leader`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    Swal.fire('成功', data.message, 'success');
                    loadParticipants();
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '操作失敗', 'error');
            }
        }

        // 查看完整自我介紹
        function showFullIntroduction(intro) {
            document.getElementById('fullIntroText').textContent = intro;
            new bootstrap.Modal(document.getElementById('viewIntroModal')).show();
        }

        // 刪除報名者
        async function deleteParticipant(participantId) {
            const result = await Swal.fire({
                title: '確定要刪除嗎?',
                text: "此操作無法復原!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: '是的,刪除!',
                cancelButtonText: '取消'
            });

            if (result.isConfirmed) {
                try {
                    const response = await fetch(`/api/admin/participants/${participantId}`, {
                        method: 'DELETE'
                    });

                    if (response.ok) {
                        Swal.fire('已刪除!', '該報名者已被刪除。', 'success');
                        loadParticipants();
                    } else {
                        throw new Error('刪除失敗');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    Swal.fire('錯誤', error.message, 'error');
                }
            }
        }

        // 切換付款狀態
        async function togglePayment(participantId) {
            try {
                const response = await fetch(`/api/admin/participant/${participantId}/payment`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: data.message,
                        showConfirmButton: false,
                        timer: 1500
                    });
                    await loadParticipants();
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '操作失敗', 'error');
            }
        }

        // 編輯備註
        async function editNote(participantId, currentNote) {
            const { value: note } = await Swal.fire({
                title: '編輯備註',
                input: 'textarea',
                inputValue: currentNote,
                inputPlaceholder: '請輸入備註內容...',
                showCancelButton: true,
                confirmButtonText: '儲存',
                cancelButtonText: '取消'
            });

            if (note !== undefined) {  // 用戶點擊了儲存
                try {
                    const response = await fetch(`/api/admin/participant/${participantId}/note`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ note })
                    });

                    if (response.ok) {
                        await loadParticipants();  // 重新載入參與者列表
                        Swal.fire({
                            icon: 'success',
                            title: '備註已更新',
                            showConfirmButton: false,
                            timer: 1500
                        });
                    } else {
                        throw new Error('更新備註失敗');
                    }
                } catch (error) {
                    console.error('Error:', error);
                    Swal.fire('錯誤', error.message, 'error');
                }
            }
        }

        // 顯示完整備註
        function showNote(note) {
            if (note) {
                Swal.fire({
                    title: '備註內容',
                    text: note,
                    confirmButtonText: '關閉'
                });
            }
        }

        // 從 Google Sheets 恢復資料
        async function restoreData() {
            try {
                const result = await Swal.fire({
                    title: '確認恢復資料?',
                    text: '這將會覆蓋目前的所有資料!',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '是,恢復資料',
                    cancelButtonText: '取消'
                });
                
                if (result.isConfirmed) {
                    // 顯示載入中
                    Swal.fire({
                        title: '處理中...',
                        text: '正在從 Google Sheets 恢復資料',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        allowEnterKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    const response = await fetch('/api/admin/settings/restore', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    const data = await response.json();
                    
                    // 關閉載入中
                    await Swal.close();
                    
                    if (response.ok) {
                        await Swal.fire({
                            icon: 'success',
                            title: '成功',
                            text: data.message,
                            showConfirmButton: false,
                            timer: 1500
                        });
                        await loadParticipants();
                    } else {
                        throw new Error(data.error || '恢復資料失敗');
                    }
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '恢復資料失敗', 'error');
            }
        }

        // 備份資料到 Google Sheets
        async function backupData() {
            try {
                const response = await fetch('/api/admin/settings/backup', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    Swal.fire('成功', '資料已成功備份到 Google Sheets', 'success');
                } else {
                    throw new Error(data.error);
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('錯誤', error.message || '備份失敗', 'error');
            }
        }

        // 檢查系統狀態的函數
        async function checkSystemStatus() {
            try {
                const response = await fetch('/api/admin/participants');
                if (!response.ok) {
                    showRestartButton();
                } else {
                    hideRestartButton();
                }
            } catch (error) {
                console.error('Error checking system status:', error);
                showRestartButton();
            }
        }

        // 顯示重啟按鈕
        function showRestartButton() {
            document.getElementById('restartContainer').style.display = 'block';
            document.getElementById('sleepingOverlay').style.display = 'block';
        }

        // 隱藏重啟按鈕
        function hideRestartButton() {
            document.getElementById('restartContainer').style.display = 'none';
            document.getElementById('sleepingOverlay').style.display = 'none';
        }

        // 重啟系統
        async function restartSpace() {
            const button = document.querySelector('#restartContainer button');
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<i class="bi bi-arrow-clockwise"></i> 正在重新啟動...';
            
            // 重新載入頁面
            window.location.reload();
        }

        // 定期檢查系統狀態
        setInterval(checkSystemStatus, 30000); // 每30秒檢查一次
        
        // 初始化頁面時也檢查一次
        document.addEventListener('DOMContentLoaded', () => {
            loadCurrentSettings();
            loadParticipants();
            checkSystemStatus();
        });
    </script>
</body>
</html>