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

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

$instructor_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", $instructor_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
$stmt->close();

// Get filter and sort
$subject_filter = isset($_GET['subject']) ? intval($_GET['subject']) : null;
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'name';

// Get instructor's subjects for filter
$subjects_query = "SELECT * FROM subjects WHERE instructor_id = ?";
$stmt = $conn->prepare($subjects_query);
$stmt->bind_param("i", $instructor_id);
$stmt->execute();
$subjects_result = $stmt->get_result();
$subjects = [];
while ($row = $subjects_result->fetch_assoc()) {
    $subjects[] = $row;
}
$stmt->close();

// Get all students enrolled in instructor's subjects
$students_query = "SELECT DISTINCT u.*, u.code_points,
                   GROUP_CONCAT(s.subject_name SEPARATOR ', ') as enrolled_subjects
                   FROM users u
                   JOIN enrollments e ON u.id = e.student_id
                   JOIN subjects s ON e.subject_id = s.id
                   WHERE s.instructor_id = ?";

if ($subject_filter) {
    $students_query .= " AND s.id = ?";
}

// Add ORDER BY based on sort parameter
$students_query .= " GROUP BY u.id ORDER BY ";
if ($sort_by === 'points_high') {
    $students_query .= "u.code_points DESC, u.full_name ASC";
} elseif ($sort_by === 'points_low') {
    $students_query .= "u.code_points ASC, u.full_name ASC";
} else {
    $students_query .= "u.year_level, u.section, u.full_name";
}

if ($subject_filter) {
    $stmt = $conn->prepare($students_query);
    $stmt->bind_param("ii", $instructor_id, $subject_filter);
} else {
    $stmt = $conn->prepare($students_query);
    $stmt->bind_param("i", $instructor_id);
}

$stmt->execute();
$students_result = $stmt->get_result();
$students = [];
while ($row = $students_result->fetch_assoc()) {
    $students[] = $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", $instructor_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 Students - 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>
</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">My Subjects</a>
                <a href="students.php" class="nav-link active">My Students</a>
                <a href="activities.php" class="nav-link">Activities</a>
                <a href="submissions.php" class="nav-link">Submissions</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>

    <div class="main-content">
        <div class="dashboard-header">
            <h1>👥 My Students</h1>
            <p>View all students enrolled in your subjects</p>
        </div>

        <!-- Filter -->
        <div class="filter-section" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <div class="filter-group">
                <label>📚 Filter by Subject</label>
                <select onchange="updateFilters('subject', this.value)" style="width: 100%;">
                    <option value="">All Subjects</option>
                    <?php foreach ($subjects as $subject): ?>
                        <option value="<?php echo $subject['id']; ?>" <?php echo $subject_filter == $subject['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($subject['subject_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="filter-group">
                <label>🏆 Sort by Code Points</label>
                <select onchange="updateFilters('sort', this.value)" style="width: 100%;">
                    <option value="name" <?php echo $sort_by === 'name' ? 'selected' : ''; ?>>Name (Default)</option>
                    <option value="points_high" <?php echo $sort_by === 'points_high' ? 'selected' : ''; ?>>Highest Points First</option>
                    <option value="points_low" <?php echo $sort_by === 'points_low' ? 'selected' : ''; ?>>Lowest Points First</option>
                </select>
            </div>
        </div>

        <script>
        function updateFilters(type, value) {
            const urlParams = new URLSearchParams(window.location.search);

            if (type === 'subject') {
                if (value) {
                    urlParams.set('subject', value);
                } else {
                    urlParams.delete('subject');
                }
            } else if (type === 'sort') {
                if (value && value !== 'name') {
                    urlParams.set('sort', value);
                } else {
                    urlParams.delete('sort');
                }
            }

            const newUrl = 'students.php' + (urlParams.toString() ? '?' + urlParams.toString() : '');
            window.location.href = newUrl;
        }
        </script>

        <!-- Students Grid -->
        <div class="dashboard-section full-width">
            <div class="section-header">
                <h2>📋 Students List (<?php echo count($students); ?> students)</h2>
            </div>
            <?php if (!empty($students)): ?>
                <?php
                // Sort students by code points for ranking (only when sorting by points)
                $ranked_students = $students;
                if ($sort_by === 'points_high' || $sort_by === 'points_low') {
                    usort($ranked_students, function($a, $b) {
                        return ($b['code_points'] ?? 0) - ($a['code_points'] ?? 0);
                    });
                }
                ?>
                <div class="students-grid">
                    <?php
                    $rank = 0;
                    $prev_points = -1;
                    $actual_position = 0;

                    foreach ($students as $index => $student):
                        $actual_position++;
                        $student_points = $student['code_points'] ?? 0;

                        // Calculate rank (handle ties)
                        if ($student_points != $prev_points) {
                            $rank = $actual_position;
                        }
                        $prev_points = $student_points;

                        // Determine rank badge
                        $rank_badge = '';
                        $rank_color = '';
                        if ($sort_by === 'points_high' && $student_points > 0) {
                            if ($rank === 1) {
                                $rank_badge = '🥇';
                                $rank_color = '#FFD700';
                            } elseif ($rank === 2) {
                                $rank_badge = '🥈';
                                $rank_color = '#C0C0C0';
                            } elseif ($rank === 3) {
                                $rank_badge = '🥉';
                                $rank_color = '#CD7F32';
                            }
                        }
                    ?>
                        <div class="student-card" style="position: relative; <?php echo $rank <= 3 && $sort_by === 'points_high' && $student_points > 0 ? 'border: 2px solid ' . $rank_color . '; box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);' : ''; ?>">
                            <?php if ($rank_badge): ?>
                                <div style="position: absolute; top: -10px; right: -10px; font-size: 3em; z-index: 10; filter: drop-shadow(0 4px 8px rgba(0,0,0,0.2));">
                                    <?php echo $rank_badge; ?>
                                </div>
                            <?php endif; ?>

                            <div class="student-avatar-container">
                                <?php if (isset($student['profile_picture']) && $student['profile_picture']): ?>
                                    <img src="../<?php echo htmlspecialchars($student['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($student['full_name'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="student-info">
                                <h3><?php echo htmlspecialchars($student['full_name']); ?></h3>
                                <p class="student-id">🆔 <?php echo htmlspecialchars($student['id_number'] ?? 'N/A'); ?></p>
                                <p class="student-detail">📧 <?php echo htmlspecialchars($student['email']); ?></p>
                                <p class="student-detail">👤 <?php echo htmlspecialchars($student['username']); ?></p>
                                <p class="student-detail">📚 <?php echo htmlspecialchars($student['year_level'] ?? 'N/A'); ?> - Section <?php echo htmlspecialchars($student['section'] ?? 'N/A'); ?></p>

                                <div style="margin: 12px 0; padding: 15px; background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%); border-radius: 12px; border-left: 4px solid #667eea; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);">
                                    <div style="display: flex; justify-content: space-between; align-items: center;">
                                        <strong style="color: #667eea; font-size: 1.1em;">🏆 Code Points</strong>
                                        <span style="font-size: 1.5em; font-weight: bold; color: #667eea;"><?php echo $student_points; ?></span>
                                    </div>
                                    <?php if ($sort_by === 'points_high' && $student_points > 0): ?>
                                        <div style="margin-top: 8px; font-size: 0.9em; color: #666;">
                                            Rank: #<?php echo $rank; ?> of <?php echo count($students); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <p class="student-subjects">
                                    <strong>Enrolled in:</strong><br>
                                    <small><?php echo htmlspecialchars($student['enrolled_subjects']); ?></small>
                                </p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <p class="empty-message">👥 No students found. Students need to enroll in your subjects first.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- 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>

    <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>
                                </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>
        .students-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 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: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid var(--primary-moss);
        }

        .student-info {
            width: 100%;
        }

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

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

        .student-detail {
            color: var(--text-secondary);
            margin: 5px 0;
            font-size: 0.9em;
        }

        .student-subjects {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            color: var(--text-secondary);
            font-size: 0.85em;
        }

        .student-subjects strong {
            color: var(--text-primary);
        }
    </style>
</body>
</html>
