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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
import psycopg2
import psycopg2.extras
import os
import pandas as pd
from datetime import datetime, date
import streamlit as st
import bcrypt

def get_db_connection():
    """Get database connection using environment variables"""
    try:
        # Try using DATABASE_URL first
        database_url = os.getenv('DATABASE_URL')
        if database_url:
            conn = psycopg2.connect(database_url)
        else:
            # Fallback to individual parameters
            conn = psycopg2.connect(
                host=os.getenv('PGHOST', 'localhost'),
                database=os.getenv('PGDATABASE', 'skillverse'),
                user=os.getenv('PGUSER', 'postgres'),
                password=os.getenv('PGPASSWORD', 'password'),
                port=os.getenv('PGPORT', '5432')
            )
        return conn
    except Exception as e:
        st.error(f"Database connection failed: {str(e)}")
        return None

def init_database():
    """Initialize database with required tables and sample data"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        
        # Create users table
        cur.execute("""
            CREATE TABLE IF NOT EXISTS users (
                id SERIAL PRIMARY KEY,
                email VARCHAR(255) UNIQUE NOT NULL,
                password_hash VARCHAR(255),
                name VARCHAR(255) NOT NULL,
                role VARCHAR(50) NOT NULL CHECK (role IN ('student', 'faculty')),
                roll_number INTEGER,
                points INTEGER DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        """)
        
        # Create achievements table
        cur.execute("""
            CREATE TABLE IF NOT EXISTS achievements (
                id SERIAL PRIMARY KEY,
                student_id INTEGER NOT NULL,
                title VARCHAR(255) NOT NULL,
                description TEXT,
                proof_url VARCHAR(255),
                status VARCHAR(50) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')),
                points_awarded INTEGER DEFAULT 0,
                reviewed_by INTEGER,
                reviewed_at TIMESTAMP,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES users (id),
                FOREIGN KEY (reviewed_by) REFERENCES users (id)
            )
        """)
        
        # Create attendance table
        cur.execute("""
            CREATE TABLE IF NOT EXISTS attendance (
                id SERIAL PRIMARY KEY,
                date DATE NOT NULL,
                student_id INTEGER NOT NULL,
                class_name VARCHAR(255),
                present BOOLEAN NOT NULL,
                FOREIGN KEY (student_id) REFERENCES users (id)
            )
        """)
        
        # Insert sample users if they don't exist
        cur.execute("SELECT COUNT(*) FROM users")
        user_count_result = cur.fetchone()
        user_count = user_count_result[0] if user_count_result else 0
        
        if user_count == 0:
            # Insert sample students
            students = [
                ('alex@student.com', 'Alex Johnson', 'student', 1001),
                ('sara@student.com', 'Sara Wilson', 'student', 1002),
                ('mike@student.com', 'Mike Chen', 'student', 1003),
                ('emily@student.com', 'Emily Davis', 'student', 1004),
                ('david@student.com', 'David Brown', 'student', 1005),
                ('lisa@student.com', 'Lisa Garcia', 'student', 1006),
                ('james@student.com', 'James Miller', 'student', 1007),
                ('anna@student.com', 'Anna Taylor', 'student', 1008),
                ('tom@student.com', 'Tom Anderson', 'student', 1009),
                ('sophie@student.com', 'Sophie Clark', 'student', 1010)
            ]
            
            for email, name, role, roll in students:
                cur.execute("""
                    INSERT INTO users (email, name, role, roll_number, points)
                    VALUES (%s, %s, %s, %s, %s)
                """, (email, name, role, roll, 0))
            
            # Insert sample faculty
            cur.execute("""
                INSERT INTO users (email, name, role, points)
                VALUES ('prof.smith@faculty.com', 'Professor Smith', 'faculty', 0)
            """)
            
            # Insert sample faculty 2
            cur.execute("""
                INSERT INTO users (email, name, role, points)
                VALUES ('dr.jones@faculty.com', 'Dr. Jones', 'faculty', 0)
            """)
        
        conn.commit()
        cur.close()
        conn.close()
        
        # Update existing users with default passwords (demo mode only)
        if os.getenv('DEMO_MODE', 'true').lower() == 'true':
            update_existing_users_passwords()
        
        return True
        
    except Exception as e:
        st.error(f"Database initialization failed: {str(e)}")
        if conn:
            conn.rollback()
        if 'cur' in locals():
            cur.close()
        if conn:
            conn.close()
        return False

def get_user_by_role(role):
    """Get all users by role for authentication dropdown"""
    conn = get_db_connection()
    if not conn:
        return []
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("SELECT id, name, email, role, roll_number FROM users WHERE role = %s ORDER BY name", (role,))
        users = cur.fetchall()
        cur.close()
        conn.close()
        return users
    except Exception as e:
        st.error(f"Error fetching users: {str(e)}")
        return []

def get_user_profile(user_id):
    """Get user profile with calculated attendance percentage"""
    conn = get_db_connection()
    if not conn:
        return None
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        
        # Get user basic info
        cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
        user = cur.fetchone()
        
        if not user:
            cur.close()
            conn.close()
            return None
        
        # Calculate attendance percentage
        cur.execute("""
            SELECT 
                COUNT(*) as total_classes,
                SUM(CASE WHEN present THEN 1 ELSE 0 END) as attended_classes
            FROM attendance 
            WHERE student_id = %s
        """, (user_id,))
        
        attendance_data = cur.fetchone()
        
        if attendance_data and attendance_data['total_classes'] and attendance_data['total_classes'] > 0:
            attendance_percentage = (attendance_data['attended_classes'] / attendance_data['total_classes']) * 100
        else:
            attendance_percentage = 0
        
        # Get user's rank
        cur.execute("""
            SELECT COUNT(*) + 1 as rank
            FROM users 
            WHERE role = 'student' AND points > %s
        """, (user['points'],))
        
        rank_data = cur.fetchone()
        
        user_profile = dict(user)
        user_profile['attendance_percentage'] = round(attendance_percentage, 1)
        user_profile['rank'] = rank_data['rank'] if rank_data else 1
        
        cur.close()
        conn.close()
        return user_profile
        
    except Exception as e:
        st.error(f"Error fetching user profile: {str(e)}")
        return None

def get_user_achievements(user_id):
    """Get all achievements for a user"""
    conn = get_db_connection()
    if not conn:
        return []
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("""
            SELECT a.*, u.name as reviewed_by_name
            FROM achievements a
            LEFT JOIN users u ON a.reviewed_by = u.id
            WHERE a.student_id = %s
            ORDER BY a.created_at DESC
        """, (user_id,))
        
        achievements = cur.fetchall()
        cur.close()
        conn.close()
        return achievements
        
    except Exception as e:
        st.error(f"Error fetching achievements: {str(e)}")
        return []

def submit_achievement(student_id, title, description, proof_url):
    """Submit a new achievement"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        cur.execute("""
            INSERT INTO achievements (student_id, title, description, proof_url)
            VALUES (%s, %s, %s, %s)
        """, (student_id, title, description, proof_url))
        
        conn.commit()
        cur.close()
        conn.close()
        return True
        
    except Exception as e:
        st.error(f"Error submitting achievement: {str(e)}")
        conn.rollback()
        return False

def get_pending_achievements():
    """Get all pending achievements for faculty review"""
    conn = get_db_connection()
    if not conn:
        return []
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("""
            SELECT a.*, u.name as student_name, u.roll_number
            FROM achievements a
            JOIN users u ON a.student_id = u.id
            WHERE a.status = 'pending'
            ORDER BY a.created_at ASC
        """, )
        
        achievements = cur.fetchall()
        cur.close()
        conn.close()
        return achievements
        
    except Exception as e:
        st.error(f"Error fetching pending achievements: {str(e)}")
        return []

def review_achievement(achievement_id, action, points, faculty_id):
    """Approve or reject an achievement"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        
        # Update achievement status
        cur.execute("""
            UPDATE achievements 
            SET status = %s, points_awarded = %s, reviewed_by = %s, reviewed_at = %s
            WHERE id = %s
        """, (action, points if action == 'approved' else 0, faculty_id, datetime.now(), achievement_id))
        
        # If approved, update student's total points
        if action == 'approved':
            cur.execute("""
                UPDATE users 
                SET points = points + %s
                WHERE id = (SELECT student_id FROM achievements WHERE id = %s)
            """, (points, achievement_id))
        
        conn.commit()
        cur.close()
        conn.close()
        return True
        
    except Exception as e:
        st.error(f"Error reviewing achievement: {str(e)}")
        conn.rollback()
        return False

def get_leaderboard():
    """Get student leaderboard ordered by points"""
    conn = get_db_connection()
    if not conn:
        return []
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("""
            SELECT 
                name, 
                roll_number, 
                points,
                ROW_NUMBER() OVER (ORDER BY points DESC, name ASC) as rank
            FROM users 
            WHERE role = 'student'
            ORDER BY points DESC, name ASC
        """)
        
        leaderboard = cur.fetchall()
        cur.close()
        conn.close()
        return leaderboard
        
    except Exception as e:
        st.error(f"Error fetching leaderboard: {str(e)}")
        return []

def upload_attendance(class_name, date, roll_numbers):
    """Upload attendance for multiple students"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        
        # Get all students
        cur.execute("SELECT id, roll_number FROM users WHERE role = 'student'")
        students = cur.fetchall()
        
        # Mark attendance for all students
        for student_id, roll_number in students:
            present = roll_number in roll_numbers
            
            # Check if attendance already exists for this date and student
            cur.execute("""
                SELECT id FROM attendance 
                WHERE date = %s AND student_id = %s AND class_name = %s
            """, (date, student_id, class_name))
            
            existing = cur.fetchone()
            
            if existing:
                # Update existing record
                cur.execute("""
                    UPDATE attendance 
                    SET present = %s
                    WHERE date = %s AND student_id = %s AND class_name = %s
                """, (present, date, student_id, class_name))
            else:
                # Insert new record
                cur.execute("""
                    INSERT INTO attendance (date, student_id, class_name, present)
                    VALUES (%s, %s, %s, %s)
                """, (date, student_id, class_name, present))
        
        conn.commit()
        cur.close()
        conn.close()
        return True
        
    except Exception as e:
        st.error(f"Error uploading attendance: {str(e)}")
        conn.rollback()
        return False

def hash_password(password):
    """Hash a password for storing in database"""
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed.decode('utf-8')

def verify_password(password, hashed):
    """Verify a password against its hash"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))

def authenticate_user(email, password):
    """Authenticate user with email and password"""
    conn = get_db_connection()
    if not conn:
        return None
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("SELECT * FROM users WHERE email = %s", (email,))
        user = cur.fetchone()
        
        if user and user['password_hash'] and verify_password(password, user['password_hash']):
            cur.close()
            conn.close()
            return dict(user)
        
        cur.close()
        conn.close()
        return None
        
    except Exception as e:
        st.error(f"Authentication failed: {str(e)}")
        if conn:
            conn.close()
        return None

def register_user(email, password, name, role, roll_number=None):
    """Register a new user"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        
        # Check if email already exists
        cur.execute("SELECT id FROM users WHERE email = %s", (email,))
        existing_user = cur.fetchone()
        if existing_user:
            st.error("Email already registered")
            if conn:
                cur.close()
                conn.close()
            return False
        
        # Hash password and create user
        password_hash = hash_password(password)
        
        if role == 'student' and roll_number:
            cur.execute("""
                INSERT INTO users (email, password_hash, name, role, roll_number, points)
                VALUES (%s, %s, %s, %s, %s, 0)
            """, (email, password_hash, name, role, roll_number))
        else:
            cur.execute("""
                INSERT INTO users (email, password_hash, name, role, points)
                VALUES (%s, %s, %s, %s, 0)
            """, (email, password_hash, name, role))
        
        conn.commit()
        cur.close()
        conn.close()
        return True
        
    except Exception as e:
        st.error(f"Registration failed: {str(e)}")
        if conn:
            conn.rollback()
            conn.close()
        return False

def update_existing_users_passwords():
    """Update existing demo users with default passwords for testing"""
    conn = get_db_connection()
    if not conn:
        return False
    
    try:
        cur = conn.cursor()
        
        # Update all users without password_hash to have default password "password123"
        default_password_hash = hash_password("password123")
        cur.execute("""
            UPDATE users 
            SET password_hash = %s 
            WHERE password_hash IS NULL OR password_hash = ''
        """, (default_password_hash,))
        
        conn.commit()
        cur.close()
        conn.close()
        return True
        
    except Exception as e:
        st.error(f"Error updating passwords: {str(e)}")
        if conn:
            conn.rollback()
            conn.close()
        return False

def get_student_portfolio(student_id):
    """Get complete student portfolio with achievements and stats"""
    conn = get_db_connection()
    if not conn:
        return None
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        
        # Get student profile
        cur.execute("""
            SELECT id, name, email, roll_number, points, created_at
            FROM users 
            WHERE id = %s AND role = 'student'
        """, (student_id,))
        
        student = cur.fetchone()
        if not student:
            cur.close()
            conn.close()
            return None
        
        # Get student achievements with approval details
        cur.execute("""
            SELECT a.*, u.name as reviewed_by_name
            FROM achievements a
            LEFT JOIN users u ON a.reviewed_by = u.id
            WHERE a.student_id = %s AND a.status = 'approved'
            ORDER BY a.reviewed_at DESC
        """, (student_id,))
        
        achievements = cur.fetchall()
        
        # Get student rank
        cur.execute("""
            SELECT COUNT(*) + 1 as rank
            FROM users 
            WHERE role = 'student' AND points > %s
        """, (student['points'],))
        
        rank_data = cur.fetchone()
        
        # Calculate achievement stats
        cur.execute("""
            SELECT 
                COUNT(*) as total_achievements,
                SUM(points_awarded) as total_points_from_achievements,
                AVG(points_awarded) as avg_points_per_achievement
            FROM achievements 
            WHERE student_id = %s AND status = 'approved'
        """, (student_id,))
        
        stats = cur.fetchone()
        
        # Calculate attendance percentage
        cur.execute("""
            SELECT 
                COUNT(*) as total_classes,
                SUM(CASE WHEN present THEN 1 ELSE 0 END) as attended_classes
            FROM attendance 
            WHERE student_id = %s
        """, (student_id,))
        
        attendance_data = cur.fetchone()
        
        portfolio = {
            'student': dict(student),
            'achievements': [dict(a) for a in achievements],
            'rank': rank_data['rank'] if rank_data else 1,
            'stats': dict(stats) if stats else {
                'total_achievements': 0,
                'total_points_from_achievements': 0,
                'avg_points_per_achievement': 0
            },
            'attendance_percentage': (
                (attendance_data['attended_classes'] / attendance_data['total_classes'] * 100) 
                if attendance_data and attendance_data['total_classes'] > 0 else 0
            )
        }
        
        cur.close()
        conn.close()
        return portfolio
        
    except Exception as e:
        st.error(f"Error fetching student portfolio: {str(e)}")
        if conn:
            conn.close()
        return None

def get_all_students_for_portfolio():
    """Get all students for portfolio browsing"""
    conn = get_db_connection()
    if not conn:
        return []
    
    try:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cur.execute("""
            SELECT 
                id, name, roll_number, points,
                ROW_NUMBER() OVER (ORDER BY points DESC, name ASC) as rank
            FROM users 
            WHERE role = 'student'
            ORDER BY points DESC, name ASC
        """)
        
        students = cur.fetchall()
        cur.close()
        conn.close()
        return students
        
    except Exception as e:
        st.error(f"Error fetching students: {str(e)}")
        return []