<?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'];
$subject_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$subject_id) {
    header('Location: subjects.php');
    exit();
}

$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();

// Check if student is enrolled in this subject
$enrollment_check = "SELECT * FROM enrollments WHERE student_id = ? AND subject_id = ?";
$stmt = $conn->prepare($enrollment_check);
$stmt->bind_param("ii", $student_id, $subject_id);
$stmt->execute();
$is_enrolled = $stmt->get_result()->num_rows > 0;
$stmt->close();

if (!$is_enrolled) {
    header('Location: subjects.php');
    exit();
}

// Get subject details with instructor info
$subject_query = "SELECT s.*, u.full_name as instructor_name, u.email as instructor_email, u.profile_picture as instructor_picture
                  FROM subjects s
                  LEFT JOIN users u ON s.instructor_id = u.id
                  WHERE s.id = ?";
$stmt = $conn->prepare($subject_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$subject_result = $stmt->get_result();
$subject = $subject_result->fetch_assoc();
$stmt->close();

if (!$subject) {
    header('Location: subjects.php');
    exit();
}

// Get all enrolled students (classmates)
$classmates_query = "SELECT u.*, e.enrolled_at
                     FROM users u
                     JOIN enrollments e ON u.id = e.student_id
                     WHERE e.subject_id = ?
                     ORDER BY u.year_level, u.section, u.full_name";
$stmt = $conn->prepare($classmates_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$classmates_result = $stmt->get_result();
$classmates = [];
while ($row = $classmates_result->fetch_assoc()) {
    $classmates[] = $row;
}
$stmt->close();

// Get activities count
$activities_query = "SELECT COUNT(*) as count FROM activities WHERE subject_id = ?";
$stmt = $conn->prepare($activities_query);
$stmt->bind_param("i", $subject_id);
$stmt->execute();
$activities_count = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 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", $subject_id, $student_id);
$avg_stmt->execute();
$avg_result = $avg_stmt->get_result();
$avg_data = $avg_result->fetch_assoc();
$avg_stmt->close();

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

// 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><?php echo htmlspecialchars($subject['subject_name']); ?> - 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" style="display: block;">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;">
                <div>
                    <a href="subjects.php" style="color: var(--primary-moss); text-decoration: none;">← Back to My Subjects</a>
                    <h1>📚 <?php echo htmlspecialchars($subject['subject_name']); ?></h1>
                    <p><?php echo htmlspecialchars($subject['subject_code']); ?></p>
                </div>
                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-primary">View Activities</a>
            </div>

            <!-- Average Score Box -->
            <?php if ($avg_score !== null): ?>
                <div style="background: linear-gradient(135deg, <?php echo $avg_score >= 75 ? '#28a745' : '#dc3545'; ?> 0%, <?php echo $avg_score >= 75 ? '#20c997' : '#bd2130'; ?> 100%); padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); text-align: center; color: white;">
                    <div style="font-size: 3em; font-weight: bold; margin-bottom: 10px;">
                        <?php echo number_format($avg_score, 2); ?>%
                    </div>
                    <div style="font-size: 1.2em; margin-bottom: 5px;">
                        📊 Average Score
                    </div>
                    <div style="font-size: 0.9em; opacity: 0.9;">
                        Based on <?php echo $graded_count; ?> graded submission<?php echo $graded_count != 1 ? 's' : ''; ?>
                    </div>
                </div>
            <?php else: ?>
                <div style="background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%); padding: 25px; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); text-align: center; color: white;">
                    <div style="font-size: 2em; margin-bottom: 10px;">
                        📊
                    </div>
                    <div style="font-size: 1.2em;">
                        No Graded Submissions Yet
                    </div>
                    <div style="font-size: 0.9em; opacity: 0.9; margin-top: 5px;">
                        Complete activities to see your average score
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Subject Info -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📋 Subject Information</h2>
            </div>
            <div class="info-grid">
                <div class="info-item">
                    <strong>Description:</strong>
                    <p><?php echo htmlspecialchars($subject['description']); ?></p>
                </div>
                <div class="info-item">
                    <strong>Instructor:</strong>
                    <div style="display: flex; align-items: center; gap: 15px; margin-top: 10px;">
                        <?php if (isset($subject['instructor_picture']) && $subject['instructor_picture']): ?>
                            <img src="../<?php echo htmlspecialchars($subject['instructor_picture']); ?>" alt="Instructor" style="width: 60px; height: 60px; border-radius: 50%; object-fit: cover; border: 3px solid var(--primary-moss);">
                        <?php else: ?>
                            <div style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center; color: white; font-size: 24px; font-weight: bold;">
                                <?php echo strtoupper(substr($subject['instructor_name'], 0, 1)); ?>
                            </div>
                        <?php endif; ?>
                        <div>
                            <p style="margin: 0; font-size: 1.1em;"><?php echo htmlspecialchars($subject['instructor_name'] ?? 'No Instructor'); ?></p>
                            <?php if ($subject['instructor_email']): ?>
                                <p style="margin: 5px 0 0 0; color: var(--text-secondary); font-size: 0.9em;">
                                    📧 <?php echo htmlspecialchars($subject['instructor_email']); ?>
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="info-item">
                    <strong>Statistics:</strong>
                    <p>👥 <?php echo count($classmates); ?> Students | 📝 <?php echo $activities_count; ?> Activities</p>
                </div>
            </div>
        </div>

        <!-- Classmates -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>👥 Classmates (<?php echo count($classmates); ?>)</h2>
            </div>
            <?php if (!empty($classmates)): ?>
                <div class="students-grid">
                    <?php foreach ($classmates as $classmate): ?>
                        <div class="student-card">
                            <div class="student-avatar-container">
                                <?php if (isset($classmate['profile_picture']) && $classmate['profile_picture']): ?>
                                    <img src="../<?php echo htmlspecialchars($classmate['profile_picture']); ?>" alt="Profile" class="student-avatar-large">
                                <?php else: ?>
                                    <div class="student-avatar-large" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; display: flex; align-items: center; justify-content: center; font-size: 48px; font-weight: bold;">
                                        <?php echo strtoupper(substr($classmate['full_name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="student-info">
                                <h3><?php echo htmlspecialchars($classmate['full_name']); ?>
                                    <?php if ($classmate['id'] == $student_id): ?>
                                        <span style="color: var(--primary-moss); font-size: 0.8em;">(You)</span>
                                    <?php endif; ?>
                                </h3>
                                <p class="student-id">🆔 <?php echo htmlspecialchars($classmate['id_number'] ?? 'N/A'); ?></p>
                                <p class="student-detail">📚 <?php echo htmlspecialchars($classmate['year_level'] ?? 'N/A'); ?> - Section <?php echo htmlspecialchars($classmate['section'] ?? 'N/A'); ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">👥 No classmates enrolled yet.</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>
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .info-item {
            padding: 15px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
        }

        .info-item strong {
            color: var(--primary-moss);
            display: block;
            margin-bottom: 8px;
        }

        .students-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .student-card {
            background: var(--card-bg);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
        }

        .student-avatar-container {
            margin-bottom: 15px;
        }

        .student-avatar-large {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--primary-moss);
        }

        .student-info {
            width: 100%;
        }

        .student-info h3 {
            margin: 0 0 10px 0;
            color: var(--text-primary);
            font-size: 1em;
        }

        .student-id {
            color: var(--primary-moss);
            font-weight: 600;
            margin: 5px 0;
            font-size: 0.9em;
        }

        .student-detail {
            color: var(--text-secondary);
            margin: 5px 0;
            font-size: 0.85em;
        }
    </style>
</body>
</html>
