File size: 82,914 Bytes
54cfc56
 
 
 
 
8a3e6e9
6775604
 
1ae198d
 
54cfc56
 
8a3e6e9
 
 
1ae198d
54cfc56
 
1ae198d
54cfc56
 
1ae198d
6775604
 
54cfc56
 
 
 
 
8a3e6e9
 
 
 
 
 
 
 
 
 
54cfc56
 
 
 
 
 
1ae198d
54cfc56
1ae198d
 
 
 
 
54cfc56
1ae198d
 
 
 
54cfc56
1ae198d
54cfc56
 
8a3e6e9
54cfc56
 
 
 
 
 
 
1ae198d
 
 
 
 
 
 
 
 
54cfc56
 
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54cfc56
 
 
9c8d13a
38ea648
54cfc56
 
9c8d13a
54cfc56
1ae198d
 
 
 
 
 
6775604
1ae198d
 
c889d8b
 
1ae198d
c889d8b
 
 
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c889d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54cfc56
1ae198d
c889d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ae198d
 
c889d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4bb069
1ae198d
 
c889d8b
 
 
 
54cfc56
1ae198d
 
c889d8b
 
 
 
1ae198d
 
 
 
 
 
c889d8b
1ae198d
c889d8b
1ae198d
 
 
54cfc56
1ae198d
 
 
 
 
 
 
 
54cfc56
1ae198d
 
 
 
 
 
 
54cfc56
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54cfc56
1ae198d
54cfc56
1ae198d
 
 
 
 
 
 
 
 
 
54cfc56
1ae198d
c889d8b
1ae198d
e19de94
 
f1cff8c
c889d8b
f1cff8c
e19de94
f1cff8c
e19de94
f1cff8c
54cfc56
 
 
f1cff8c
54cfc56
 
c889d8b
f1cff8c
54cfc56
 
 
 
 
 
 
f0d4780
 
 
 
 
 
 
 
 
 
 
 
de1241f
 
54cfc56
f1cff8c
c889d8b
1ae198d
54cfc56
6775604
 
1ae198d
 
 
6775604
 
 
 
c889d8b
6775604
 
1ae198d
6775604
 
9c8d13a
 
 
1ae198d
9c8d13a
0711d01
d731959
9c8d13a
c889d8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ae198d
c889d8b
1ae198d
dfcba55
 
 
1ae198d
dfcba55
1ae198d
 
 
 
c889d8b
1ae198d
dfcba55
 
 
 
 
 
 
1ae198d
dfcba55
1ae198d
 
 
 
dfcba55
 
 
1ae198d
 
 
dfcba55
 
1ae198d
 
dfcba55
 
f4bb069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e19de94
54cfc56
e19de94
1ae198d
 
e19de94
 
 
54cfc56
 
 
 
 
 
8fc85df
 
54cfc56
 
 
 
 
 
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54cfc56
1ae198d
de1241f
f4bb069
 
54cfc56
f4bb069
1ae198d
f4bb069
 
 
 
 
e19de94
f4bb069
6775604
 
 
 
 
1ae198d
 
 
f4bb069
1ae198d
 
f4bb069
 
 
 
 
54cfc56
 
1ae198d
54cfc56
 
 
1ae198d
54cfc56
6775604
 
 
 
 
1ae198d
 
54cfc56
 
f4bb069
54cfc56
 
 
 
 
 
1ae198d
6775604
 
1ae198d
 
54cfc56
 
 
 
 
 
 
 
 
 
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c8d13a
 
 
 
 
1ae198d
9c8d13a
 
1ae198d
 
9c8d13a
1ae198d
54cfc56
9c8d13a
1ae198d
 
9c8d13a
1ae198d
9c8d13a
1ae198d
54cfc56
 
1ae198d
54cfc56
 
 
1ae198d
54cfc56
 
f4bb069
1ae198d
909dd6c
1ae198d
54cfc56
f4bb069
54cfc56
 
 
1ae198d
54cfc56
 
1ae198d
 
 
54cfc56
1ae198d
 
 
54cfc56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909dd6c
54cfc56
909dd6c
54cfc56
 
 
 
 
1ae198d
 
 
 
 
c889d8b
 
 
 
 
 
 
 
 
1ae198d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54cfc56
 
1ae198d
 
54cfc56
f4bb069
 
 
1ae198d
 
 
dfa1e24
54cfc56
1ae198d
54cfc56
 
6489bf2
 
df0a5ed
 
6489bf2
905bf45
1ae198d
 
 
54cfc56
9c8d13a
1ae198d
 
 
 
 
54cfc56
 
4aab1d5
 
54cfc56
 
 
 
4377400
1ae198d
4377400
 
 
38ea648
4377400
1ae198d
4377400
 
 
 
 
1ae198d
4377400
44bb735
1ae198d
44bb735
6775604
5b3b226
6775604
4377400
 
4aab1d5
 
54cfc56
 
4aab1d5
 
5b3b226
4aab1d5
54cfc56
9c8d13a
54cfc56
38ea648
54cfc56
9c8d13a
 
784ea02
9c8d13a
 
 
 
 
 
40e2ab7
cbd62ba
8fc85df
 
059aa3b
cbd62ba
 
 
 
 
 
 
1ae198d
 
 
 
 
059aa3b
 
 
 
 
 
 
 
 
1ae198d
 
059aa3b
 
 
 
 
 
 
 
 
279450c
059aa3b
 
 
f4bb069
059aa3b
 
1ae198d
279450c
059aa3b
 
 
 
1ae198d
 
 
059aa3b
f1cff8c
059aa3b
 
 
 
1ae198d
059aa3b
 
1ae198d
 
 
 
 
059aa3b
 
 
1ae198d
8a3e6e9
 
 
 
 
 
f4bb069
 
8a3e6e9
 
 
f4bb069
 
 
 
8a3e6e9
 
 
f4bb069
 
8a3e6e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4bb069
8a3e6e9
 
f4bb069
8a3e6e9
1ae198d
 
 
 
8a3e6e9
f4bb069
 
8a3e6e9
de1241f
26874f3
8a3e6e9
f0d4780
 
 
 
de1241f
 
 
 
 
 
 
 
 
 
01146ef
 
de1241f
1de8a84
de1241f
1de8a84
de1241f
 
ba6967d
 
 
 
de1241f
ba6967d
 
 
de1241f
ba6967d
 
de1241f
 
 
 
 
1de8a84
ebae484
de1241f
 
1ae198d
de1241f
6775604
 
 
1ae198d
6775604
 
 
de1241f
1ae198d
 
 
ebae484
de1241f
 
1de8a84
ebae484
1ae198d
de1241f
6775604
 
 
 
 
1ae198d
 
 
1de8a84
de1241f
 
1ae198d
 
 
de1241f
 
 
ba6967d
 
 
 
de1241f
ba6967d
 
 
de1241f
ba6967d
 
de1241f
 
ebae484
de1241f
 
 
 
6775604
1ae198d
6775604
 
 
1ae198d
 
 
ebae484
de1241f
1ae198d
dfa1e24
8a3e6e9
f4bb069
8a3e6e9
 
 
 
 
1ae198d
8a3e6e9
f4bb069
 
 
 
 
 
1ae198d
f4bb069
 
 
 
 
 
 
 
 
8a3e6e9
 
 
 
 
1ae198d
 
 
8a3e6e9
38ea648
 
6775604
38ea648
 
 
 
 
 
 
 
6775604
38ea648
 
 
 
8a3e6e9
f4bb069
 
1ae198d
8a3e6e9
f4bb069
 
 
 
1ae198d
 
 
f4bb069
 
 
1ae198d
 
 
38ea648
 
 
 
dfcba55
 
 
 
 
 
 
 
 
 
 
1ae198d
dfcba55
 
c889d8b
6775604
38ea648
1ae198d
f4bb069
1ae198d
f4bb069
8a3e6e9
f4bb069
 
 
8a3e6e9
5b3b226
 
 
1ae198d
5b3b226
1ae198d
4aab1d5
8a3e6e9
 
 
 
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
import sys
import os
import json
import base64
import uuid
import warnings
import threading
import shutil
import sqlite3
import hashlib
from datetime import datetime, timezone, timedelta

# 忽略 Gradio 6.0 的 UserWarning 以免日誌洗版
warnings.filterwarnings("ignore", message="The parameters have been moved from the Blocks constructor.*")

# 【終極防護設定】精準設定您的專屬網址
os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "https://schillercfk-ssys.hf.space"

# 【設定台北時區】
TAIPEI_TZ = timezone(timedelta(hours=8))

# 【優化:資料庫執行緒鎖】保護 SQLite 在多執行緒環境下的併發寫入安全
db_lock = threading.Lock()

try:
    import gradio as gr
    import pandas as pd
    import subprocess
    from fastapi import FastAPI, Request, HTTPException
    from linebot.v3 import WebhookHandler
    from linebot.v3.exceptions import InvalidSignatureError
    from linebot.v3.messaging import (
        Configuration,
        ApiClient,
        MessagingApi,
        ReplyMessageRequest,
        TextMessage
    )
    from linebot.v3.webhooks import MessageEvent, TextMessageContent
    import uvicorn
except ImportError as e:
    print(f"❌ 啟動失敗:缺少必要的套件!請檢查 requirements.txt。詳細錯誤:{e}")
    sys.exit(1)

# ----------------------------
# 📱 LINE Bot 設定區 (資安優化:支援環境變數優先讀取)
# ----------------------------
# 優先從環境變數讀取,若無則使用預設金鑰,避免金鑰直接裸露於公開原始碼的風險
LINE_CHANNEL_ACCESS_TOKEN = os.environ.get(
    "LINE_ACCESS_TOKEN", 
    "HadCmCBmnZtI4LjC1Ad2rBwGZX7x1jZu4A0DXCX+LIjt3SpQq0vVz1kh8U74GB2XPbRdgwfqvFcVRR+i0NodOZ2P6hPC5ZV8EuxPOt+WnAvTJ29P5UBoENQCVAxu/AuRP2xgYKNYOg5voggl73mfkgdB04t89/1O/w1cDnyilFU="
).replace(" ", "").strip()

LINE_CHANNEL_SECRET = os.environ.get(
    "LINE_CHANNEL_SECRET", 
    "ae66c98db5eca3e75aff2ff28ef62f25"
).replace(" ", "").strip()

WEB_ORDER_URL = "https://schillercfk-ssys.hf.space/?openExternalBrowser=1"

try:
    configuration = Configuration(access_token=LINE_CHANNEL_ACCESS_TOKEN)
    handler = WebhookHandler(LINE_CHANNEL_SECRET)
except Exception as e:
    print(f"❌ LINE API 初始化失敗:{e}")

custom_api = FastAPI()

# ----------------------------
# 🔒 資安優化:密碼雜湊加密函數
# ----------------------------
def hash_pwd(password):
    """使用 SHA-256 進行單向加密,提升密碼儲存的安全性"""
    if len(str(password)) == 64: return password # 若已是 64 碼(雜湊值)則不重複加密
    return hashlib.sha256(str(password).encode('utf-8')).hexdigest()

# ----------------------------
# 🗄️ 系統資料與資料庫 (SQLite 優化升級)
# ----------------------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DB_FILE = os.path.join(BASE_DIR, "system_database.sqlite")

# 建立 SQLite 連線
db_conn = sqlite3.connect(DB_FILE, check_same_thread=False)
db_cursor = db_conn.cursor()

# 初始化資料庫表格
with db_lock:
    db_cursor.execute('''CREATE TABLE IF NOT EXISTS orders (
        order_id TEXT PRIMARY KEY, status TEXT, time TEXT, delivery_time TEXT, pickup_method TEXT,
        location TEXT, customer TEXT, item TEXT, price INTEGER, cost INTEGER, qty INTEGER,
        total INTEGER, total_cost INTEGER, note TEXT
    )''')
    db_cursor.execute('''CREATE TABLE IF NOT EXISTS menu (
        seq INTEGER, enable BOOLEAN, level TEXT, category TEXT, name TEXT, spec TEXT, price INTEGER, cost INTEGER, note TEXT
    )''')
    db_cursor.execute('''CREATE TABLE IF NOT EXISTS members (
        acc TEXT PRIMARY KEY, pwd TEXT, level TEXT, name TEXT, location TEXT
    )''')
    db_cursor.execute('''CREATE TABLE IF NOT EXISTS config (
        key TEXT PRIMARY KEY, value TEXT
    )''')
    db_conn.commit()

# 全域變數 (記憶體快取,供前端高速渲染)
orders_db = []
MENU = []
MEMBERS = {}
APP_CONFIG = {"bg_source": "default", "bg_url": "", "bg_file": "", "bg_opacity": 0.85}
ADMIN_PASSWORD = hash_pwd("0000") # 預設加密密碼

# 舊版檔案路徑 (供無縫升級轉移使用)
MENU_FILE = os.path.join(BASE_DIR, "menu.json")
PWD_FILE = os.path.join(BASE_DIR, "admin_pwd.json")
ORDERS_FILE = os.path.join(BASE_DIR, "orders.json")
MEMBERS_FILE = os.path.join(BASE_DIR, "members.json")
APP_CONFIG_FILE = os.path.join(BASE_DIR, "app_config.json")
BACKUP_FILE = os.path.join(BASE_DIR, "orders_backup.csv")
MENU_BACKUP_FILE = os.path.join(BASE_DIR, "menu_backup.csv")
MEMBERS_BACKUP_FILE = os.path.join(BASE_DIR, "members_backup.csv")

# ============================
# 📦 資料庫存取與無縫轉移邏輯
# ============================
def init_and_load_data():
    global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD
    
    with db_lock:
        db_cursor.execute("SELECT COUNT(*) FROM menu")
        m_cnt = db_cursor.fetchone()[0]
        db_cursor.execute("SELECT COUNT(*) FROM orders")
        o_cnt = db_cursor.fetchone()[0]
        
    # 【智慧轉移機制】如果 SQLite 裡沒有資料,但舊的檔案存在,就執行轉移
    if m_cnt == 0 and o_cnt == 0 and (os.path.exists(MENU_FILE) or os.path.exists(MENU_BACKUP_FILE) or os.path.exists(BACKUP_FILE)):
        print("🔄 偵測到舊版檔案資料,正在進行 SQLite 無縫升級轉移...")
        migrate_old_data()
    else:
        # 從強大的 SQLite 直接載入至記憶體
        with db_lock:
            # 載入訂單
            db_cursor.execute("SELECT * FROM orders ORDER BY time DESC")
            orders_db = [{
                "訂單編號": r[0], "狀態": r[1], "時間": r[2], "預定交期": r[3], "取貨方式": r[4], 
                "送貨地點": r[5], "顧客姓名": r[6], "商品": r[7], "單價": r[8], "成本": r[9], 
                "數量": r[10], "總價": r[11], "總成本": r[12], "備註": r[13]
            } for r in db_cursor.fetchall()]
            
            # 載入菜單
            db_cursor.execute("SELECT * FROM menu ORDER BY seq")
            MENU = [{
                "seq": r[0], "enable": bool(r[1]), "level": r[2], "category": r[3], "name": r[4], 
                "spec": r[5], "price": r[6], "cost": r[7], "note": r[8]
            } for r in db_cursor.fetchall()]
            
            # 載入會員
            db_cursor.execute("SELECT * FROM members")
            MEMBERS = {r[0]: {"password": r[1], "level": r[2], "name": r[3], "location": r[4]} for r in db_cursor.fetchall()}
            
            # 載入設定
            db_cursor.execute("SELECT * FROM config")
            for k, v in db_cursor.fetchall():
                if k == 'admin_pwd':
                    ADMIN_PASSWORD = v
                elif k == 'bg_opacity':
                    APP_CONFIG[k] = float(v)
                else:
                    APP_CONFIG[k] = v

def migrate_old_data():
    global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD
    
    # 載入舊 CSV 訂單 (優先)
    orders_db.clear()
    if os.path.exists(BACKUP_FILE):
        try:
            df = pd.read_csv(BACKUP_FILE, dtype={"訂單編號": str, "顧客姓名": str, "商品": str, "備註": str, "送貨地點": str, "時間": str, "訂單時間": str, "預定交期": str})
            df = df.fillna("")
            loaded_orders = df.to_dict('records')
            for o in loaded_orders:
                orders_db.append({
                    "訂單編號": str(o.get("訂單編號", "")), "狀態": str(o.get("狀態", "處理中")),
                    "時間": str(o.get("時間", "") or o.get("訂單時間", "")), "預定交期": str(o.get("預定交期", "")),
                    "取貨方式": str(o.get("取貨方式", "自取")), "送貨地點": str(o.get("送貨地點", "")),
                    "顧客姓名": str(o.get("顧客姓名", "")), "商品": str(o.get("商品", "")),
                    "單價": int(float(o.get("單價", 0) or 0)), "成本": int(float(o.get("成本", 0) or 0)),
                    "數量": int(float(o.get("數量", 0) or 0)), "總價": int(float(o.get("總價", 0) or 0)),
                    "總成本": int(float(o.get("總成本", 0) or 0)), "備註": str(o.get("備註", ""))
                })
        except: pass
    elif os.path.exists(ORDERS_FILE):
        try:
            with open(ORDERS_FILE, "r", encoding="utf-8") as f:
                orders_db = json.load(f)
                for o in orders_db: o["狀態"] = str(o.get("狀態", "處理中"))
        except: pass
            
    # 載入舊菜單
    MENU.clear()
    if os.path.exists(MENU_BACKUP_FILE):
        try:
            df = pd.read_csv(MENU_BACKUP_FILE, dtype={"品項": str, "規格": str, "分類": str, "備註": str, "適用等級": str})
            df = df.fillna("")
            for _, row in df.iterrows():
                val_enable = row.get("啟用", True)
                enable = val_enable.lower() in ["true", "1", "yes", "是", "t"] if isinstance(val_enable, str) else bool(val_enable)
                item = str(row.get("品項", "")).strip()
                if item:
                    MENU.append({
                        "name": item, "price": int(float(row.get("價格", 0) or 0)), "cost": int(float(row.get("成本", 0) or 0)), 
                        "enable": enable, "level": str(row.get("適用等級", "全部")).strip() or "全部", 
                        "seq": int(row.get("流水號", 999)), 
                        "category": str(row.get("分類", "未分類")).strip() or "未分類", 
                        "spec": str(row.get("規格", "")).strip(), "note": str(row.get("備註", "")).strip()
                    })
        except: pass
    elif os.path.exists(MENU_FILE):
        try:
            with open(MENU_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
                if isinstance(data, dict):
                    for k, v in data.items():
                        if isinstance(v, dict): v["name"], MENU = k, MENU + [v]
                        else: MENU.append({"name": k, "price": int(v), "cost": 0, "enable": True, "level": "全部", "seq": 999, "category": "未分類", "spec": "", "note": ""})
                elif isinstance(data, list): MENU.extend(data)
        except: pass
            
    # 載入舊會員 (並將舊的明文密碼進行加密)
    MEMBERS.clear()
    if os.path.exists(MEMBERS_BACKUP_FILE):
        try:
            df = pd.read_csv(MEMBERS_BACKUP_FILE, dtype=str).fillna("")
            for _, row in df.iterrows():
                acc = str(row.get("會員登入帳號", "")).strip()
                if acc:
                    MEMBERS[acc] = {
                        "password": hash_pwd(row.get("密碼", "")), "level": str(row.get("會員等級", "1")).strip(),
                        "name": str(row.get("顧客姓名", "")).strip(), "location": str(row.get("送貨地點", "")).strip()
                    }
        except: pass
    elif os.path.exists(MEMBERS_FILE):
        try:
            with open(MEMBERS_FILE, "r", encoding="utf-8") as f:
                old_mem = json.load(f)
                for acc, info in old_mem.items():
                    MEMBERS[acc] = {
                        "password": hash_pwd(info.get("password", "")), "level": str(info.get("level", "1")),
                        "name": str(info.get("name", "")), "location": str(info.get("location", ""))
                    }
        except: pass
                
    # 載入舊密碼
    if os.path.exists(PWD_FILE):
        try:
            with open(PWD_FILE, "r", encoding="utf-8") as f:
                ADMIN_PASSWORD = hash_pwd(json.load(f).get("password", "0000"))
        except: pass
            
    # 載入舊外觀設定
    if os.path.exists(APP_CONFIG_FILE):
        try:
            with open(APP_CONFIG_FILE, "r", encoding="utf-8") as f:
                APP_CONFIG.update(json.load(f))
        except: pass
            
    # 寫入至 SQLite
    save_menu_to_db()
    save_members_to_db()
    save_config_to_db()
    with db_lock:
        db_cursor.execute("DELETE FROM orders")
        for o in orders_db:
            db_cursor.execute('''INSERT OR IGNORE INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
                (o.get("訂單編號"), o.get("狀態"), o.get("時間"), o.get("預定交期"), o.get("取貨方式"), o.get("送貨地點"), o.get("顧客姓名"), o.get("商品"), o.get("單價"), o.get("成本"), o.get("數量"), o.get("總價"), o.get("總成本"), o.get("備註"))
            )
        db_conn.commit()

# --- 資料庫儲存與操作函數 (替代舊有的肥大 File I/O) ---
def add_order_to_db(o):
    with db_lock:
        orders_db.append(o)
        db_cursor.execute('''INSERT INTO orders VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)''',
            (o["訂單編號"], o.get("狀態"), o["時間"], o.get("預定交期"), o.get("取貨方式"), o.get("送貨地點"), o.get("顧客姓名"), o["商品"], o["單價"], o["成本"], o["數量"], o["總價"], o["總成本"], o.get("備註"))
        )
        db_conn.commit()

def save_menu_to_db():
    with db_lock:
        db_cursor.execute('DELETE FROM menu')
        for m in MENU:
            db_cursor.execute('INSERT INTO menu VALUES (?,?,?,?,?,?,?,?,?)', 
                (m.get("seq"), m.get("enable"), m.get("level"), m.get("category"), m.get("name"), m.get("spec"), m.get("price"), m.get("cost"), m.get("note")))
        db_conn.commit()

def save_members_to_db():
    with db_lock:
        db_cursor.execute('DELETE FROM members')
        for acc, info in MEMBERS.items():
            db_cursor.execute('INSERT INTO members VALUES (?,?,?,?,?)', 
                (acc, info.get("password"), info.get("level"), info.get("name"), info.get("location")))
        db_conn.commit()

def save_config_to_db(key=None, value=None):
    with db_lock:
        if key and value:
            db_cursor.execute('INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)', (key, str(value)))
        else:
            db_cursor.execute('DELETE FROM config WHERE key != "admin_pwd"')
            for k, v in APP_CONFIG.items():
                if k != "_cached_b64": db_cursor.execute('INSERT INTO config VALUES (?, ?)', (k, str(v)))
        db_conn.commit()

# 啟動時載入資料
init_and_load_data()


# ----------------------------
# 🎨 動態背景樣式產生函數
# ----------------------------
def generate_bg_css(config=None):
    if config is None:
        config = APP_CONFIG
        
    opacity = config.get("bg_opacity", 0.85)
    bg_source = config.get("bg_source", "default")
    
    if bg_source == "default":
        bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop"
    elif bg_source == "url":
        bg_url = config.get("bg_url", "")
        if not bg_url:
            bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop"
    elif bg_source == "upload":
        if "_cached_b64" in config:
            bg_url = f"data:image/jpeg;base64,{config['_cached_b64']}"
        else:
            bg_file = config.get("bg_file", "custom_bg.jpg")
            bg_path = os.path.join(BASE_DIR, bg_file)
            if os.path.exists(bg_path):
                try:
                    with open(bg_path, "rb") as f:
                        b64 = base64.b64encode(f.read()).decode("utf-8")
                    config["_cached_b64"] = b64 
                    bg_url = f"data:image/jpeg;base64,{b64}"
                except:
                    bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop"
            else:
                bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop"
    else:
        bg_url = "https://images.unsplash.com/photo-1495474472207-464ba5231c2c?q=80&w=2000&auto=format&fit=crop"

    return f"""
    <style>
    body, .gradio-container {{
        background-image: linear-gradient(rgba(255, 255, 255, {opacity}), rgba(255, 255, 255, {opacity})), url('{bg_url}') !important;
        background-size: cover !important;
        background-attachment: fixed !important;
        background-position: center !important;
    }}
    </style>
    """

# ----------------------------
# 💻 網頁 UI 資料獲取函數 (Data Fetchers)
# ----------------------------
def get_frontend_menu_items(user_level="全部"):
    enabled_items = []
    for item_dict in MENU:
        if not item_dict.get("enable", True): continue
        item_lvl = str(item_dict.get("level", "全部")).strip()
        if user_level == "admin" or item_lvl == "全部" or item_lvl == str(user_level):
            enabled_items.append(item_dict)
            
    enabled_items = sorted(enabled_items, key=lambda x: x.get("seq", 999))
    category_order = []
    items_by_cat = {}
    
    for details in enabled_items:
        cat = details.get("category", "未分類")
        cat = cat.strip() if cat.strip() else "未分類"
        if cat not in category_order: category_order.append(cat)
        items_by_cat.setdefault(cat, []).append((details.get("name", "未命名"), details))
        
    flat_list = []
    for cat in category_order:
        flat_list.extend(items_by_cat[cat])
        
    return category_order, items_by_cat, flat_list

def get_menu_cat_choices():
    cats = list(dict.fromkeys([m.get("category", "未分類") for m in MENU]))
    return ["全部分類"] + cats

def get_menu_lvl_choices():
    lvls = list(dict.fromkeys([str(m.get("level", "全部")) for m in MENU]))
    return ["全部等級"] + lvls

def get_menu_item_choices():
    items = list(dict.fromkeys([m.get("name", "") for m in MENU if m.get("name")]))
    return ["所有品項"] + items

def get_menu_df_for_export():
    sorted_menu = sorted(MENU, key=lambda x: x.get("seq", 999))
    data = []
    for v in sorted_menu:
        data.append([v.get("seq", 999), v.get("enable", True), v.get("level", "全部"), v.get("category", "未分類"), v.get("name", ""), v.get("spec", ""), v.get("price", 0), v.get("cost", 0), v.get("note", "")])
    return pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"])

def get_menu_df(cat_filter="全部分類", lvl_filter="全部等級", item_filter="所有品項"):
    filtered_menu = MENU
    if cat_filter != "全部分類": filtered_menu = [m for m in filtered_menu if m.get("category", "未分類") == cat_filter]
    if lvl_filter != "全部等級": filtered_menu = [m for m in filtered_menu if str(m.get("level", "全部")) == lvl_filter]
    if item_filter != "所有品項": filtered_menu = [m for m in filtered_menu if m.get("name", "") == item_filter]

    sorted_menu = sorted(filtered_menu, key=lambda x: x.get("seq", 999))
    data = []
    for v in sorted_menu:
        data.append([v.get("seq", 999), v.get("enable", True), v.get("level", "全部"), v.get("category", "未分類"), v.get("name", ""), v.get("spec", ""), v.get("price", 0), v.get("cost", 0), v.get("note", "")])
        
    df = pd.DataFrame(data, columns=["流水號", "啟用", "適用等級", "分類", "品項", "規格", "價格", "成本", "備註"])
    if not df.empty: df["品項"] = df["品項"].astype(str)
    return df

def get_members_df():
    data = []
    for acc, info in MEMBERS.items():
        data.append([acc, "***", info.get("level", "1"), info.get("name", ""), info.get("location", "")])
        
    df = pd.DataFrame(data, columns=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"], dtype=str)
    return df

def get_customer_choices():
    customers = []
    for o in orders_db:
        if o.get("顧客姓名") and o["顧客姓名"] not in customers: customers.append(o["顧客姓名"])
    return ["所有顧客"] + customers

def get_time_choices():
    times = set()
    for o in orders_db:
        dt_str = o.get("時間", "") or o.get("訂單時間", "")
        if len(dt_str) >= 10: times.add(dt_str[:10]); times.add(dt_str[:7])  
    return ["所有時間"] + sorted(list(times), reverse=True)

def get_item_choices():
    items = []
    for o in orders_db:
        if o.get("商品") and o["商品"] not in items: items.append(o["商品"])
    return ["所有商品"] + items

def get_delivery_choices():
    deliveries = []
    for o in orders_db:
        d = o.get("預定交期", "")
        if d and d not in deliveries: deliveries.append(d)
    return ["所有交期"] + deliveries

def get_orders_data(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"):
    filtered_db = orders_db
    if filter_name != "所有顧客": filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name]
    if filter_time != "所有時間": filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)]
    if filter_item != "所有商品": filtered_db = [o for o in filtered_db if o.get("商品") == filter_item]
    if filter_delivery != "所有交期": filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
        
    if not filtered_db: return [[""] * 14] 
        
    return [[
        o.get("訂單編號", ""), o.get("狀態", "處理中"), o.get("時間", "") or o.get("訂單時間", ""), 
        o.get("預定交期", ""), o.get("取貨方式", "自取"), o.get("送貨地點", ""), o.get("顧客姓名", ""), 
        o.get("商品", ""), o.get("單價", 0), o.get("成本", 0), o.get("數量", 0), 
        o.get("總價", 0), o.get("總成本", 0), o.get("備註", "")
    ] for o in filtered_db]

def get_revenue(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"):
    filtered_db = orders_db
    if filter_name != "所有顧客": filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name]
    if filter_time != "所有時間": filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)]
    if filter_item != "所有商品": filtered_db = [o for o in filtered_db if o.get("商品") == filter_item]
    if filter_delivery != "所有交期": filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
        
    total_revenue = sum(o.get("總價", 0) for o in filtered_db)
    total_cost = sum(o.get("總成本", 0) for o in filtered_db)
    profit = total_revenue - total_cost
    
    title_parts = []
    if filter_name != "所有顧客": title_parts.append(f"【{filter_name}】")
    if filter_time != "所有時間": title_parts.append(f"【{filter_time}】")
    if filter_item != "所有商品": title_parts.append(f"【{filter_item}】")
    if filter_delivery != "所有交期": title_parts.append(f"【{filter_delivery}】")
    
    prefix = "💰 " + "".join(title_parts) + " 的總消費" if title_parts else "💰 目前總營收"
    profit_prefix = "📈 篩選總毛利" if title_parts else "📈 目前總毛利"
    
    return f"### {prefix}:NT$ {total_revenue} &nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp; {profit_prefix}:NT$ {profit}"


# -----------------
# 📝 UI 動作處理操作 (Actions)
# -----------------
def save_single_member(acc, pwd, lvl, name, loc):
    global MEMBERS
    acc = str(acc).strip() if acc else ""
    if not acc: return gr.update(value="❌ 錯誤:會員登入帳號不可為空!"), gr.update()
        
    pwd_to_save = MEMBERS.get(acc, {}).get("password", "")
    if pwd and pwd.strip() != "***":
        pwd_to_save = hash_pwd(pwd.strip())

    MEMBERS[acc] = {"password": pwd_to_save, "level": str(lvl).strip() if lvl else "1", "name": str(name).strip() if name else "", "location": str(loc).strip() if loc else ""}
    save_members_to_db()
    
    msg = f"✅ 會員 {acc} 已儲存成功!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"
    return gr.update(value=msg), get_members_df()

def delete_single_member(acc):
    global MEMBERS
    acc = str(acc).strip() if acc else ""
    if not acc: return gr.update(value="❌ 錯誤:請先選擇要刪除的會員帳號!"), gr.update()
        
    if acc in MEMBERS:
        del MEMBERS[acc]
        save_members_to_db()
        return gr.update(value=f"🗑️ 會員 {acc} 已刪除!"), get_members_df()
    return gr.update(value=f"❌ 找不到會員 {acc}"), gr.update()

def change_password(old_pwd, new_pwd):
    global ADMIN_PASSWORD
    if not new_pwd.strip(): return gr.update(value="❌ 新密碼不能為空白!")
    if hash_pwd(old_pwd) != ADMIN_PASSWORD:
        return gr.update(value="❌ 舊密碼輸入錯誤,請重新確認!")
    
    ADMIN_PASSWORD = hash_pwd(new_pwd.strip())
    save_config_to_db('admin_pwd', ADMIN_PASSWORD)
    return gr.update(value=f"✅ 密碼修改成功!下次登入請使用新密碼。({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})")

def calc_cart_summary(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
    user_level = "全部"
    if current_user == "admin": user_level = "admin"
    elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1")
        
    _, _, flat_list = get_frontend_menu_items(user_level)
    c_name = str(c_name).strip() if c_name else ""
    
    quantities = []
    for q in qty_args:
        try: quantities.append(int(q))
        except: quantities.append(0)
            
    if sum(quantities) == 0:
        return "❌ **購物車是空的,請先在上方選擇商品數量!**", gr.update(visible=False)
        
    if not c_name:
        return "❌ **請先輸入上方的「顧客姓名」才能結帳!**", gr.update(visible=False)

    total_order_price = 0
    items_desc = []
    for i, qty in enumerate(quantities):
        if qty > 0:
            item_name, details = flat_list[i]
            price = details["price"]
            spec = details.get("spec", "")
            item_note = f" ({spec})" if spec else ""
            total_price = price * qty
            total_order_price += total_price
            items_desc.append(f"- ✅ **{item_name}**{item_note} x {qty} = {total_price} 元")
            
    md = "### 🛒 購物車明細確認\n"
    md += f"**顧客姓名**:{c_name} \n"
    md += f"**取貨方式**:{p_method}" + (f" (地點:{d_location})" if p_method == "送貨" else "") + " \n"
    md += f"**預定交期**:{d_month}{d_day} {d_time} \n"
    md += "**備註留言**:" + (nts if nts else "無") + " \n\n"
    md += "**【已選商品】**\n"
    md += "\n".join(items_desc)
    md += f"\n\n💰 **結帳總金額:NT$ {total_order_price}**"
    
    return md, gr.update(visible=True)

def add_order(current_user, c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
    try:
        user_level = "全部"
        if current_user == "admin": user_level = "admin"
        elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1")
            
        _, _, flat_list = get_frontend_menu_items(user_level)
        
        c_name = str(c_name).strip() if c_name else ""
        nts = str(nts).strip() if nts else ""
        delivery_date = f"{d_month}{d_day} {d_time}" if d_time != "盡快" else "盡快"
        
        quantities = []
        for q in qty_args:
            try: quantities.append(int(q))
            except: quantities.append(0)
                
        reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
        timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S")
        total_order_price = 0
        items_desc = []
        
        for i, qty in enumerate(quantities):
            if qty > 0:
                item_name, details = flat_list[i]
                price = details["price"]
                cost = details.get("cost", 0)
                spec = details.get("spec", "")
                
                item_note = f"({spec})" if spec else ""
                total_price = price * qty
                total_cost = cost * qty
                total_order_price += total_price
                
                order_id = str(uuid.uuid4())[:6].upper()
                final_note = f"{item_note} {nts}".strip() if item_note else nts
                
                # 優化:直接呼叫 DB 操作,取代笨重的 JSON Rewrite
                add_order_to_db({
                    "訂單編號": order_id, "狀態": "處理中", "時間": timestamp, 
                    "預定交期": delivery_date, "取貨方式": p_method,
                    "送貨地點": d_location if p_method == "送貨" else "",
                    "顧客姓名": c_name, "商品": item_name, "單價": price, 
                    "成本": cost, "數量": qty, "總價": total_price, 
                    "總成本": total_cost, "備註": final_note
                })
                desc = f"{item_name}{item_note}x{qty}"
                items_desc.append(desc)
                
        if not items_desc: return [gr.update(value="❌ 錯誤:請至少選擇一項商品的數量")] + reset_qtys
        
        msg = f"🎉 訂單已成功送出!{c_name} 共訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
        return [gr.update(value=msg), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*訂單已送出,請重新選擇商品*")] + reset_qtys
    except Exception as e:
        reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
        return [gr.update(value=f"❌ 系統異常:{str(e)}"), gr.update(visible=False), gr.update(value="### 🛒 購物車明細\n*發生錯誤*")] + reset_qtys

def update_order_status(order_id, new_status, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
    if order_id == "__CANCEL__": return gr.update(), gr.update(), gr.update()
    order_id = str(order_id).strip()
    if not order_id: return gr.update(value="❌ 錯誤:請先點擊上方表格選擇訂單!"), gr.update(), gr.update()
        
    found = False
    with db_lock:
        for o in orders_db:
            if o.get("訂單編號") == order_id:
                o["狀態"] = new_status
                found = True
        if found:
            db_cursor.execute('UPDATE orders SET status = ? WHERE order_id = ?', (new_status, order_id))
            db_conn.commit()
            
    if not found: return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update()
    
    return (
        gr.update(value=f"✅ 成功將訂單 {order_id} 標記為『{new_status}』"),
        gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
        gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter))
    )

def delete_single_order(order_id, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
    if order_id == "__CANCEL__": return gr.update(), gr.update(), gr.update(), gr.update()
        
    global orders_db
    order_id = str(order_id).strip()
    if not order_id: return gr.update(value="❌ 錯誤:請輸入要刪除的訂單編號!"), gr.update(), gr.update(), gr.update()
        
    with db_lock:
        original_len = len(orders_db)
        orders_db = [o for o in orders_db if o.get("訂單編號") != order_id]
        if len(orders_db) == original_len:
            return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update(), gr.update()
        db_cursor.execute('DELETE FROM orders WHERE order_id = ?', (order_id,))
        db_conn.commit()
        
    return (
        gr.update(value=f"✅ 成功永久刪除訂單:{order_id}"),
        gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
        gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
        gr.update(value="") 
    )

def clear_orders(filter_val):
    if filter_val == "__CANCEL__": return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
    with db_lock:
        orders_db.clear()
        db_cursor.execute('DELETE FROM orders')
        db_conn.commit()
    return (
        gr.update(value="🗑️ 所有訂單已清空"), 
        gr.update(value=get_orders_data("所有顧客", "所有時間", "所有商品", "所有交期")), 
        gr.update(value=get_revenue("所有顧客", "所有時間", "所有商品", "所有交期")),
        gr.update(choices=["所有顧客"], value="所有顧客"),
        gr.update(choices=["所有時間"], value="所有時間"),
        gr.update(choices=["所有商品"], value="所有商品"),
        gr.update(choices=["所有交期"], value="所有交期")
    )

def refresh_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter):
    c_choices = get_customer_choices()
    if current_filter not in c_choices: current_filter = "所有顧客"
    t_choices = get_time_choices()
    if current_time_filter not in t_choices: current_time_filter = "所有時間"
    i_choices = get_item_choices()
    if current_item_filter not in i_choices: current_item_filter = "所有商品"
    d_choices = get_delivery_choices()
    if current_delivery_filter not in d_choices: current_delivery_filter = "所有交期"
        
    return (
        gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)), 
        gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
        gr.update(choices=c_choices, value=current_filter),
        gr.update(choices=t_choices, value=current_time_filter),
        gr.update(choices=i_choices, value=current_item_filter),
        gr.update(choices=d_choices, value=current_delivery_filter)
    )

def do_login(acc, pwd):
    acc = acc.strip()
    pwd = pwd.strip()
    
    if not acc:
        return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 請輸入帳號!"), "", gr.update(value=""), gr.update(value=""))
        
    if acc == "admin":
        if hash_pwd(pwd) == ADMIN_PASSWORD:
            return (gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(value=""), "admin", gr.update(value="👋 **管理員 您好!**"), gr.update(value=""))
        else:
            return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 管理員密碼錯誤!"), "", gr.update(value=""), gr.update(value=""))
            
    else:
        # 會員登入防護
        if acc in MEMBERS and MEMBERS[acc].get("password") == hash_pwd(pwd):
            user_name = MEMBERS[acc].get("name", acc)
            return (gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(value=""), acc, gr.update(value=f"👋 **會員 {user_name} 您好!**"), gr.update(value=""))
        else:
            return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value="❌ 帳號或密碼錯誤!"), "", gr.update(value=""), gr.update(value=""))

def logout():
    return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(value=""), gr.update(value=""), gr.update(value=""), "", gr.update(value=""), gr.update(value=""))

def run_git_cmd(command):
    result = subprocess.run(command, shell=True, text=True, capture_output=True)
    if result.returncode == 0: return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
    return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"

def backup_and_push_to_github():
    log_messages = ["🚀 開始匯出資料庫備份並推送至 GitHub...\n" + "-"*40]
    
    # 將 SQLite 狀態還原匯出成 CSV 以便外部使用與備份
    if not orders_db:
        df = pd.DataFrame(columns=["訂單編號", "狀態", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"])
    else:
        export_data = []
        for o in orders_db:
            export_data.append({"訂單編號": o.get("訂單編號", ""), "狀態": o.get("狀態", "處理中"), "訂單時間": o.get("時間", "") or o.get("訂單時間", ""), "預定交期": o.get("預定交期", ""), "取貨方式": o.get("取貨方式", "自取"), "送貨地點": o.get("送貨地點", ""), "顧客姓名": o.get("顧客姓名", ""), "商品": o.get("商品", ""), "單價": o.get("單價", 0), "成本": o.get("成本", 0), "數量": o.get("數量", 0), "總價": o.get("總價", 0), "總成本": o.get("總成本", 0), "備註": o.get("備註", "")})
        df = pd.DataFrame(export_data)
        
    df.to_csv(BACKUP_FILE, index=False, encoding="utf-8-sig")
    get_menu_df_for_export().to_csv(MENU_BACKUP_FILE, index=False, encoding="utf-8-sig")
    get_members_df().to_csv(MEMBERS_BACKUP_FILE, index=False, encoding="utf-8-sig")
    
    # 匯出 SQLite 主檔
    log_messages.append(f"💾 已封裝 SQLite 資料庫: {DB_FILE}")

    run_git_cmd('git config user.email "bot@example.com"')
    run_git_cmd('git config user.name "AutoBackupBot"')
    
    success, msg = run_git_cmd("git add .")
    log_messages.append(msg)
    
    commit_msg = f"自動備份: {datetime.now(TAIPEI_TZ).strftime('%Y-%m-%d %H:%M:%S')}"
    success, msg = run_git_cmd(f'git commit -m "{commit_msg}"')
    log_messages.append(msg)
    
    if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
        log_messages.append("ℹ️ 無變更。\n✅ 結束。")
        return gr.update(value="\n\n".join(log_messages))

    hf_token = os.environ.get("HF_TOKEN")
    if hf_token:
        repo_url = f"https://oauth2:{hf_token}@huggingface.co/spaces/schillercfk/ssys"
        run_git_cmd(f"git remote set-url origin {repo_url}")
    else:
        log_messages.append("⚠️ 警告:未偵測到 HF_TOKEN!若上傳失敗請至 Settings 設定。")

    success, msg = run_git_cmd("git push origin main")
    log_messages.append(msg)
    
    if success:
        log_messages.append("🎉 雲端備份完成!\n\n⚠️ 【重要提示】:\n因為資料已推送至雲端,系統將自動重新啟動來套用變更。\n這看起來會像「網頁當機」或「連線中斷」,這是正常的重新佈署過程!\n👉 請稍候約 30 秒至 1 分鐘,然後「重新整理網頁」即可恢復正常。")
    else:
        log_messages.append("❌ 上傳失敗:請檢查 Hugging Face 專案 Settings -> Variables and secrets 是否有設定具備 Write 權限的 HF_TOKEN。")
        
    return gr.update(value="\n\n".join(log_messages))

def restore_from_backup():
    # 備份還原邏輯 (從 CSV 讀取覆寫進 SQLite)
    global orders_db, MENU, MEMBERS, APP_CONFIG, ADMIN_PASSWORD
    msg = ""
    try:
        with db_lock:
            db_cursor.execute('DELETE FROM orders')
            db_cursor.execute('DELETE FROM menu')
            db_cursor.execute('DELETE FROM members')
            db_conn.commit()
            orders_db.clear()
            MENU.clear()
            MEMBERS.clear()
            
        migrate_old_data()
        msg += "✅ 成功從備份檔進行 SQLite 資料庫重建!"
    except Exception as e:
        msg += f"❌ 資料庫重建失敗:{e}"

    cats = get_menu_cat_choices()
    lvls = get_menu_lvl_choices()
    items = get_menu_item_choices()
    
    init_source = APP_CONFIG.get("bg_source", "default")
    init_source_str = {"default": "預設圖片", "url": "自訂網址", "upload": "上傳圖片"}.get(init_source, "預設圖片")

    return (
        gr.update(value=msg), get_members_df(), datetime.now(TAIPEI_TZ).timestamp(),
        gr.update(choices=cats, value="全部分類"), gr.update(choices=lvls, value="全部等級"), gr.update(choices=items, value="所有品項"),
        generate_bg_css(APP_CONFIG), gr.update(value=init_source_str), gr.update(value=APP_CONFIG.get("bg_url", "")), gr.update(value=APP_CONFIG.get("bg_opacity", 0.85))
    )

def autofill_delete_target(evt: gr.SelectData, df_data):
    try:
        return str(df_data.iloc[evt.index[0], 0])
    except: return ""

def autofill_member_form(evt: gr.SelectData, df_data):
    try:
        row_idx = evt.index[0]
        return (df_data.iloc[row_idx, 0], df_data.iloc[row_idx, 1], df_data.iloc[row_idx, 2], df_data.iloc[row_idx, 3], df_data.iloc[row_idx, 4])
    except: return "", "", "1", "", ""


# ----------------------------
# 🖥️ 網頁介面 (UI)
# ----------------------------
custom_css = """
/* 強制置中對齊用的 Column */
.center-col { display: flex !important; flex-direction: column !important; justify-content: center !important; align-items: center !important; margin: auto 0 !important; }
.menu-row { border-bottom: 1px solid #e5e7eb; padding: 12px 0; align-items: center; flex-wrap: nowrap !important; gap: 8px !important; }
.menu-header { border-bottom: 2px solid #cbd5e1; padding: 8px 0; align-items: center; flex-wrap: nowrap !important; gap: 8px !important; background-color: #f8fafc; border-radius: 8px 8px 0 0; margin-bottom: 8px; }
.qty-group { display: flex !important; flex-wrap: nowrap !important; flex-direction: row !important; align-items: center !important; justify-content: center !important; gap: 4px !important; width: 100% !important; background: transparent !important; margin: auto !important; }
.qty-group > * { min-width: 0 !important; flex: 0 0 auto !important; margin: 0 !important; }
.action-btn { font-size: 18px !important; font-weight: bold !important; border-radius: 8px !important; padding: 0 !important; width: 36px !important; height: 36px !important; min-width: 36px !important; display: flex !important; justify-content: center !important; align-items: center !important; flex-shrink: 0 !important; cursor: pointer !important; }
.qty-input { min-width: 45px !important; width: 45px !important; flex-shrink: 0 !important; border: none !important; box-shadow: none !important; background: transparent !important; }
.qty-input input { text-align: center !important; font-size: 18px !important; font-weight: bold !important; pointer-events: none !important; touch-action: none !important; padding: 0 !important; height: 36px !important; background: transparent !important; }
.github-log textarea { font-family: monospace; background-color: #1e1e1e; color: #00ff00; }
.login-box { max-width: 400px; margin: 0 auto !important; padding: 20px; border: 1px solid #e5e7eb; border-radius: 10px; background: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.horizontal-menu-admin { display: flex !important; flex-wrap: nowrap !important; overflow-x: auto !important; gap: 16px !important; padding: 16px 8px !important; align-items: stretch !important; scrollbar-width: thin; }
.horizontal-menu-admin::-webkit-scrollbar { height: 8px; }
.horizontal-menu-admin::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
.menu-card-admin { min-width: 300px !important; width: 300px !important; flex: 0 0 auto !important; background: rgba(255, 255, 255, 0.95) !important; border: 1px solid #e2e8f0 !important; border-radius: 12px !important; padding: 16px !important; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1) !important; display: flex !important; flex-direction: column !important; gap: 8px !important; }
.new-card-admin { background: rgba(248, 250, 252, 0.95) !important; border: 2px dashed #cbd5e1 !important; }
"""

kill_badge_js = """
function() {
    if (window.location.search.includes("openExternalBrowser")) {
        const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
        window.history.replaceState({path: newUrl}, "", newUrl);
    }
    const nukeHF = () => {
        ['huggingface-space-header', 'huggingface-workspace-badge', 'huggingface-space-badge'].forEach(tag => { document.querySelectorAll(tag).forEach(el => el.remove()); });
        if (document.body) {
            Array.from(document.body.children).forEach(el => {
                if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'LINK') return;
                if (el.classList.contains('gradio-container-wrap') || el.querySelector('.gradio-container') || el.id === 'custom-css-injector' || el.id === 'dynamic-bg-css-injector') return;
                const html = el.innerHTML || '';
                if (html.includes('huggingface.co') || html.includes('Sign in') || html.includes('Duplicate Space') || html.includes('Log in')) { el.style.setProperty('display', 'none', 'important'); el.remove(); }
            });
            document.body.style.setProperty('padding-top', '0px', 'important');
            document.body.style.setProperty('margin-top', '0px', 'important');
        }
        document.querySelectorAll('.gradio-container-header, footer').forEach(el => el.remove());
        if (document.documentElement) document.documentElement.style.setProperty('padding-top', '0px', 'important');
    };
    const style = document.createElement('style');
    style.innerHTML = `huggingface-space-header, huggingface-workspace-badge, huggingface-space-badge { display: none !important; opacity: 0 !important; position: absolute !important; pointer-events: none !important; } .gradio-container-header, footer { display: none !important; }`;
    document.head.appendChild(style);
    
    // 【優化】降低掃描頻率至 500ms,減少前端設備(手機)的 CPU 算力消耗與發熱問題
    setInterval(nukeHF, 500);
    new MutationObserver(nukeHF).observe(document.documentElement, { childList: true, subtree: true });
    nukeHF();
    return [];
}
"""

with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統") as demo_ui:
    gr.HTML(f"<style>{custom_css}</style>", elem_id="custom-css-injector")
    dynamic_bg_html = gr.HTML(elem_id="dynamic-bg-css-injector")

    menu_trigger = gr.State(value=0)
    current_user_state = gr.State(value="")
    
    gr.Markdown("<h1 style='text-align: center; margin-top: 20px;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
    
    with gr.Column(visible=True, elem_classes="login-box") as login_container:
        gr.Markdown("<h2 style='text-align: center;'>🔐 會員登入</h2>")
        login_acc = gr.Textbox(label="會員帳號", placeholder="請輸入帳號")
        login_pwd = gr.Textbox(label="密碼", type="password", placeholder="請輸入密碼")
        login_btn = gr.Button("登入系統", variant="primary", size="lg")
        login_msg = gr.Markdown(value="")

    with gr.Column(visible=False) as main_container:
        with gr.Row(elem_classes="menu-row"):
            user_greeting = gr.Markdown(value="")
            global_sys_msg = gr.Markdown(value="") 
            logout_btn = gr.Button("🚪 登出系統", size="sm", min_width=100, scale=0)

        with gr.Tabs() as main_tabs:
            with gr.TabItem("📝 現場/網頁新增訂單"):
                @gr.render(inputs=[current_user_state, menu_trigger])
                def render_order_form(current_user, m_trigger):
                    if not current_user:
                        return gr.Markdown("")
                        
                    user_level = "全部"
                    if current_user == "admin": user_level = "admin"
                    elif current_user in MEMBERS: user_level = MEMBERS[current_user].get("level", "1")

                    default_name = MEMBERS[current_user].get("name", "") if current_user != "admin" and current_user in MEMBERS else ""
                    default_loc = MEMBERS[current_user].get("location", "") if current_user != "admin" and current_user in MEMBERS else ""
                    default_method = "送貨" if default_loc else "自取"

                    with gr.Row():
                        with gr.Column():
                            customer_name = gr.Textbox(label="顧客姓名", placeholder="請輸入姓名", value=default_name)
                            
                            gr.Markdown("#### 📦 取貨方式與地點")
                            with gr.Row():
                                pickup_method = gr.Radio(choices=["自取", "送貨"], value=default_method, label="取貨方式", interactive=True)
                                delivery_location = gr.Textbox(label="送貨地點", placeholder="請輸入送貨地點", value=default_loc, visible=(default_method == "送貨"), interactive=True)
                            pickup_method.change(fn=lambda m: gr.update(visible=(m == "送貨")), inputs=[pickup_method], outputs=[delivery_location])
                            
                            gr.Markdown("#### 🕒 預定交期")
                            with gr.Row():
                                current_month = datetime.now(TAIPEI_TZ).strftime("%m月")
                                current_day = datetime.now(TAIPEI_TZ).strftime("%d日")
                                delivery_month = gr.Dropdown(choices=[f"{i:02d}月" for i in range(1, 13)], label="月", value=current_month, interactive=True)
                                delivery_day = gr.Dropdown(choices=[f"{i:02d}日" for i in range(1, 32)], label="日", value=current_day, interactive=True)
                                time_choices = ["盡快"] + [f"{h:02d}:{m:02d}" for h in range(0, 24) for m in (0, 15, 30, 45)]
                                delivery_time = gr.Dropdown(choices=time_choices, label="時間", value="盡快", interactive=True)
                                
                            gr.Markdown("#### 🛍️ 選擇商品與數量")
                            quantity_components = []
                            pic_dir = os.path.join(BASE_DIR, "pic")
                            if not os.path.exists(pic_dir): os.makedirs(pic_dir, exist_ok=True)
                            
                            category_order, items_by_cat, flat_list = get_frontend_menu_items(user_level)
                            if not category_order: gr.Markdown("目前尚無提供商品,請至後台設定菜單。")
                                
                            with gr.Tabs():
                                for cat in category_order:
                                    with gr.TabItem(cat):
                                        with gr.Row(elem_classes="menu-header"):
                                            with gr.Column(scale=0, min_width=60, elem_classes="center-col"): gr.HTML("<div style='text-align: center; font-weight: bold; color: #64748b; font-size: 0.9em;'>圖示</div>")
                                            with gr.Column(scale=1, min_width=150, elem_classes="center-col"): gr.HTML("<div style='display: flex; width: 100%; text-align: center; font-weight: bold; color: #64748b; font-size: 0.9em;'><div style='flex: 1;'>商品名稱</div><div style='flex: 1;'>規格</div><div style='flex: 1;'>單價</div></div>")
                                            with gr.Column(scale=0, min_width=140, elem_classes="center-col"): gr.HTML("<div style='text-align: center; font-weight: bold; color: #64748b; font-size: 0.9em; width: 100%;'>數量</div>")
                                        
                                        for item_name, details in items_by_cat[cat]:
                                            price = details["price"]
                                            spec = details.get("spec", "")
                                            with gr.Row(elem_classes="menu-row"):
                                                with gr.Column(scale=0, min_width=60, elem_classes="center-col"):
                                                    found_img_path = next((os.path.join(pic_dir, f"{item_name}{ext}") for ext in ['.jpg', '.jpeg', '.png', '.JPG', '.PNG'] if os.path.exists(os.path.join(pic_dir, f"{item_name}{ext}"))), None)
                                                    if found_img_path:
                                                        try:
                                                            with open(found_img_path, "rb") as img_file: b64 = base64.b64encode(img_file.read()).decode('utf-8')
                                                            mtype = "image/png" if found_img_path.lower().endswith(".png") else "image/jpeg"
                                                            gr.HTML(value=f'<div style="width: 60px; height: 60px; border-radius: 8px; overflow: hidden; margin: 0 auto; pointer-events: none; background: white;"><img src="data:{mtype};base64,{b64}" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;"></div>')
                                                        except: gr.HTML(value=f'<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">{item_name[0] if item_name else "品"}</div>')
                                                    else: gr.HTML(value=f'<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">{item_name[0] if item_name else "品"}</div>')

                                                with gr.Column(scale=1, min_width=150, elem_classes="center-col"):
                                                    spec_html = f"<span style='font-size: 0.85em; color: #ef4444; padding: 2px 6px; background: #fee2e2; border-radius: 4px;'>{spec}</span>" if spec else ""
                                                    gr.HTML(f"<div style='display: flex; width: 100%; align-items: center; text-align: center; margin: auto 0;'><div style='flex: 1; font-weight: bold; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'>{item_name}</div><div style='flex: 1;'>{spec_html}</div><div style='flex: 1; color: gray; font-size: 0.9em; white-space: nowrap;'>NT$ {price}</div></div>")
                                                
                                                with gr.Column(scale=0, min_width=140, elem_classes="center-col"):
                                                    with gr.Row(elem_classes="qty-group"):
                                                        minus_btn = gr.Button("➖", elem_classes="action-btn", variant="secondary", min_width=36)
                                                        qty_box = gr.Textbox(value="0", show_label=False, interactive=True, elem_classes="qty-input", container=False, min_width=45)
                                                        plus_btn = gr.Button("➕", elem_classes="action-btn", variant="secondary", min_width=36)
                                                    minus_btn.click(fn=None, inputs=[qty_box], outputs=[qty_box], js="(v) => { let n = parseInt(v || 0); return Math.max(0, n - 1).toString(); }")
                                                    plus_btn.click(fn=None, inputs=[qty_box], outputs=[qty_box], js="(v) => { let n = parseInt(v || 0); return (n + 1).toString(); }")
                                                    quantity_components.append(qty_box)
                            
                            notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
                            gr.Markdown("---")
                            cart_summary = gr.Markdown("### 🛒 購物車明細\n*尚未計算,請點擊下方按鈕確認*")
                            calc_btn = gr.Button("💰 結算總金額與明細", variant="secondary", size="lg")
                            submit_btn = gr.Button("🚀 確認無誤,正式送出訂單", variant="primary", size="lg", visible=False)
                            status_msg = gr.Textbox(label="系統狀態", interactive=False)
                            
                            inputs_list = [current_user_state, customer_name, pickup_method, delivery_location, delivery_month, delivery_day, delivery_time, notes] + quantity_components
                            calc_btn.click(fn=calc_cart_summary, inputs=inputs_list, outputs=[cart_summary, submit_btn])
                            submit_btn.click(fn=add_order, inputs=inputs_list, outputs=[status_msg, submit_btn, cart_summary] + quantity_components)

            with gr.TabItem("📊 系統管理與總覽", visible=False, id="admin_tab") as admin_tab:
                with gr.Accordion("☁️ 雲端備份與還原 (點擊展開/收合)", open=True):
                    with gr.Row():
                        github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
                        restore_btn = gr.Button("📥 從備份還原", variant="secondary")
                    github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=5, elem_classes="github-log")
                
                with gr.Tabs():
                    with gr.TabItem("📊 訂單詳細數據"):
                        revenue_display = gr.Markdown(value=get_revenue())
                        with gr.Row():
                            customer_filter = gr.Dropdown(choices=["所有顧客"], value="所有顧客", label="🔍 篩選顧客", interactive=True)
                            time_filter = gr.Dropdown(choices=["所有時間"], value="所有時間", label="📅 篩選訂單時間", interactive=True)
                            item_filter = gr.Dropdown(choices=["所有商品"], value="所有商品", label="🍔 篩選商品", interactive=True)
                            delivery_filter = gr.Dropdown(choices=["所有交期"], value="所有交期", label="🕒 篩選預定交期", interactive=True)
                            refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
                        
                        orders_table = gr.Dataframe(value=get_orders_data(), headers=["訂單編號", "狀態", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"], interactive=False)
                        
                        gr.Markdown("---")
                        gr.Markdown("### 🚦 訂單狀態管理 (點擊表格自動帶入)")
                        with gr.Row(elem_classes="menu-row"):
                            with gr.Column(scale=2): delete_target = gr.Textbox(label="操作對象 (訂單編號)", placeholder="👉 點擊上方表格中的訂單")
                            with gr.Column(scale=1): mark_done_btn = gr.Button("✅ 標記為 已完成", variant="primary")
                            with gr.Column(scale=1): mark_cancel_btn = gr.Button("⏸️ 標記為 已取消", variant="secondary")
                            with gr.Column(scale=1): delete_single_btn = gr.Button("🗑️ 永久刪除", variant="stop")
                                
                        admin_status_msg = gr.Textbox(label="狀態提示", interactive=False)
                        clear_btn = gr.Button("🚨 清空所有歷史訂單", variant="stop")
                    
                    with gr.TabItem("📝 菜單管理 (橫向卡片)"):
                        gr.Markdown("✅ **適用等級**:輸入 `1` 至 `10` 代表專屬該等級會員可見,輸入 `全部` 則所有會員均可見。<br>✅ **左右滑動**:可以瀏覽與編輯所有品項。<br>⚠️ **自動流水號**:每次點擊儲存或刪除後,系統會依照目前的順序自動將流水號重新編排 (1 至 N)。")
                        
                        with gr.Row():
                            menu_cat_filter = gr.Dropdown(choices=get_menu_cat_choices(), value="全部分類", label="🔍 篩選分類", interactive=True)
                            menu_lvl_filter = gr.Dropdown(choices=get_menu_lvl_choices(), value="全部等級", label="🏅 篩選等級", interactive=True)
                            menu_item_filter = gr.Dropdown(choices=get_menu_item_choices(), value="所有品項", label="🍔 篩選品項", interactive=True)

                        with gr.Row(elem_classes="horizontal-menu-admin"):
                            @gr.render(inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter, menu_trigger])
                            def render_admin_menu(cat_f, lvl_f, item_f, trigger):
                                filtered_menu = MENU
                                if cat_f != "全部分類": filtered_menu = [m for m in filtered_menu if m.get("category", "未分類") == cat_f]
                                if lvl_f != "全部等級": filtered_menu = [m for m in filtered_menu if str(m.get("level", "全部")) == lvl_f]
                                if item_f != "所有品項": filtered_menu = [m for m in filtered_menu if m.get("name", "") == item_f]

                                sorted_menu = sorted(filtered_menu, key=lambda x: x.get("seq", 999))
                                existing_cats = [c for c in get_menu_cat_choices() if c != "全部分類"]
                                
                                for m in sorted_menu:
                                    old_seq = m.get("seq", 999)
                                    old_n = m.get("name", "")
                                    
                                    with gr.Column(elem_classes="menu-card-admin"):
                                        with gr.Row():
                                            e_enable = gr.Checkbox(label="上架啟用", value=m.get("enable", True), min_width=50, interactive=True)
                                            e_seq = gr.Number(label="排序(流水號)", value=old_seq, precision=0, min_width=80, interactive=True)
                                        e_name = gr.Textbox(label="品項名稱", value=old_n, interactive=True)
                                        e_cat = gr.Dropdown(choices=existing_cats, label="分類", value=m.get("category", "未分類"), allow_custom_value=True, interactive=True)
                                        with gr.Row():
                                            e_price = gr.Number(label="價格(NT$)", value=m.get("price", 0), min_width=80, interactive=True)
                                            e_cost = gr.Number(label="成本(NT$)", value=m.get("cost", 0), min_width=80, interactive=True)
                                        e_spec = gr.Textbox(label="規格", value=m.get("spec", ""), placeholder="例如: 中杯、大份", interactive=True)
                                        with gr.Row():
                                            e_lvl = gr.Textbox(label="適用等級", value=m.get("level", "全部"), min_width=80, interactive=True)
                                            e_note = gr.Textbox(label="備註", value=m.get("note", ""), min_width=80, interactive=True)
                                            
                                        with gr.Row():
                                            save_btn = gr.Button("💾 儲存", variant="primary")
                                            del_btn = gr.Button("🗑️ 刪除", variant="stop")
                                            
                                        def make_save_fn(o_seq):
                                            def save_item(seq_val, en_val, n_val, c_val, p_val, co_val, s_val, l_val, note_val, cur_cat, cur_lvl, cur_item):
                                                global MENU
                                                n_val = str(n_val).strip() if n_val else ""
                                                if not n_val: return "❌ 品項名稱不可為空!", gr.skip(), gr.skip(), gr.skip(), gr.skip()
                                                
                                                with db_lock:
                                                    for item in MENU:
                                                        if item.get("seq") == o_seq:
                                                            item.update({"name": n_val, "spec": str(s_val).strip() if s_val else "", "seq": int(seq_val) if seq_val is not None else 999, "enable": bool(en_val), "level": str(l_val).strip() if l_val else "全部", "category": str(c_val).strip() if c_val else "未分類", "price": int(float(p_val)) if p_val is not None else 0, "cost": int(float(co_val)) if co_val is not None else 0, "note": str(note_val).strip() if note_val else ""})
                                                            break
                                                    MENU.sort(key=lambda x: x.get("seq", 999))
                                                    for i, item in enumerate(MENU): item["seq"] = i + 1
                                                
                                                save_menu_to_db()
                                                c_choices, l_choices, i_choices = get_menu_cat_choices(), get_menu_lvl_choices(), get_menu_item_choices()
                                                cv, lv, iv = cur_cat if cur_cat in c_choices else "全部分類", cur_lvl if cur_lvl in l_choices else "全部等級", cur_item if cur_item in i_choices else "所有品項"
                                                return f"✅ {n_val} 已儲存,流水號已自動重排!", datetime.now(TAIPEI_TZ).timestamp(), gr.update(choices=c_choices, value=cv), gr.update(choices=l_choices, value=lv), gr.update(choices=i_choices, value=iv)
                                            return save_item
                                            
                                        def make_del_fn(o_seq, o_name):
                                            def delete_item(cur_cat, cur_lvl, cur_item):
                                                if cur_cat == "__CANCEL__": return gr.skip(), gr.skip(), gr.skip(), gr.skip(), gr.skip()
                                                global MENU
                                                with db_lock:
                                                    MENU[:] = [item for item in MENU if item.get("seq") != o_seq]
                                                    MENU.sort(key=lambda x: x.get("seq", 999))
                                                    for i, item in enumerate(MENU): item["seq"] = i + 1
                                                
                                                save_menu_to_db()
                                                c_choices, l_choices, i_choices = get_menu_cat_choices(), get_menu_lvl_choices(), get_menu_item_choices()
                                                cv, lv, iv = cur_cat if cur_cat in c_choices else "全部分類", cur_lvl if cur_lvl in l_choices else "全部等級", cur_item if cur_item in i_choices else "所有品項"
                                                return f"🗑️ {o_name} 已刪除,流水號已重排!", datetime.now(TAIPEI_TZ).timestamp(), gr.update(choices=c_choices, value=cv), gr.update(choices=l_choices, value=lv), gr.update(choices=i_choices, value=iv)
                                            return delete_item
                                            
                                        save_btn.click(fn=make_save_fn(old_seq), inputs=[e_seq, e_enable, e_name, e_cat, e_price, e_cost, e_spec, e_lvl, e_note, menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[global_sys_msg, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter])
                                        del_btn.click(fn=make_del_fn(old_seq, old_n), inputs=[menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[global_sys_msg, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter], js="(c, l, i) => confirm('⚠️ 警告:確定要刪除這個品項嗎?動作無法復原!') ? [c, l, i] : ['__CANCEL__', l, i]")

                                with gr.Column(elem_classes="menu-card-admin new-card-admin"):
                                    gr.Markdown("<h3 style='text-align:center; color:#3b82f6;'>✨ 新增菜單品項</h3>")
                                    with gr.Row():
                                        new_enable = gr.Checkbox(label="上架啟用", value=True, min_width=50, interactive=True)
                                        new_seq = gr.Number(label="排序(預設放最後)", value=len(MENU)+1, precision=0, min_width=80, interactive=True)
                                    new_name = gr.Textbox(label="品項名稱", placeholder="輸入新名稱...", interactive=True)
                                    new_cat = gr.Dropdown(choices=existing_cats, label="分類", value=cat_f if cat_f != "全部分類" else "未分類", allow_custom_value=True, interactive=True)
                                    with gr.Row():
                                        new_price = gr.Number(label="價格(NT$)", value=100, min_width=80, interactive=True)
                                        new_cost = gr.Number(label="成本(NT$)", value=50, min_width=80, interactive=True)
                                    new_spec = gr.Textbox(label="規格", placeholder="例如: 大杯、一份", interactive=True)
                                    with gr.Row():
                                        new_lvl = gr.Textbox(label="適用等級", value=lvl_f if lvl_f != "全部等級" else "全部", min_width=80, interactive=True)
                                        new_note = gr.Textbox(label="備註", placeholder="內部備註", min_width=80, interactive=True)
                                    add_btn = gr.Button("➕ 確認新增", variant="primary")
                                    
                                    def add_item(seq_val, en_val, n_val, c_val, p_val, co_val, s_val, l_val, note_val, cur_cat, cur_lvl, cur_item):
                                        global MENU
                                        n_val = str(n_val).strip() if n_val else ""
                                        if not n_val: return "❌ 品項名稱不可為空!", gr.skip(), gr.skip(), gr.skip(), gr.skip()
                                        
                                        with db_lock:
                                            MENU.append({"name": n_val, "spec": str(s_val).strip() if s_val else "", "seq": int(seq_val) if seq_val is not None else 999, "enable": bool(en_val), "level": str(l_val).strip() if l_val else "全部", "category": str(c_val).strip() if c_val else "未分類", "price": int(float(p_val)) if p_val is not None else 0, "cost": int(float(co_val)) if co_val is not None else 0, "note": str(note_val).strip() if note_val else ""})
                                            MENU.sort(key=lambda x: x.get("seq", 999))
                                            for i, item in enumerate(MENU): item["seq"] = i + 1
                                        
                                        save_menu_to_db()
                                        c_choices, l_choices, i_choices = get_menu_cat_choices(), get_menu_lvl_choices(), get_menu_item_choices()
                                        cv, lv, iv = cur_cat if cur_cat in c_choices else "全部分類", cur_lvl if cur_lvl in l_choices else "全部等級", cur_item if cur_item in i_choices else "所有品項"
                                        return f"✅ {n_val} 已新增,流水號已自動重排!", datetime.now(TAIPEI_TZ).timestamp(), gr.update(choices=c_choices, value=cv), gr.update(choices=l_choices, value=lv), gr.update(choices=i_choices, value=iv)
                                        
                                    add_btn.click(fn=add_item, inputs=[new_seq, new_enable, new_name, new_cat, new_price, new_cost, new_spec, new_lvl, new_note, menu_cat_filter, menu_lvl_filter, menu_item_filter], outputs=[global_sys_msg, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter])
                        
                    with gr.TabItem("👥 會員資料管理"):
                        gr.Markdown("⚠️ **點擊下方表格內任何一筆資料,即可在最底下的「編輯表單」中修改或刪除。**")
                        
                        members_table = gr.Dataframe(
                            value=get_members_df(),
                            headers=["會員登入帳號", "密碼", "會員等級", "顧客姓名", "送貨地點"],
                            datatype=["str", "str", "str", "str", "str"],
                            interactive=False, column_widths=["20%", "20%", "10%", "25%", "25%"]
                        )
                        
                        gr.Markdown("---")
                        gr.Markdown("### 👤 會員編輯區")
                        with gr.Group():
                            with gr.Row():
                                mem_acc = gr.Textbox(label="會員登入帳號", placeholder="必填 (做為帳號)")
                                mem_pwd = gr.Textbox(label="密碼", placeholder="輸入新密碼以覆蓋,留白或維持 *** 則保留原密碼")
                                mem_lvl = gr.Textbox(label="會員等級", value="1")
                            with gr.Row():
                                mem_name = gr.Textbox(label="顧客姓名")
                                mem_loc = gr.Textbox(label="送貨地點")
                            with gr.Row():
                                save_members_btn = gr.Button("💾 儲存 / 新增會員", variant="primary")
                                del_members_btn = gr.Button("🗑️ 刪除此會員", variant="stop")
                                clear_mem_form_btn = gr.Button("🔄 清空表單", variant="secondary")
                                
                        members_status = gr.Markdown()

                    with gr.TabItem("🔑 安全性設定"):
                        gr.Markdown("### 🔑 修改管理員密碼")
                        with gr.Row():
                            with gr.Column(scale=1): old_pwd_input = gr.Textbox(label="目前密碼", type="password", placeholder="請輸入舊密碼")
                            with gr.Column(scale=1): new_pwd_input = gr.Textbox(label="新密碼", type="password", placeholder="請輸入新密碼")
                            with gr.Column(scale=1, min_width=150): update_pwd_btn = gr.Button("💾 確認更新密碼", variant="primary")
                        pwd_update_status = gr.Markdown()
                        
                    with gr.TabItem("🎨 外觀設定"):
                        gr.Markdown("### 🖼️ 系統背景與透明度設定\n您可以自訂網頁的背景圖片,以及白色遮罩的不透明度。<br>⚠️ **【優化升級】**:現在上傳圖片會被實體儲存於伺服器中,不再使用肥大的文字編碼塞爆設定檔,大幅提升系統載入速度!")
                        
                        init_source = APP_CONFIG.get("bg_source", "default")
                        init_source_str = {"default": "預設圖片", "url": "自訂網址", "upload": "上傳圖片"}.get(init_source, "預設圖片")
                        
                        with gr.Row():
                            with gr.Column():
                                bg_source_radio = gr.Radio(choices=["預設圖片", "自訂網址", "上傳圖片"], label="背景圖來源", value=init_source_str, interactive=True)
                                bg_url_input = gr.Textbox(label="圖片網址", value=APP_CONFIG.get("bg_url", ""), visible=(init_source_str == "自訂網址"), interactive=True)
                                bg_upload_input = gr.Image(type="filepath", label="上傳背景圖 (自動壓縮優化儲存)", visible=(init_source_str == "上傳圖片"), interactive=True)
                            with gr.Column():
                                bg_opacity_slider = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="白色遮罩不透明度 (數值越高背景越白越不明顯)", value=APP_CONFIG.get("bg_opacity", 0.85), interactive=True)
                                save_bg_btn = gr.Button("💾 儲存外觀設定並套用", variant="primary")
                                bg_status_msg = gr.Markdown()

                # --- Admin 事件綁定 ---
                for f_cmp in [customer_filter, time_filter, item_filter, delivery_filter]:
                    f_cmp.change(fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))), inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display])
                
                refresh_btn.click(fn=refresh_data, inputs=[customer_filter, time_filter, item_filter, delivery_filter], outputs=[orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter])
                orders_table.select(fn=autofill_delete_target, inputs=[orders_table], outputs=[delete_target])
                mark_done_btn.click(fn=lambda o, c, t, i, d: update_order_status(o, "已完成", c, t, i, d), inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display])
                mark_cancel_btn.click(fn=lambda o, c, t, i, d: update_order_status(o, "已取消", c, t, i, d), inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display])
                delete_single_btn.click(fn=delete_single_order, inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter], outputs=[admin_status_msg, orders_table, revenue_display, delete_target], js="(t,c,f,i,d) => confirm('⚠️ 確定永久刪除訂單 [' + t + '] 嗎?') ? [t,c,f,i,d] : ['__CANCEL__',c,f,i,d]")
                clear_btn.click(fn=clear_orders, inputs=[customer_filter], outputs=[admin_status_msg, orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter], js="(f) => confirm('🚨 極度危險:確定清空所有訂單?') ? [f] : ['__CANCEL__']")

                members_table.select(fn=autofill_member_form, inputs=[members_table], outputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc])
                clear_mem_form_btn.click(fn=lambda: ("","", "1", "", ""), inputs=[], outputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc])
                save_members_btn.click(fn=save_single_member, inputs=[mem_acc, mem_pwd, mem_lvl, mem_name, mem_loc], outputs=[members_status, members_table])
                del_members_btn.click(fn=delete_single_member, inputs=[mem_acc], outputs=[members_status, members_table], js="(acc) => { if(!acc) return acc; return confirm('⚠️ 確定刪除會員 ' + acc + ' 嗎?') ? acc : ''; }")

                bg_source_radio.change(fn=lambda s: (gr.update(visible=(s=="自訂網址")), gr.update(visible=(s=="上傳圖片"))), inputs=[bg_source_radio], outputs=[bg_url_input, bg_upload_input])
                
                def update_background(source, url, img_path, opacity):
                    global APP_CONFIG
                    src_map = {"預設圖片": "default", "自訂網址": "url", "上傳圖片": "upload"}
                    with db_lock:
                        APP_CONFIG["bg_source"] = src_map.get(source, "default")
                        APP_CONFIG["bg_url"] = str(url).strip() if url else ""
                        APP_CONFIG["bg_opacity"] = float(opacity)
                        if APP_CONFIG["bg_source"] == "upload" and img_path:
                            try:
                                data_dir = os.path.join(BASE_DIR, "data")
                                os.makedirs(data_dir, exist_ok=True)
                                bg_dest = os.path.join(data_dir, "custom_bg.jpg")
                                shutil.copy(img_path, bg_dest)
                                APP_CONFIG["bg_file"] = "data/custom_bg.jpg"
                                if "_cached_b64" in APP_CONFIG: APP_CONFIG.pop("_cached_b64", None)
                            except Exception as e:
                                return gr.update(), f"❌ 圖片儲存失敗: {str(e)}"
                    save_config_to_db()
                    return generate_bg_css(APP_CONFIG), f"✅ 外觀設定已更新並完成最佳化儲存!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"

                save_bg_btn.click(fn=update_background, inputs=[bg_source_radio, bg_url_input, bg_upload_input, bg_opacity_slider], outputs=[dynamic_bg_html, bg_status_msg])
                github_btn.click(fn=backup_and_push_to_github, inputs=[], outputs=[github_log_output])
                restore_btn.click(fn=restore_from_backup, inputs=[], outputs=[global_sys_msg, members_table, menu_trigger, menu_cat_filter, menu_lvl_filter, menu_item_filter, dynamic_bg_html, bg_source_radio, bg_url_input, bg_opacity_slider])
                update_pwd_btn.click(fn=change_password, inputs=[old_pwd_input, new_pwd_input], outputs=[pwd_update_status])

    login_btn.click(fn=do_login, inputs=[login_acc, login_pwd], outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg])
    login_pwd.submit(fn=do_login, inputs=[login_acc, login_pwd], outputs=[login_container, main_container, admin_tab, login_msg, current_user_state, user_greeting, global_sys_msg])
    logout_btn.click(fn=logout, inputs=[], outputs=[login_container, main_container, admin_tab, login_acc, login_pwd, login_msg, current_user_state, user_greeting, global_sys_msg])

    def load_initial_state():
        init_source = APP_CONFIG.get("bg_source", "default")
        init_source_str = {"default": "預設圖片", "url": "自訂網址", "upload": "上傳圖片"}.get(init_source, "預設圖片")
        return (generate_bg_css(APP_CONFIG), gr.update(value=init_source_str), gr.update(value=APP_CONFIG.get("bg_url", "")), gr.update(value=APP_CONFIG.get("bg_opacity", 0.85)))

    demo_ui.load(fn=load_initial_state, inputs=None, outputs=[dynamic_bg_html, bg_source_radio, bg_url_input, bg_opacity_slider], js=kill_badge_js)

app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860, proxy_headers=True, forwarded_allow_ips="*")