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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290

import pymssql
import random
import uuid
import requests
from fastapi import FastAPI, HTTPException, Header
from pydantic import BaseModel
from datetime import datetime, timedelta
from typing import Optional
import os
import firebase_admin
from firebase_admin import credentials, messaging
import json

# πŸ”₯ Firebase Setup
firebase_key = json.loads(os.environ["FIREBASE_KEY"])
cred = credentials.Certificate(firebase_key)
firebase_admin.initialize_app(cred)

# =====================================================
# CONFIG
# =====================================================

# --- Brevo Email Config ---
BREVO_API_KEY = os.getenv("KEY")
BREVO_SENDER_EMAIL = "patelkanostudent@gmail.com"
BREVO_SENDER_NAME = "College ERP System"
BREVO_API_URL = "https://api.brevo.com/v3/smtp/email"

# --- Database Config ---
DB_SERVER = "kano2026.mssql.somee.com:1433"   # βœ… fixed
DB_USER = "Dhvanit_SQLLogin_1"
DB_PASSWORD = os.getenv("PASS")
DB_NAME = "kano2026"
# =====================================================

# =====================================================
# FASTAPI APP
# =====================================================
app = FastAPI(title="College ERP Backend")


# =====================================================
# DATABASE CONNECTION
# =====================================================
def get_connection():
    return pymssql.connect(
        server=DB_SERVER,
        user=DB_USER,
        password=DB_PASSWORD,
        database=DB_NAME
    )


# =====================================================
# BREVO EMAIL β€” CORE FUNCTION
# =====================================================
def send_email_brevo(to_email: str, subject: str, body: str) -> bool:
    """
    Send email using Brevo transactional API.
    Returns True on success, False on failure.
    """
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "api-key": BREVO_API_KEY
    }

    payload = {
        "sender": {
            "name": BREVO_SENDER_NAME,
            "email": BREVO_SENDER_EMAIL
        },
        "to": [
            {
                "email": to_email,
                "name": to_email
            }
        ],
        "subject": subject,
        "textContent": body
    }

    try:
        response = requests.post(
            BREVO_API_URL,
            json=payload,
            headers=headers,
            timeout=30
        )

        print(f"Brevo Status Code: {response.status_code}")
        print(f"Brevo Response: {response.text}")

        if response.status_code in (200, 201):
            print(f"Email sent successfully to: {to_email}")
            return True
        else:
            print(f"Brevo FAILED: {response.status_code} - {response.text}")
            return False

    except requests.exceptions.Timeout:
        print("Brevo Error: Request timed out")
        return False

    except requests.exceptions.ConnectionError:
        print("Brevo Error: Cannot connect to Brevo API")
        return False

    except Exception as e:
        print(f"Brevo Error: {e}")
        return False


# =====================================================
# OTP EMAIL
# =====================================================
def generate_otp() -> str:
    return str(random.randint(100000, 999999))


def send_otp_email(email: str, otp: str) -> bool:
    subject = "College Leave Management System β€” Login OTP"
    body = f"Your OTP is {otp}. Valid for 5 minutes."
    return send_email_brevo(email, subject, body)


# =====================================================
# PARENT NOTIFICATION EMAIL
# =====================================================
def send_parent_email(
    parent_email: str,
    student_name: str,
    from_date: str,
    to_date: str,
    reason: str,
    status: str
) -> bool:
    subject = f"Leave {status} Notification"
    body = (
        f"Dear Parent,\n\n"
        f"Your ward {student_name} applied for leave.\n\n"
        f"From: {from_date}\n"
        f"To: {to_date}\n"
        f"Reason: {reason}\n\n"
        f"Status: {status}\n\n"
        f"Thank you.\n"
        f"College ERP System"
    )
    return send_email_brevo(parent_email, subject, body)


# =====================================================
# PYDANTIC MODELS
# =====================================================
class StudentRegister(BaseModel):
    fullname: str
    roll_no: int
    registration_no: str
    semester: int
    student_email: str
    parent_email: str

class SendOTP(BaseModel):
    email: str


class OTPVerify(BaseModel):
    email: str
    otp: str


class LeaveApply(BaseModel):
    student_id: int
    from_date: str
    to_date: str
    reason: str


class EmergencyLeave(BaseModel):
    student_id: int
    from_date: str
    to_date: str
    reason: str


class Action(BaseModel):
    leave_id: int
    action: str


# =====================================================
# TOKEN VALIDATION
# =====================================================
def get_user_from_token(authorization: str) -> int:
    if not authorization:
        raise HTTPException(
            status_code=401,
            detail="Authorization header missing"
        )

    token = authorization.replace("Bearer ", "")

    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            "SELECT UserId FROM LoginSessions "
            "WHERE Token=%s AND IsActive=1",
            (token,)
        )
        row = cursor.fetchone()

        if not row:
            raise HTTPException(
                status_code=401,
                detail="Invalid session"
            )

        return row[0]
    finally:
        conn.close()


# =====================================================
# TEST BREVO EMAIL ENDPOINT
# =====================================================
@app.get("/test/email/{to_email}")
def test_email(to_email: str):
    """
    Test endpoint to check if Brevo email works.
    Usage: GET /test/email/someone@gmail.com
    """
    success = send_email_brevo(
        to_email=to_email,
        subject="Test Email from College ERP",
        body="If you received this, Brevo is working correctly!"
    )

    if success:
        return {
            "status": "success",
            "message": f"Test email sent to {to_email}"
        }
    else:
        raise HTTPException(
            status_code=500,
            detail="Brevo email failed. Check console logs."
        )


# =====================================================
# DASHBOARD
# =====================================================
@app.get("/dashboard")
def dashboard():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            "SELECT COUNT(*) FROM Users "
            "WHERE Role='STUDENT' AND IsActive=1"
        )
        count = cursor.fetchone()[0]
        return {"total_students": count}
    finally:
        conn.close()


# =====================================================
# STUDENT REGISTER
# =====================================================
@app.post("/student/register")
def student_register(data: StudentRegister):
    nms = 0
    conn = get_connection()
    try:
        cursor = conn.cursor()

        # Check duplicate email
        cursor.execute(
            "SELECT 1 FROM Users WHERE Email=%s",
            (data.student_email,)
        )
        if cursor.fetchone():
            raise HTTPException(
                status_code=400,
                detail="Email already registered"
            )

        # Check duplicate registration
        cursor.execute(
            "SELECT 1 FROM StudentProfile WHERE RegistrationNo=%s",
            (data.registration_no,)
        )
        if cursor.fetchone():
            raise HTTPException(
                status_code=400,
                detail="Student already registered"
            )

        # Insert user
        cursor.execute(
            "INSERT INTO Users (FullName, Email, Role) "
            "VALUES (%s, %s, 'STUDENT')",
            (data.fullname, data.student_email)
        )

        # Get new user ID
        cursor.execute("SELECT SCOPE_IDENTITY()")
        student_id = cursor.fetchone()[0]
        nms = nms + 1

        # Insert student profile
        cursor.execute(
            """
            INSERT INTO StudentProfile
            (StudentId, RollNo, RegistrationNo,
             Semester, StudentEmail, ParentEmail)
            VALUES (%s, %s, %s, %s, %s, %s)
            """,
            (
                student_id,
                data.roll_no,
                data.registration_no,
                data.semester,
                data.student_email,
                data.parent_email
            )
        )

        # Find available professor
        cursor.execute(
    """
    SELECT p.ProfessorId
    FROM ProfessorProfile p
    LEFT JOIN StudentProfessorMapping sp
        ON p.ProfessorId = sp.ProfessorId
        AND sp.Semester = %s
    GROUP BY p.ProfessorId
    HAVING COUNT(sp.StudentId) < 7
    ORDER BY COUNT(sp.StudentId) ASC
    """,
    (data.semester,)
)
        prof = cursor.fetchone()

        if not prof:
            raise HTTPException(
                status_code=400,
                detail="No professor available"
            )

        # Map student to professor
        cursor.execute(
            """
            INSERT INTO StudentProfessorMapping
            (StudentId, ProfessorId, Semester)
            VALUES (%s, %s, %s)
            """,
            (student_id, prof[0], data.semester)
        )

        conn.commit()

        return {
            "message": "Student registered",
            "professor": prof[0],
            "number_of_student": nms
        }

    except HTTPException:
        raise
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        conn.close()


# =====================================================
# AUTH β€” SEND OTP (via Brevo)
# =====================================================
@app.post("/auth/send-otp")
def send_otp(data: SendOTP):
    conn = get_connection()
    try:
        cursor = conn.cursor()

        # Check user exists
        cursor.execute(
            "SELECT UserId FROM Users "
            "WHERE Email=%s AND IsActive=1",
            (data.email,)
        )
        user = cursor.fetchone()

        if not user:
            raise HTTPException(
                status_code=404,
                detail="User not found"
            )

        # Generate OTP
        otp = generate_otp()
        expiry = datetime.now() + timedelta(minutes=5)

        # Save OTP to database
        cursor.execute(
            "INSERT INTO EmailOTP (Email, OTPCode, ExpiryTime) "
            "VALUES (%s, %s, %s)",
            (data.email, otp, expiry)
        )
        conn.commit()

        # Send OTP via Brevo
        email_sent = send_otp_email(data.email, otp)

        if email_sent:
            return {"message": "OTP sent successfully via Brevo"}
        else:
            return {
                "message": "OTP saved in database but email failed",
                "otp_for_debug": otp,
                "warning": "Check Brevo API key and sender verification"
            }

    except HTTPException:
        raise
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        conn.close()


# =====================================================
# AUTH β€” VERIFY OTP
# =====================================================
@app.post("/auth/verify-otp")
def verify_otp(data: OTPVerify):
    conn = get_connection()
    try:
        cursor = conn.cursor()

        # Validate OTP
        cursor.execute(
            """
            SELECT OTPId FROM EmailOTP
            WHERE Email=%s AND OTPCode=%s
              AND IsUsed=0 AND ExpiryTime>=GETDATE()
            """,
            (data.email, data.otp)
        )
        otp_row = cursor.fetchone()

        if not otp_row:
            raise HTTPException(
                status_code=400,
                detail="Invalid OTP"
            )

        # Mark OTP used
        cursor.execute(
            "UPDATE EmailOTP SET IsUsed=1 WHERE OTPId=%s",
            (otp_row[0],)
        )

        # Get user
        cursor.execute(
            "SELECT UserId, Role FROM Users "
            "WHERE Email=%s AND IsActive=1",
            (data.email,)
        )
        user = cursor.fetchone()

        if not user:
            raise HTTPException(
                status_code=404,
                detail="User not found"
            )

        # Create session
        token = str(uuid.uuid4())

        cursor.execute(
            "UPDATE LoginSessions SET IsActive=0 "
            "WHERE UserId=%s",
            (user[0],)
        )

        cursor.execute(
            "INSERT INTO LoginSessions (UserId, Token) "
            "VALUES (%s, %s)",
            (user[0], token)
        )

        conn.commit()

        return {
            "login": "success",
            "token": token,
            "user_id": user[0],
            "role": user[1]
        }

    except HTTPException:
        raise
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        conn.close()


# =====================================================
# APPLY LEAVE
# =====================================================
@app.post("/leave/apply")
def apply_leave(
    data: LeaveApply,
    authorization: str = Header(None)
):
    
    data.student_id = get_user_from_token(authorization)
    conn = get_connection()
    try:
        cursor = conn.cursor()

        cursor.execute(
            "SELECT ProfessorId FROM StudentProfessorMapping WHERE StudentId=%s",
            (data.student_id,)
        )
        prof = cursor.fetchone()

        cursor.execute("SELECT DeanId FROM DeanProfile")
        dean = cursor.fetchone()

        if not prof or not dean:
            raise HTTPException(status_code=400, detail="Config error")

        # INSERT
        cursor.execute(
            """
            INSERT INTO LeaveApplications
            (StudentId, ProfessorId, DeanId,
             ProfessorStatus, DeanStatus,
             FromDate, ToDate, Reason)
            VALUES (%s,%s,%s,'PENDING','PENDING',%s,%s,%s)
            """,
            (
                data.student_id,
                prof[0],
                dean[0],
                data.from_date,
                data.to_date,
                data.reason
            )
        )

            # Inside @app.post("/leave/apply")
        cursor.execute(
            "SELECT p.FcmToken FROM Users p "
            "JOIN StudentProfessorMapping sp ON p.UserId = sp.ProfessorId "
            "WHERE sp.StudentId = %s", 
            (data.student_id,)
        )
        prof_token = cursor.fetchone()

        if prof_token and prof_token[0]:
            send_fcm(prof_token[0], "New Leave Request", f"Student {data.student_id} has applied for leave.")

    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        conn.close()# =====================================================
# STUDENT LEAVE VIEWS
# =====================================================
@app.get("/student/rejected/{student_id}")
def student_rejected(student_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT LeaveId, FromDate, ToDate, Reason
            FROM LeaveApplications
            WHERE StudentId=%s
              AND FinalStatus LIKE 'REJECTED%%'
            """,
            (student_id,)
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/student/approved/{student_id}")
def student_approved(student_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT LeaveId, FromDate, ToDate, Reason
            FROM LeaveApplications
            WHERE StudentId=%s
              AND FinalStatus='FINAL_APPROVED'
            """,
            (student_id,)
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/student/leaves/{student_id}") # βœ… Added {student_id} to match Flutter
def student_leaves(student_id: int):      # βœ… Accepting ID as a parameter
    conn = get_connection()
    try:
        cursor = conn.cursor()
        # Fetching TOP 5 to keep the dashboard clean
        cursor.execute(
            """
            SELECT TOP 5 
                LeaveId, ProfessorStatus, DeanStatus, FinalStatus, FromDate, ToDate, Reason
            FROM LeaveApplications
            WHERE StudentId=%s
            ORDER BY LeaveId DESC
            """,
            (student_id,)
        )
        rows = cursor.fetchall()
        
        results = []
        for r in rows:
            # --- STATUS MINING LOGIC ---
            # This tells the student exactly who needs to take action next
            if r[3] == 'PENDING' and r[1] == 'PENDING':
                mining_status = "Waiting for Professor"
            elif r[1] == 'APPROVED' and r[2] == 'PENDING':
                mining_status = "Waiting for Dean"
            elif r[3] == 'FINAL_APPROVED':
                mining_status = "Approved βœ…"
            elif 'REJECTED' in r[3]:
                mining_status = "Rejected ❌"
            else:
                mining_status = r[3] # Fallback to FinalStatus

            results.append({
                "leave_id": r[0],
                "professor_status": r[1],
                "dean_status": r[2],
                "final_status": r[3],
                "display_status": mining_status, # βœ… NEW: Send this to Flutter
                "from_date": str(r[4]),
                "to_date": str(r[5]),
                "reason": r[6]
            })
        return results
    finally:
        conn.close()
# =====================================================
# EMERGENCY LEAVE
# =====================================================
@app.post("/leave/emergency")

def emergency_leave(
    data: EmergencyLeave,
    authorization: str = Header(None)
):
    data.student_id= get_user_from_token(authorization)
    conn = get_connection()
    try:
        cursor = conn.cursor()

        cursor.execute(
            "SELECT ProfessorId FROM StudentProfessorMapping "
            "WHERE StudentId=%s",
            (data.student_id,)
        )
        prof = cursor.fetchone()

        cursor.execute("SELECT DeanId FROM DeanProfile")
        dean = cursor.fetchone()

        if not prof or not dean:
            raise HTTPException(
                status_code=400,
                detail="Configuration error"
            )

        cursor.execute(
            """
            INSERT INTO LeaveApplications
            (StudentId, ProfessorId, DeanId,
             ProfessorStatus, DeanStatus,
             FromDate, ToDate, Reason)
            VALUES (%s, %s, %s, 'SKIPPED', 'PENDING', %s, %s, %s)
            """,
            (
                data.student_id,
                prof[0],
                dean[0],
                data.from_date,
                data.to_date,
                data.reason
            )
                )
        # Inside @app.post("/leave/emergency")
        cursor.execute("SELECT FcmToken FROM Users WHERE Role='DEAN'")
        dean_token = cursor.fetchone()

        if dean_token and dean_token[0]:
            send_fcm(dean_token[0], "🚨 EMERGENCY LEAVE", f"Student {data.student_id} requested emergency leave.")
    except HTTPException:
        raise
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        conn.close()


# =====================================================
# DEAN APIs
# =====================================================
@app.get("/dean/pending")
def dean_pending():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, l.StudentId, u.FullName,
                   s.Semester, l.FromDate, l.ToDate, l.Reason
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.DeanStatus='PENDING'
            """
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/dean/approved")
def dean_approved():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, l.StudentId, u.FullName,
                   s.Semester, l.FromDate, l.ToDate, l.Reason
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.DeanStatus='APPROVED'
            """
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/dean/emergency")
def dean_emergency():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, l.StudentId, u.FullName,
                   s.Semester, l.FromDate, l.ToDate, l.Reason
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.ProfessorStatus='SKIPPED'
              AND l.DeanStatus='PENDING'
            """
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/dean/students")
def dean_students():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT u.UserId, u.FullName, s.RollNo,
                   s.RegistrationNo, s.Semester,
                   s.StudentEmail, s.ParentEmail
            FROM Users u
            JOIN StudentProfile s ON u.UserId = s.StudentId
            WHERE u.Role='STUDENT' AND u.IsActive=1
            """
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.post("/leave/dean-action")
def dean_action(data: Action):

    conn = get_connection()
    try:
        cursor = conn.cursor()

        status = "APPROVED" if data.action == "APPROVED" else "REJECTED"
        final_status = (
            "FINAL_APPROVED" if status == "APPROVED"
            else "REJECTED_BY_DEAN"
        )

        cursor.execute(
            """
            UPDATE LeaveApplications
            SET DeanStatus=%s, FinalStatus=%s
            WHERE LeaveId=%s
            """,
            (status, final_status, data.leave_id)
        )

        # Get student + parent info
        cursor.execute(
            """
            SELECT u.FullName, s.ParentEmail,
                   l.FromDate, l.ToDate, l.Reason
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.LeaveId=%s
            """,
            (data.leave_id,)
        )
        row = cursor.fetchone()


        # Send parent email via Brevo
        email_sent = False
        if row:
            try:
                email_sent = send_parent_email(
                    parent_email=row[1],
                    student_name=row[0],
                    from_date=str(row[2]),
                    to_date=str(row[3]),
                    reason=row[4],
                    status=status
                )
            except Exception as mail_err:
                print(f"Parent Email Error: {mail_err}")
 

        # βœ… GET STUDENT TOKEN
        cursor.execute(
            "SELECT u.FcmToken FROM LeaveApplications l "
            "JOIN Users u ON l.StudentId=u.UserId "
            "WHERE l.LeaveId=%s",
            (data.leave_id,)
        )
        student = cursor.fetchone()

        conn.commit()
        # βœ… SEND FCM
        if student and student[0]:
            send_fcm(
                student[0],
                "Leave Status",
                f"Your leave is {status}"
                    )
        # Inside @app.post("/leave/dean-action")
        cursor.execute(
            "SELECT FcmToken FROM Users WHERE UserId = "
            "(SELECT StudentId FROM LeaveApplications WHERE LeaveId = %s)",
            (data.leave_id,)
        )
        student_token = cursor.fetchone()

        if student_token and student_token[0]:
            status_msg = "Approved" if data.action == "APPROVED" else "Rejected"
            send_fcm(student_token[0], "Leave Decision", f"The Dean has {status_msg} your leave request.")
           
        return {
                        "message": f"Dean action done ({status})",
                        "parent_email_sent": email_sent
                    }
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        conn.close()

@app.get("/dean/semester-wise")
def semester_wise():
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT s.Semester,
                   u.FullName AS StudentName,
                   s.RollNo,
                   pUser.FullName AS ProfessorName
            FROM StudentProfessorMapping sp
            JOIN Users u ON sp.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = u.UserId
            JOIN Users pUser ON pUser.UserId = sp.ProfessorId
            ORDER BY s.Semester, s.RollNo
            """
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


# =====================================================
# PROFESSOR APIs
# =====================================================
@app.get("/professor/pending/{professor_id}")
def professor_pending(professor_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, l.StudentId, u.FullName,
                   s.Semester, l.FromDate, l.ToDate, l.Reason
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.ProfessorId=%s
              AND l.ProfessorStatus='PENDING'
            """,
            (professor_id,)
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/professor/approved/{professor_id}")
def professor_approved(professor_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, u.FullName, s.Semester,
                   l.FromDate, l.ToDate
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.ProfessorId=%s
              AND l.ProfessorStatus='APPROVED'
            """,
            (professor_id,)
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/professor/rejected/{professor_id}")
def professor_rejected(professor_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT l.LeaveId, u.FullName, s.Semester,
                   l.FromDate, l.ToDate
            FROM LeaveApplications l
            JOIN Users u ON l.StudentId = u.UserId
            JOIN StudentProfile s ON s.StudentId = l.StudentId
            WHERE l.ProfessorId=%s
              AND l.ProfessorStatus='REJECTED'
            """,
            (professor_id,)
        )
        rows = cursor.fetchall()
        return [list(r) for r in rows]
    finally:
        conn.close()


@app.get("/professor/students/{professor_id}")
def professor_students(professor_id: int):
    conn = get_connection()
    try:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT sp.Semester,
                   COUNT(*) AS total_students
            FROM StudentProfessorMapping sp
            WHERE sp.ProfessorId=%s
            GROUP BY sp.Semester
            """,
            (professor_id,)
        )
        rows = cursor.fetchall()
        return [
            {
                "semester": r[0],
                "total_students": r[1]
            }
            for r in rows
        ]
    finally:
        conn.close()


@app.post("/leave/professor-action")
def professor_action(data: Action):

    conn = get_connection()
    try:
        cursor = conn.cursor()

        status = "APPROVED" if data.action == "APPROVED" else "REJECTED"
        final_status = (
            "FORWARDED_TO_DEAN" if status == "APPROVED"
            else "REJECTED_BY_PROFESSOR"
        )

        cursor.execute(
            """
            UPDATE LeaveApplications
            SET ProfessorStatus=%s, FinalStatus=%s
            WHERE LeaveId=%s
            """,
            (status, final_status, data.leave_id)
        )

        # Inside @app.post("/leave/professor-action")
        if data.action == "APPROVED":
            # Get the Dean's token (assuming there is one Dean or a specific DeanId)
            cursor.execute("SELECT FcmToken FROM Users WHERE Role='DEAN'")
            dean_token = cursor.fetchone()
            
            if dean_token and dean_token[0]:
                send_fcm(dean_token[0], "Leave Forwarded", f"Professor approved Leave ID {data.leave_id}. Action required.")
    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        conn.close()
# =====================================================
# USER PROFILE
# =====================================================
@app.get("/user/profile")
def get_profile(authorization: str = Header(None)):
    user_id = get_user_from_token(authorization)

    conn = get_connection()
    try:
        cursor = conn.cursor()

        cursor.execute(
            "SELECT FullName, Email, Role "
            "FROM Users WHERE UserId=%s",
            (user_id,)
        )
        user = cursor.fetchone()

        if not user:
            raise HTTPException(
                status_code=404,
                detail="User not found"
            )

        role = user[2]

        profile_data = {
            "user_id": user_id,
            "name": user[0],
            "email": user[1],
            "role": role
        }

        # STUDENT
        if role == "STUDENT":
            cursor.execute(
                """
                SELECT RollNo, RegistrationNo, Semester,
                       StudentEmail, ParentEmail
                FROM StudentProfile
                WHERE StudentId=%s
                """,
                (user_id,)
            )
            data = cursor.fetchone()

            if data:
                profile_data.update({
                    "roll_no": data[0],
                    "registration_no": data[1],
                    "semester": data[2],
                    "student_email": data[3],
                    "parent_email": data[4],
                })

        # PROFESSOR
        elif role == "PROFESSOR":
            cursor.execute(
                """
                SELECT ProfessorCode, Email
                FROM ProfessorProfile
                WHERE ProfessorId=%s
                """,
                (user_id,)
            )
            data = cursor.fetchone()

            if data:
                profile_data.update({
                    "professor_code": data[0],
                    "email": data[1],
                })

        # DEAN
        elif role == "DEAN":
            cursor.execute(
                """
                SELECT DeanCode, Email
                FROM DeanProfile
                WHERE DeanId=%s
                """,
                (user_id,)
            )
            data = cursor.fetchone()

            if data:
                profile_data.update({
                    "dean_code": data[0],
                    "email": data[1],
                })

        return profile_data

    finally:
        conn.close()

#==========================================================
# ===============================
# ADD PROFESSOR (DEAN)
# ==========================================================
# ADD PROFESSOR (DEAN)
# ==========================================================

class ProfessorCreate(BaseModel):
    full_name: str
    email: str


@app.post("/dean/add-professor")
def add_professor(prof: ProfessorCreate):

    conn = get_connection()

    try:
        cursor = conn.cursor()

        # check email already exists
        cursor.execute(
            "SELECT UserId FROM Users WHERE Email=%s",
            (prof.email,)
        )

        if cursor.fetchone():
            raise HTTPException(
                status_code=400,
                detail="Email already exists"
            )

        # insert into Users
        cursor.execute(
            """
            INSERT INTO Users (FullName, Email, Role, IsActive, CreatedAt)
            VALUES (%s,%s,'PROFESSOR',1,GETDATE())
            """,
            (prof.full_name, prof.email)
        )

        # get new professor id
        cursor.execute("SELECT SCOPE_IDENTITY()")
        professor_id = cursor.fetchone()[0]

        # generate professor code
        professor_code = f"PROF{int(professor_id):04d}"

        # insert into ProfessorProfile
        cursor.execute(
            """
            INSERT INTO ProfessorProfile
            (ProfessorId, ProfessorCode, Email)
            VALUES (%s,%s,%s)
            """,
            (
                professor_id,
                professor_code,
                prof.email
            )
        )

        conn.commit()

        return {
            "message": "Professor added successfully",
            "professor_id": professor_id,
            "professor_code": professor_code
        }

    except Exception as e:
        conn.rollback()
        raise HTTPException(status_code=500, detail=str(e))

    finally:
        conn.close()
#==========================================================
#============================fcm tocken==============================
class SaveToken(BaseModel):
    user_id: int
    fcm_token: str

@app.post("/save-fcm-token")
def save_fcm_token(
    data: SaveToken, 
    authorization: str = Header(None) # FastAPI looks for 'Authorization' header
):
    # This line triggers the 401 if 'authorization' is missing or token is invalid
    user_id_from_db = get_user_from_token(authorization) 

    conn = get_connection()
    try:
        cursor = conn.cursor()
        # Use the ID from the token for better security
        cursor.execute(
            "UPDATE Users SET FcmToken=%s WHERE UserId=%s",
            (data.fcm_token, user_id_from_db)
        )
        conn.commit()
        return {"message": "Token saved successfully"}
    except Exception as e:
        print(f"Error: {e}")
        raise HTTPException(status_code=500, detail="Database error")
    finally:
        conn.close()
#=======================================================
def send_fcm(token, title, body):
    try:
        message = messaging.Message(
            notification=messaging.Notification(
                title=title,
                body=body,
            ),
            token=token,
        )
        response = messaging.send(message)
        print(f"βœ… FCM sent successfully: {response}")
    except Exception as e:
        # This is where your 'Permission denied' error is coming from
        print(f"❌ FCM FATAL ERROR: {str(e)}")
# =====================================================
# RUN
# =====================================================
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("app:app", host="0.0.0.0", port=7860)