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

// Check if user is logged in and is a student
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
$subjects_query = "SELECT s.*, u.full_name as instructor_name 
                   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 = ?";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$enrolled_subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $enrolled_subjects[] = $row;
}
$stmt->close();

// Get recent scores
$scores_query = "SELECT a.title, s.score, s.submitted_at, sub.subject_name, s.status
                 FROM submissions s
                 JOIN activities a ON s.activity_id = a.id
                 JOIN subjects sub ON a.subject_id = sub.id
                 WHERE s.student_id = ?
                 ORDER BY s.submitted_at DESC
                 LIMIT 5";
$stmt = $conn->prepare($scores_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$scores_result = $stmt->get_result();
$recent_scores = [];
while ($row = $scores_result->fetch_assoc()) {
    $recent_scores[] = $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();

// Get pending activities (not submitted yet)
$pending_query = "SELECT a.*, s.subject_name, s.subject_code,
                  (SELECT COUNT(*) FROM submissions sub WHERE sub.activity_id = a.id AND sub.student_id = ?) as submitted
                  FROM activities a
                  JOIN subjects s ON a.subject_id = s.id
                  JOIN enrollments e ON s.id = e.subject_id
                  WHERE e.student_id = ?
                  HAVING submitted = 0
                  ORDER BY a.due_date ASC";
$stmt = $conn->prepare($pending_query);
$stmt->bind_param("ii", $student_id, $student_id);
$stmt->execute();
$pending_result = $stmt->get_result();
$pending_activities = [];
while ($row = $pending_result->fetch_assoc()) {
    $pending_activities[] = $row;
}
$stmt->close();

// Get total activities completed
$completed_query = "SELECT COUNT(*) as count FROM submissions WHERE student_id = ?";
$stmt = $conn->prepare($completed_query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$completed_result = $stmt->get_result();
$completed_count = $completed_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>Student Dashboard - CODELAB</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/tutorial.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/tutorial.js" defer></script>
    <script src="../assets/js/student-tutorial-steps.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 active">Dashboard</a>
                <a href="subjects.php" class="nav-link">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">
            <div class="welcome-section">
                <h1>Welcome, <?php echo htmlspecialchars($_SESSION['full_name']); ?>! 👋</h1>
                <p>Ready to continue your C/C++ programming journey?</p>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">✅</div>
                <div class="stat-info">
                    <h3>Completed Activities</h3>
                    <p class="stat-value"><?php echo $completed_count; ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">⏳</div>
                <div class="stat-info">
                    <h3>Pending Activities</h3>
                    <p class="stat-value"><?php echo count($pending_activities); ?></p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📚</div>
                <div class="stat-info">
                    <h3>Enrolled Subjects</h3>
                    <p class="stat-value"><?php echo count($enrolled_subjects); ?></p>
                </div>
            </div>
        </div>

        <!-- Main Dashboard Grid -->
        <div class="dashboard-grid">
            <!-- Pending Activities Section -->
            <div class="dashboard-section pending-activities">
                <div class="section-header">
                    <h2>📝 Pending Activities</h2>
                    <a href="activities.php" class="view-all-link">View All →</a>
                </div>
                <div class="activities-list">
                    <?php if (!empty($pending_activities)): ?>
                        <?php foreach (array_slice($pending_activities, 0, 5) as $activity): ?>
                            <div class="activity-item">
                                <div class="activity-info">
                                    <h4><?php echo htmlspecialchars($activity['title']); ?></h4>
                                    <p class="subject-tag"><?php echo htmlspecialchars($activity['subject_name']); ?></p>
                                    <p class="due-date">
                                        Due: <?php echo date('M d, Y', strtotime($activity['due_date'])); ?>
                                    </p>
                                </div>
                                <a href="take_activity.php?id=<?php echo $activity['id']; ?>" class="btn btn-small">
                                    Start Activity
                                </a>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="empty-message">🎉 No pending activities! Great job!</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Recent Scores Section -->
            <div class="dashboard-section">
                <div class="section-header">
                    <h2>🏆 Recent Scores</h2>
                    <a href="grades.php" class="view-all-link">View All →</a>
                </div>
                <div class="scores-list">
                    <?php if (!empty($recent_scores)): ?>
                        <?php foreach ($recent_scores as $score): ?>
                            <div class="score-item">
                                <div class="score-info">
                                    <h4><?php echo htmlspecialchars($score['title']); ?></h4>
                                    <p class="subject-tag"><?php echo htmlspecialchars($score['subject_name']); ?></p>
                                    <p class="submitted-date">
                                        Submitted: <?php echo date('M d, Y', strtotime($score['submitted_at'])); ?>
                                    </p>
                                </div>
                                <div class="score-badge">
                                    <?php if ($score['status'] == 'graded'): ?>
                                        <span class="score-value <?php echo $score['score'] >= 75 ? 'passing' : 'failing'; ?>">
                                            <?php echo number_format($score['score'], 2); ?>%
                                        </span>
                                    <?php else: ?>
                                        <span class="score-value pending">Pending</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="empty-message">📋 No submissions yet. Start working on activities!</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Enrolled Subjects Section -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📚 My Subjects</h2>
            </div>
            <div class="subjects-grid">
                <?php if (!empty($enrolled_subjects)): ?>
                    <?php foreach ($enrolled_subjects as $subject): ?>
                        <div class="subject-card">
                            <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-footer">
                                <span class="instructor">
                                    👤 <?php echo htmlspecialchars($subject['instructor_name']); ?>
                                </span>
                                <a href="activities.php?subject=<?php echo $subject['id']; ?>" class="btn btn-small">
                                    View Activities
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?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>
    </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;
                        
                        // Mark notifications as read
                        fetch('mark_notifications_read.php');
                    }
                })
                .catch(error => {
                    content.innerHTML = '<p class="error-message">Failed to load notifications.</p>';
                });
        }

        // Close notifications panel when clicking outside
        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');
            }
        });

        // Initialize tutorial for new students
        window.addEventListener('load', function() {
            // Wait for tutorial steps to load
            setTimeout(function() {
                if (typeof Tutorial !== 'undefined' && typeof studentTutorialSteps !== 'undefined') {
                    const tutorial = new Tutorial(studentTutorialSteps, 'student');
                    tutorial.init();
                }
            }, 500);
        });
    </script>
</body>
</html>
