File size: 31,278 Bytes
a6161e8
 
 
 
 
 
 
 
 
 
e2212dd
 
a6161e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2212dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6161e8
 
 
e2212dd
a6161e8
 
 
 
e2212dd
a6161e8
e2212dd
 
 
 
 
a6161e8
 
 
 
 
 
e2212dd
a6161e8
 
e2212dd
a6161e8
 
 
 
 
 
 
e2212dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6161e8
e2212dd
 
 
 
 
 
 
 
a6161e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Request, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import base64
import os
import shutil
import cv2
import numpy as np
from unidecode import unidecode
from FaceNet import *
# from faceDetect import faceDetector
from faceDetect import face_cascade
from connectDatabase import get_connection
import csv
from typing import List
from fastapi import Body, Query
from config import *
from fastapi import HTTPException
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
from email.message import EmailMessage
import io
import smtplib
from fastapi.responses import JSONResponse
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"

EMAILSENDER = os.getenv("emailsender")
PASSWORDEMAILSENDER = os.getenv("passwordemailsender")

app = FastAPI()

# CORS cho tất cả các domain
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allow all origins, or specify trusted ones
    allow_credentials=True,
    allow_methods=["*"],  # Allow all methods
    allow_headers=["*"],  # Allow all headers
)

# ==== MODEL ĐẦU VÀO ====
class ImageData(BaseModel):
    image_base64: str

class SignupData(BaseModel):
    name_: str
    phone: str
    email: str
    birthday: str
    province: str
    school: str
    major: str

class SavePersonData(BaseModel):
    number_id: int
    name_: str
    birthday: str
    phone: str
    major: str
    
class Major(BaseModel):
    ID: int
    Major: str
    Script: str
    VideoLink: str

class GETNEWID(BaseModel):
    number_id: int
    
class PersonID(BaseModel):
    person_id: int

class PeopleDataResponse(BaseModel):
    Number: int
    Name: str
    YearOfBirth: str
    NoPhone: str
    Major: str
    No_checkIn_ed: int


class UserLogin(BaseModel):
    username: str
    password: str

class UserRegister(BaseModel):
    username: str
    password: str
    role: int

class GmailAccountData(BaseModel):
    account: str
    last_time: Optional[datetime] = None
    number: Optional[int] = 0

# # ==== API: PHÁT HIỆN VÀ XÁC NHẬN KHUÔN MẶT ====
# @app.post("/Capture", tags=["CheckIn API"])
# async def Capture(data: ImageData):
#     try:
#         # Giải mã base64 và lưu ảnh
#         imgData = base64.b64decode(data.image_base64)
#         with open(filename_path, 'wb') as f:
#             f.write(imgData)

#         # Đọc ảnh và phát hiện khuôn mặt
#         img = cv2.imread(filename_path)
#         results = faceDetector(img, classes=0, conf=0.3, verbose=False, device="cpu")
#         face_location = len(results[0].boxes)

#         if face_location == 0:
#             # Không có khuôn mặt nào trong ảnh
#             return {"lock": 0, "person_id": None}
#         elif face_location > 1:
#             # Có quá nhiều khuôn mặt trong ảnh
#             return {"lock": 1, "person_id": None}

#         with get_connection() as conn:
#             with conn.cursor() as cursor:
#                 # Kiểm tra xem có ai trong danh sách chưa
#                 cursor.execute("SELECT COUNT(*) FROM PeopleData")
#                 result = cursor.fetchone()
#                 count = result[0] if result else 0

#                 if count == 0:
#                     # Nếu danh sách trống, người trong ảnh là người đầu tiên
#                     return {"lock": 2, "person_id": 1}

#                 else:
#                     # Cắt khuôn mặt và lưu vào file
#                     for result in results[0]:
#                         boxes = result.boxes.cpu().numpy()
#                         for box in boxes:
#                             if box.cls[0] == 0:  # Kiểm tra đối tượng là người
#                                 x_min, y_min, x_max, y_max = map(int, box.xyxy[0])
#                                 faceArea = img[y_min:y_max, x_min:x_max]
#                                 cv2.imwrite(face_img_path, faceArea)

#                     # So sánh khuôn mặt mới với các khuôn mặt trong cơ sở dữ liệu
#                     cursor.execute("""
#                         SELECT PeopleImage.Number, PeopleImage.VectoFaceNet, PeopleData.Name, PeopleData.No_checkIn_ed
#                         FROM PeopleImage
#                         JOIN PeopleData ON PeopleImage.Number = PeopleData.Number
#                     """)
#                     rows = cursor.fetchall()

#                     list_True_threshold = []
#                     list_identity = []

#                     encoding = img_to_encoding(face_img_path, model_FV)
#                     best_idx = -99
#                     for row in rows:
#                         person_id, vector_str, name, checkin_count = row
#                         if vector_str:
#                             vector_clean = vector_str.strip('[] \n')  # Loại bỏ dấu [] và xuống dòng
#                             vector_list = list(map(float, vector_clean.split()))  # Tách các giá trị và chuyển sang float
#                             vector_np = np.array(vector_list, dtype=np.float32)  # Chuyển thành numpy array
#                             distance = verifyFace(encoding, vector_np, model_FV)  # Tính khoảng cách giữa khuôn mặt
#                             if distance[0] <= 0.4:
#                                 list_True_threshold.append(distance[0])

#                     if list_True_threshold:
#                         best_idx = np.argmin(np.array(list_True_threshold))
#                         # Nếu khuôn mặt đã có trong danh sách
#                         return {
#                             "lock": 3,
#                             "person_id": int(best_idx + 1)
#                         }

#                     else:
#                         # Nếu khuôn mặt chưa có trong danh sách, tạo ID mới
#                         cursor.execute("SELECT COUNT(*) FROM PeopleData")
#                         num_rows_id = cursor.fetchone()[0]
#                         new_id = num_rows_id + 1
#                         return {
#                             "lock": 4,
#                             "person_id": new_id
#                         }

#     except Exception as e:
#         return {"lock": None, "error": str(e)}

# ==== API: PHÁT HIỆN VÀ XÁC NHẬN KHUÔN MẶT ==== 
@app.post("/Capture", tags=["CheckIn API"])
async def Capture(data: ImageData):
    try:
        # Giải mã ảnh base64
        imgData = base64.b64decode(data.image_base64)
        with open(filename_path, 'wb') as f:
            f.write(imgData)

        # Đọc ảnh và chuyển sang grayscale
        img = cv2.imread(filename_path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Phát hiện khuôn mặt bằng Haarcascade
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(60, 60))
        face_location = len(faces)

        if face_location == 0:
            return {"lock": 0, "person_id": None}
        elif face_location > 1:
            return {"lock": 1, "person_id": None}

        # Kết nối DB
        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Kiểm tra số người trong danh sách
                cursor.execute("SELECT COUNT(*) FROM PeopleData")
                result = cursor.fetchone()
                count = result[0] if result else 0

                if count == 0:
                    return {"lock": 2, "person_id": 1}

                # Cắt khuôn mặt từ ảnh
                for (x, y, w, h) in faces:
                    faceArea = img[y:y+h, x:x+w]
                    cv2.imwrite(face_img_path, faceArea)

                # So sánh khuôn mặt với DB
                cursor.execute("""
                    SELECT PeopleImage.Number, PeopleImage.VectoFaceNet, PeopleData.Name, PeopleData.No_checkIn_ed
                    FROM PeopleImage
                    JOIN PeopleData ON PeopleImage.Number = PeopleData.Number
                """)
                rows = cursor.fetchall()

                list_True_threshold = []
                encoding = img_to_encoding(face_img_path, model_FV)

                for row in rows:
                    person_id, vector_str, name, checkin_count = row
                    if vector_str:
                        vector_clean = vector_str.strip('[] \n')
                        vector_list = list(map(float, vector_clean.split()))
                        vector_np = np.array(vector_list, dtype=np.float32)
                        distance = verifyFace(encoding, vector_np, model_FV)
                        if distance[0] <= 0.4:
                            list_True_threshold.append((distance[0], person_id))

                if list_True_threshold:
                    # Lấy người có khoảng cách nhỏ nhất
                    best_match = min(list_True_threshold, key=lambda x: x[0])
                    return {
                        "lock": 3,
                        "person_id": int(best_match[1])
                    }
                else:
                    # Nếu không có khớp -> gán ID mới
                    cursor.execute("SELECT COUNT(*) FROM PeopleData")
                    num_rows_id = cursor.fetchone()[0]
                    new_id = num_rows_id + 1
                    return {
                        "lock": 4,
                        "person_id": new_id
                    }

    except Exception as e:
        return {"lock": None, "error": str(e)}


# ==== API: cập nhật số lần check-in add ====
@app.post("/AddCheckin", tags=["CheckIn API"])
async def add_checkin(data: PersonID):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Tăng số lần check-in
                cursor.execute(
                    "UPDATE PeopleData SET No_checkIn_ed = No_checkIn_ed + 1 WHERE Number = %s", 
                    (data.person_id,)
                )
                conn.commit()

                # Lấy số lần check-in mới nhất
                cursor.execute(
                    "SELECT No_checkIn_ed FROM PeopleData WHERE Number = %s", 
                    (data.person_id,)
                )
                result = cursor.fetchone()
                checkin_count = result[0] if result else None

                # Lấy tổng số người
                cursor.execute("SELECT COUNT(*) FROM PeopleData")
                num_rows_id = cursor.fetchone()[0]

                return {
                    "message": "Check-in updated successfully",
                    "person_id": data.person_id,
                    "checkin_info_number": checkin_count,
                    "number_id": num_rows_id
                }

    except Exception as e:
        return {"message": "Error", "error": str(e)}

    
# ==== API: cập nhật số lần check-in sub ====
@app.post("/SubCheckin", tags=["CheckIn API"])
async def Sub_checkin(data: PersonID):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Giảm số lần check-in
                cursor.execute(
                    "UPDATE PeopleData SET No_checkIn_ed = No_checkIn_ed - 1 WHERE Number = %s", 
                    (data.person_id,)
                )
                conn.commit()

                # Lấy số lần check-in mới nhất
                cursor.execute(
                    "SELECT No_checkIn_ed FROM PeopleData WHERE Number = %s", 
                    (data.person_id,)
                )
                result = cursor.fetchone()
                checkin_count = result[0] if result else None

                # Lấy tổng số người
                cursor.execute("SELECT COUNT(*) FROM PeopleData")
                num_rows_id = cursor.fetchone()[0]

                return {
                    "message": "Check-in updated successfully",
                    "person_id": data.person_id,
                    "checkin_info_number": checkin_count,
                    "number_id": num_rows_id
                }

    except Exception as e:
        return {"message": "Error", "error": str(e)}

# ==== API: GetNewId ====
@app.get("/GetNewId", response_model=GETNEWID, tags=["CheckIn API"])
def GetNewId():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT COUNT(*) FROM PeopleData")
                num_rows_id = cursor.fetchone()[0]
                new_id = num_rows_id + 1
                return GETNEWID(number_id=new_id)
    except Exception as e:
        return {"error": str(e)}


# ==== API: LƯU NGƯỜI MỚI ====
@app.post("/SaveNewPeople", tags=["CheckIn API"])
async def SaveNewPeople(data: SavePersonData):
    try:
        number_id_save = data.number_id
        name_save = data.name_
        birthday_save = data.birthday
        phone_save = data.phone
        major_save = data.major

        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Insert dữ liệu người mới vào PeopleData
                cursor.execute("""
                    INSERT INTO PeopleData (Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed)
                    VALUES (%s, %s, %s, %s, %s, %s)
                """, (number_id_save, name_save, birthday_save, phone_save, major_save, 1))
                conn.commit()

        # Detect & extract vector (xử lý ngoài database)
        img = cv2.imread(filename_path)
        results = faceDetector.predict(img, classes=0, conf=0.3, verbose=False, device="cpu")

        # Cắt và lưu khuôn mặt
        for result in results[0]:
            boxes = result.boxes.cpu().numpy()
            for box in boxes:
                if box.cls[0] == 0:
                    x_min, y_min, x_max, y_max = map(int, box.xyxy[0])
                    faceArea = img[y_min:y_max, x_min:x_max]
                    cv2.imwrite(face_img_path, faceArea)

        vecto_extract = img_to_encoding(face_img_path, model_FV)
        print("vecto_extract:", vecto_extract)

        with open(filename_path, "rb") as f:
            full_img_base64 = base64.b64encode(f.read()).decode("utf-8")
        with open(face_img_path, "rb") as f:
            face_img_base64 = base64.b64encode(f.read()).decode("utf-8")

        vecto_string = ",".join(map(str, vecto_extract))
        print("vecto_string:", vecto_string)

        # Insert hình ảnh và vector vào PeopleImage
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("""
                    INSERT INTO PeopleImage (Number, FullImageBase64, FaceImageBase64, VectoFaceNet)
                    VALUES (%s, %s, %s, %s)
                """, (number_id_save, full_img_base64, face_img_base64, vecto_string))
                conn.commit()

        return {"content": "Saved"}

    except Exception as e:
        return {"error": str(e)}


# ==== API: LẤY TẤT CẢ DỮ LIỆU PeopleData ====
@app.get("/GetAllPeopleData", response_model=List[PeopleDataResponse], tags=["CheckIn API"])
def get_all_people_data():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed FROM PeopleData")
                rows = cursor.fetchall()

                return [
                    PeopleDataResponse(
                        Number=row[0],
                        Name=row[1],
                        YearOfBirth=row[2],
                        NoPhone=row[3],
                        Major=row[4],
                        No_checkIn_ed=row[5]
                    )
                    for row in rows
                ]
    except Exception as e:
        return {"error": str(e)}


# ==== API: XÓA MỘT NGƯỜI ====
@app.delete("/DeletePerson", tags=["CheckIn API"])
async def delete_person(data: PersonID):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("DELETE FROM PeopleImage WHERE Number = %s", (data.person_id,))
                cursor.execute("DELETE FROM PeopleData WHERE Number = %s", (data.person_id,))
                conn.commit()

        return {
            "message": f"Person with ID {data.person_id} deleted successfully."
        }
    except Exception as e:
        return {
            "message": "Error during deletion",
            "error": str(e)
        }


# ==== API: LẤY THÔNG TIN ĐẦY ĐỦ CỦA 1 NGƯỜI ====
@app.get("/GetFullPersonInfo", tags=["CheckIn API"])
async def get_full_person_info(person_id: int = Query(..., description="ID của người cần lấy thông tin")):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Lấy thông tin cơ bản
                cursor.execute("""
                    SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed 
                    FROM PeopleData 
                    WHERE Number = %s
                """, (person_id,))
                person_data = cursor.fetchone()

                if not person_data:
                    return {
                        "message": "Không tìm thấy người dùng với person_id này.",
                        "person_id": person_id
                    }

                # Lấy ảnh và vector khuôn mặt
                cursor.execute("""
                    SELECT FullImageBase64, FaceImageBase64, VectoFaceNet 
                    FROM PeopleImage 
                    WHERE Number = %s
                """, (person_id,))
                image_data = cursor.fetchone()

                # Lấy mô tả chuyên ngành
                cursor.execute("""
                    SELECT Script, VideoLink 
                    FROM MajorData 
                    WHERE Major = %s
                """, (person_data[4],))
                major_data = cursor.fetchone()

                return {
                    "message": "Lấy thông tin đầy đủ thành công.",
                    "person": {
                        "Number": person_data[0],
                        "Name": person_data[1],
                        "YearOfBirth": person_data[2],
                        "NoPhone": person_data[3],
                        "Major": person_data[4],
                        "No_checkIn_ed": person_data[5],
                        "Image": {
                            "FullImageBase64": image_data[0] if image_data else None,
                            "FaceImageBase64": image_data[1] if image_data else None,
                            "VectoFaceNet": image_data[2] if image_data else None
                        },
                        "MajorInfo": {
                            "Script": major_data[0] if major_data else None,
                            "VideoLink": major_data[1] if major_data else None
                        }
                    }
                }
    except Exception as e:
        return {
            "message": "Lỗi khi truy vấn dữ liệu",
            "error": str(e)
        }

# ==== API: LẤY THÔNG TIN PHẦN QUÀ ====
@app.get("/GetRewards", tags=["Rewards"])
async def get_rewards():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT Name FROM Rewards")
                rows = cursor.fetchall()
                rewards = [row[0] for row in rows]

        return {"rewards": rewards}
    except Exception as e:
        return {"message": "Lỗi khi truy vấn phần quà", "error": str(e)}

 
# # ==== API: Lấy thông tin của ngành nghề quan tâm ====   
@app.get("/GetMajors", tags=["Majors"])
async def get_majors():
    try:
        with get_connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute("SELECT Name FROM Majors;")
                rows = cursor.fetchall()
                majors = [{"label": row[0], "value": row[0]} for row in rows]
                return {"data_major": majors}
    except Exception as e:
        return {"message": "Lỗi khi truy vấn ngành học", "error": str(e)}

# ==== API: LẤY DATA MAJOR TRÊN BẢNG TIN ====
@app.get("/GetMajorData", response_model=List[Major], tags=["Majors"])
def get_major_data():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT ID, Major, Script, VideoLink FROM MajorData")
                rows = cursor.fetchall()
                
                return [
                    Major(
                        ID=row[0],
                        Major=row[1],
                        Script=row[2],
                        VideoLink=row[3]
                    ) for row in rows
                ]
    except Exception as e:
        return [{"ID": -1, "Major": "Error", "Script": str(e), "VideoLink": ""}]

# ==== API: ĐĂNG KÝ NHẬN TƯ VẤN ====
@app.post("/SignupAdvise", tags=["SignUp Advise"])
async def signup_advise(data: SignupData):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("""
                    INSERT INTO signup_advise (Name, Nophone, email, birthYear, province, school, major)
                    VALUES (%s, %s, %s, %s, %s, %s, %s)
                """, (data.name_, data.phone, data.email, data.birthday, data.province, data.school, data.major))
                
                conn.commit()
        return {"content": "Saved"}
    except Exception as e:
        return {"content": f"Error: {str(e)}"}
    

# ==== API: Lấy toàn bộ bảng signup_advise ====
@app.get("/GetAllAdvise", response_model=List[SignupData], tags=["SignUp Advise"])
async def get_all_advise():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT * FROM signup_advise")
                rows = cursor.fetchall()

                advise_list = []
                for row in rows:
                    advise_data = SignupData(
                        name_=row[1],  # chú ý: row[0] là id, còn name nằm ở row[1]
                        phone=row[2],
                        email=row[3],
                        birthday=row[4],
                        province=row[5],
                        school=row[6],
                        major=row[7]
                    )
                    advise_list.append(advise_data)

                return advise_list
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
    
# ====  API: Xóa một bản ghi theo ID ====
@app.delete("/DeleteAdvise/{advise_id}", tags=["SignUp Advise"])
async def delete_advise(advise_id: int):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("DELETE FROM signup_advise WHERE id = %s", (advise_id,))
                conn.commit()

                if cursor.rowcount == 0:
                    return {"content": f"No record found with ID {advise_id}"}
                return {"content": f"Record with ID {advise_id} deleted successfully"}
    except Exception as e:
        return {"content": f"Error: {str(e)}"}
    
# ==== API: Lấy thông tin một bản ghi theo ID ====
@app.get("/GetAdvise/{advise_id}", response_model=SignupData, tags=["SignUp Advise"])
async def get_advise_by_id(advise_id: int):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT * FROM signup_advise WHERE id = %s", (advise_id,))
                row = cursor.fetchone()

                if row:
                    advise_data = SignupData(
                        name_=row[1],
                        phone=row[2],
                        email=row[3],
                        birthday=row[4],
                        province=row[5],
                        school=row[6],
                        major=row[7]
                    )
                    return advise_data
                else:
                    return {"content": f"No record found with ID {advise_id}"}
    except Exception as e:
        return {"content": f"Error: {str(e)}"}


# ==== API: Đăng nhập với root (chỉ role=0) ====
@app.post("/manager/login-root", tags=["Manager"])
async def login_root(data: UserLogin):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT role FROM UserAccount WHERE username=%s AND password=%s", (data.username, data.password))
                row = cursor.fetchone()
                if row and row[0] == 0:
                    return {"message": "Login successful (root)"}
                else:
                    return {"message": "Unauthorized or wrong credentials"}
    except Exception as e:
        return {"error": str(e)}

# ==== API: Đăng nhập (mọi role) ====
@app.post("/manager/login", tags=["Manager"])
async def login(data: UserLogin):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT role FROM UserAccount WHERE username=%s AND password=%s", (data.username, data.password))
                row = cursor.fetchone()
                if row:
                    return {"message": "Login successful", "role": row[0]}
                else:
                    return {"message": "Invalid credentials"}
    except Exception as e:
        return {"error": str(e)}

# ==== API: Đăng ký ====
@app.post("/manager/register", tags=["Manager"])
async def register(data: UserRegister):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("INSERT INTO UserAccount (username, password, role) VALUES (%s, %s, %s)", 
                               (data.username, data.password, data.role))
                conn.commit()
                return {"message": "User registered successfully"}
    except Exception as e:
        return {"error": str(e)}

# ==== API:  Thêm Gmail vào bảng GmailAccount====
@app.post("/manager/gmail", tags=["Manager"])
async def add_gmail(data: GmailAccountData):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("INSERT INTO GmailAccount (account, last_time, number) VALUES (%s, %s, %s)",
                               (data.account, data.last_time, data.number))
                conn.commit()
                return {"message": "Gmail account added successfully"}
    except Exception as e:
        return {"error": str(e)}

# ==== API: Sửa Gmail theo id====
@app.put("/manager/gmail/{id}", tags=["Manager"])
async def update_gmail(id: int, data: GmailAccountData):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("""
                    UPDATE GmailAccount 
                    SET account=%s, last_time=%s, number=%s 
                    WHERE id=%s
                """, (data.account, data.last_time, data.number, id))
                conn.commit()
                return {"message": "Gmail account updated successfully"}
    except Exception as e:
        return {"error": str(e)}

# ==== API: Xóa Gmail theo id ====
@app.delete("/manager/gmail/{id}", tags=["Manager"])
async def delete_gmail(id: int):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("DELETE FROM GmailAccount WHERE id=%s", (id,))
                conn.commit()
                return {"message": f"Gmail account with id {id} deleted"}
    except Exception as e:
        return {"error": str(e)}

# ==== API: Lấy tất cả Gmail ====
@app.get("/manager/gmail", tags=["Manager"])
async def get_all_gmail():
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute("SELECT * FROM GmailAccount")
                rows = cursor.fetchall()
                return [{"id": r[0], "account": r[1], "last_time": r[2], "number": r[3]} for r in rows]
    except Exception as e:
        return {"error": str(e)}

# ==== API: Send report to Gmail ==== 
@app.post("/manager/send-report", tags=["Manager"])
async def send_report(to: str = Form(...)):
    try:
        with get_connection() as conn:
            with conn.cursor() as cursor:
                # Lấy dữ liệu từ bảng signup_advise
                cursor.execute("SELECT * FROM signup_advise")
                advise_rows = cursor.fetchall()
                advise_headers = [desc[0] for desc in cursor.description]

                # Lấy dữ liệu từ bảng PeopleData
                cursor.execute("SELECT Number, Name, YearOfBirth, NoPhone, Major, No_checkIn_ed FROM PeopleData")
                people_rows = cursor.fetchall()
                people_headers = [desc[0] for desc in cursor.description]

        def generate_csv(rows, headers):
            output = io.StringIO()
            writer = csv.writer(output)
            writer.writerow(headers)
            writer.writerows(rows)
            return output.getvalue()

        advise_csv = generate_csv(advise_rows, advise_headers)
        people_csv = generate_csv(people_rows, people_headers)

        # Tạo email đẹp bằng HTML
        msg = MIMEMultipart()
        msg['Subject'] = "📊 Báo cáo hệ thống"
        msg['From'] = EMAILSENDER
        msg['To'] = to

        html_content = """
        <html>
        <body>
            <h2>📋 Báo cáo hệ thống</h2>
            <p>Xin chào,</p>
            <p>Vui lòng xem báo cáo mới nhất từ hệ thống trong các tệp đính kèm bên dưới:</p>
            <ul>
                <li><strong>signupAdvise.csv</strong>: Danh sách tư vấn đăng ký.</li>
                <li><strong>checkin.csv</strong>: Dữ liệu điểm danh.</li>
            </ul>
            <p>Trân trọng,<br>Hệ thống FPT Check-in</p>
        </body>
        </html>
        """
        msg.attach(MIMEText(html_content, "html"))

        # Đính kèm từng file CSV
        part1 = MIMEApplication(advise_csv.encode("utf-8"), _subtype="csv")
        part1.add_header('Content-Disposition', 'attachment', filename="signupAdvise.csv")
        msg.attach(part1)

        part2 = MIMEApplication(people_csv.encode("utf-8"), _subtype="csv")
        part2.add_header('Content-Disposition', 'attachment', filename="checkin.csv")
        msg.attach(part2)

        # Gửi email
        with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
            smtp.login(EMAILSENDER, PASSWORDEMAILSENDER)
            smtp.send_message(msg)

        return {"message": f"Email đã được gửi thành công tới {to}"}

    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})