<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] != 'student') {
    header('Location: ../index.php');
    exit();
}

$student_id = $_SESSION['user_id'];
$conn = getDBConnection();

// Get user data including profile picture
$user_query = "SELECT profile_picture FROM users WHERE id = ?";
$stmt = $conn->prepare($user_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Get enrolled subjects with details
$subjects_query = "SELECT s.*, u.full_name as instructor_name, u.email as instructor_email,
                   (SELECT COUNT(*) FROM enrollments e WHERE e.subject_id = s.id) as total_students,
                   (SELECT COUNT(*) FROM activities a WHERE a.subject_id = s.id) as activity_count
                   FROM subjects s
                   JOIN enrollments e ON s.id = e.subject_id
                   LEFT JOIN users u ON s.instructor_id = u.id
                   WHERE e.student_id = ?
                   ORDER BY s.subject_name";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    // Calculate average score for this subject
    $avg_query = "SELECT AVG(sub.score) as avg_score, COUNT(*) as graded_count
                  FROM submissions sub
                  JOIN activities a ON sub.activity_id = a.id
                  WHERE a.subject_id = ? AND sub.student_id = ? AND sub.status = 'graded'";
    $avg_stmt = $conn->prepare($avg_query);
    $avg_stmt->bind_param("ii", $row['id'], $student_id);
    $avg_stmt->execute();
    $avg_result = $avg_stmt->get_result();
    $avg_data = $avg_result->fetch_assoc();
    $avg_stmt->close();

    $row['avg_score'] = $avg_data['avg_score'] ? round($avg_data['avg_score'], 2) : null;
    $row['graded_count'] = $avg_data['graded_count'];

    $subjects[] = $row;
}
$stmt->close();

// Get unread notifications count
$notif_count_query = "SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE";
$stmt = $conn->prepare($notif_count_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$notif_result = $stmt->get_result();
$notif_count = $notif_result->fetch_assoc()['count'];
$stmt->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Subjects - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="../assets/js/dark-mode.js" defer>
        // HTML escape function to prevent XSS
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
</script>
    <script src="../assets/js/interactive-pet.js" defer></script>
    <script src="../assets/js/push-notifications.js" defer></script>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-brand">
                <?php if (isset($user['profile_picture']) && $user['profile_picture']): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile" class="nav-profile-pic">
                <?php else: ?>
                    <div class="nav-avatar"><?php echo strtoupper(substr($_SESSION['full_name'], 0, 1)); ?></div>
                <?php endif; ?>
                <h2>CODELAB</h2>
            </div>
            <button class="burger-menu" onclick="toggleMenu()">
                <span></span>
                <span></span>
                <span></span>
            </button>
            <div class="nav-menu" id="nav-menu">
                <a href="dashboard.php" class="nav-link">Dashboard</a>
                <a href="subjects.php" class="nav-link active">My Subjects</a>
                <a href="activities.php" class="nav-link">Activities</a>
                <a href="grades.php" class="nav-link">Grades</a>
                <a href="profile.php" class="nav-link">Profile</a>
                <a href="#" class="nav-link notification-bell" onclick="toggleNotifications()">
                    🔔 Notifications
                    <?php if ($notif_count > 0): ?>
                        <span class="badge"><?php echo $notif_count; ?></span>
                    <?php endif; ?>
                </a>
                <a href="../auth/logout.php" class="nav-link logout">Logout</a>
            </div>
        </div>
    </nav>

    <!-- Notifications Panel -->
    <div id="notifications-panel" class="notifications-panel">
        <div class="notifications-header">
            <h3>📬 Notifications</h3>
            <button onclick="toggleNotifications()" class="close-btn">×</button>
        </div>
        <div class="notifications-content" id="notifications-content">
            <p class="loading">Loading notifications...</p>
        </div>
    </div>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>📚 My Subjects</h1>
            <a href="enroll.php" class="btn btn-primary">+ Enroll in Subject</a>
        </div>

        <!-- Subjects Grid -->
        <div class="dashboard-section full-width">
            <?php if (!empty($subjects)): ?>
                <div class="subjects-grid">
                    <?php foreach ($subjects as $subject): ?>
                        <div class="subject-card" style="cursor: pointer;" onclick="window.location.href='subject_details.php?id=<?php echo $subject['id']; ?>'">
                            <div class="subject-header">
                                <h3><?php echo htmlspecialchars($subject['subject_name']); ?></h3>
                                <span class="subject-code"><?php echo htmlspecialchars($subject['subject_code']); ?></span>
                            </div>
                            <p class="subject-description"><?php echo htmlspecialchars($subject['description']); ?></p>
                            <div class="subject-info">
                                <p class="instructor-info">
                                    👨‍🏫 <strong><?php echo htmlspecialchars($subject['instructor_name']); ?></strong>
                                </p>
                                <p class="subject-stats">
                                    👥 <?php echo $subject['total_students']; ?> Students |
                                    📝 <?php echo $subject['activity_count']; ?> Activities
                                </p>
                                <?php if ($subject['avg_score'] !== null): ?>
                                    <div class="subject-score" style="margin-top: 12px; padding: 10px; background: <?php echo $subject['avg_score'] >= 75 ? 'rgba(40, 167, 69, 0.1)' : 'rgba(220, 53, 69, 0.1)'; ?>; border-radius: 8px; border-left: 4px solid <?php echo $subject['avg_score'] >= 75 ? '#28a745' : '#dc3545'; ?>;">
                                        <strong style="color: <?php echo $subject['avg_score'] >= 75 ? '#28a745' : '#dc3545'; ?>; font-size: 1.1em;">
                                            📊 Average Score: <?php echo number_format($subject['avg_score'], 2); ?>%
                                        </strong>
                                        <small style="display: block; margin-top: 4px; color: var(--text-secondary);">
                                            Based on <?php echo $subject['graded_count']; ?> graded submission<?php echo $subject['graded_count'] != 1 ? 's' : ''; ?>
                                        </small>
                                    </div>
                                <?php else: ?>
                                    <div class="subject-score" style="margin-top: 12px; padding: 10px; background: rgba(108, 117, 125, 0.1); border-radius: 8px;">
                                        <small style="color: var(--text-secondary);">📊 No graded submissions yet</small>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="subject-footer">
                                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small" onclick="event.stopPropagation()">
                                    View Activities
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">📚 You haven't enrolled in any subjects yet. <a href="enroll.php">Enroll now</a></p>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function toggleMenu() {
            const navMenu = document.getElementById('nav-menu');
            navMenu.classList.toggle('active');
        }

        function toggleNotifications() {
            const panel = document.getElementById('notifications-panel');
            const isOpen = panel.classList.contains('open');

            if (isOpen) {
                panel.classList.remove('open');
            } else {
                panel.classList.add('open');
                loadNotifications();
            }
        }

        function loadNotifications() {
            const content = document.getElementById('notifications-content');

            fetch('get_notifications.php')
                .then(response => response.json())
                .then(data => {
                    if (data.length === 0) {
                        content.innerHTML = '<p class="empty-message">No notifications yet.</p>';
                    } else {
                        let html = '';
                        data.forEach(notif => {
                            html += `
                                <div class="notification-item ${notif.is_read ? '' : 'unread'}">
                                    <p>${escapeHtml(notif.message)}</p>
                                    <span class="notif-time">${escapeHtml(notif.created_at)}</span>
                                    ${notif.activity_id ? `<a href="take_activity.php?id=${notif.activity_id}" class="notif-link">View Activity →</a>` : ''}
                                </div>
                            `;
                        });
                        content.innerHTML = html;

                        fetch('mark_notifications_read.php');
                    }
                })
                .catch(error => {
                    content.innerHTML = '<p class="error-message">Failed to load notifications.</p>';
                });
        }

        document.addEventListener('click', function(event) {
            const panel = document.getElementById('notifications-panel');
            const target = event.target;

            if (!panel.contains(target) && !target.closest('.nav-link')) {
                panel.classList.remove('open');
            }
        });
    </script>

    <style>
        .subject-info {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .instructor-info {
            color: var(--text-secondary);
            margin-bottom: 8px;
            font-size: 0.9em;
        }

        .subject-stats {
            color: var(--text-secondary);
            font-size: 0.85em;
            opacity: 0.8;
        }
    </style>
</body>
</html>
