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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Fetch teachers from database
$teachers = [];
try {
    $stmt = $pdo->prepare("SELECT id, first_name, last_name, employee_id FROM teachers WHERE status = 'active' ORDER BY first_name, last_name");
    $stmt->execute();
    $teachers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching teachers: " . $e->getMessage());
}

// Fetch students from database, organized by class
$studentsByClass = [];
try {
    // First get class information for mapping
    $classStmt = $pdo->prepare("SELECT id, name FROM classes");
    $classStmt->execute();
    $classes = $classStmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Then get students organized by class
    $stmt = $pdo->prepare("
        SELECT s.id, s.first_name, s.last_name, s.student_id, s.class_id, c.name as class_name 
        FROM students s 
        LEFT JOIN classes c ON s.class_id = c.id 
        WHERE s.status = 'active' 
        ORDER BY s.class_id, s.first_name, s.last_name
    ");
    $stmt->execute();
    $allStudents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Organize students by class (no limit now)
    foreach ($allStudents as $student) {
        $classId = $student['class_id'];
        $className = $student['class_name'] ?? 'Class ' . $classId;
        
        if (!isset($studentsByClass[$className])) {
            $studentsByClass[$className] = [];
        }
        
        // Add all students (no limit)
        $studentsByClass[$className][] = $student;
    }
} catch (PDOException $e) {
    error_log("Error fetching students: " . $e->getMessage());
}

// Combine participants
$participants = array_merge($teachers, []);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ভার্চুয়াল ক্লাসরুম - অনলাইন শিক্ষা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .class-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .class-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .class-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
        }
        
        .class-body {
            padding: 20px;
        }
        
        .class-footer {
            background-color: #f8f9fa;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-upcoming {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-live {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-ended {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        /* Google Meet-like styles */
        .meet-container {
            height: calc(100vh - 100px);
            display: flex;
            flex-direction: column;
        }
        
        .meet-header {
            background: #ffffff;
            border-bottom: 1px solid #e0e0e0;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .meet-main {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        
        .video-section {
            flex: 3;
            display: flex;
            flex-direction: column;
            padding: 15px;
            background: #f5f5f5;
            overflow-y: auto;
        }
        
        .participants-section {
            flex: 1;
            min-width: 250px;
            background: #ffffff;
            border-left: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }
        
        .video-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr); /* Exactly 5 boxes per row */
            gap: 15px; /* Space between boxes */
            row-gap: 25px; /* Additional space between rows */
            flex: 1;
            overflow-y: auto;
        }
        
        .video-tile {
            background: #000;
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            aspect-ratio: 1/1; /* Square aspect ratio */
            transition: transform 0.3s ease;
            min-height: 150px; /* Minimum height to ensure proper sizing */
            display: none; /* Hidden by default, shown only when participant joins */
        }
        
        .video-tile.active {
            display: block; /* Show only when participant is active */
        }
        
        .video-tile.zoomed {
            transform: scale(1.1);
            z-index: 10;
            box-shadow: 0 0 20px rgba(0,0,0,0.5);
        }
        
        .video-tile.fullscreen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            z-index: 1000;
            transform: none;
            border-radius: 0;
            box-shadow: none;
        }
        
        .video-tile video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .video-label {
            position: absolute;
            bottom: 10px;
            left: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
        }
        
        .video-controls {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 5px;
        }
        
        .video-control-btn {
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border: none;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .video-tile:hover .video-control-btn {
            opacity: 1;
        }
        
        .participant-list {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
        }
        
        .participant-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 5px;
        }
        
        .participant-item:hover {
            background: #f5f5f5;
        }
        
        .participant-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #667eea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .participant-name {
            flex: 1;
            font-size: 0.9rem;
        }
        
        .participant-status {
            font-size: 0.8rem;
            color: #666;
        }
        
        .participant-item.online {
            background-color: #e9f7ef;
            border-left: 3px solid #28a745;
        }
        
        .controls-section {
            background: #ffffff;
            border-top: 1px solid #e0e0e0;
            padding: 15px;
            display: flex;
            justify-content: center;
        }
        
        .control-button {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #f5f5f5;
            border: none;
            margin: 0 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .control-button:hover {
            background: #e0e0e0;
        }
        
        .control-button.danger {
            background: #dc3545;
            color: white;
        }
        
        .control-button.danger:hover {
            background: #bd2130;
        }
        
        .control-button.active {
            background: #007bff;
            color: white;
        }
        
        .control-button.active:hover {
            background: #0069d9;
        }
        
        .chat-section {
            background: #ffffff;
            border-top: 1px solid #e0e0e0;
            padding: 15px;
            display: none;
        }
        
        .chat-messages {
            height: 200px;
            overflow-y: auto;
            margin-bottom: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .chat-input {
            display: flex;
        }
        
        .chat-input input {
            flex: 1;
            margin-right: 10px;
        }
        
        .video-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: white;
            text-align: center;
        }
        
        .video-placeholder i {
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .video-placeholder h4 {
            margin-bottom: 5px;
            font-size: 0.9rem;
        }
        
        .start-class-btn {
            margin-top: 20px;
        }
        
        .notification-banner {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 15px;
            font-size: 0.9rem;
        }
        
        .participant-item.calling {
            background-color: #e9f7ef;
            border-left: 3px solid #28a745;
        }
        
        .chat-message img {
            cursor: pointer;
            transition: transform 0.2s;
        }
        
        .chat-message img:hover {
            transform: scale(1.05);
        }
        
        .input-group .btn {
            padding: 0.375rem 0.75rem;
        }
        
        /* Class section styles */
        .class-section {
            margin-bottom: 20px;
        }
        
        .class-section-header {
            background: #e9ecef;
            padding: 8px 15px;
            border-radius: 5px;
            margin-bottom: 10px;
            font-weight: bold;
        }
        
        /* Responsive adjustments */
        @media (max-width: 1400px) {
            .video-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        
        @media (max-width: 1100px) {
            .video-grid {
                grid-template-columns: repeat(3, 1fr);
                row-gap: 20px; /* Adjust row gap for smaller screens */
            }
        }
        
        @media (max-width: 992px) {
            .meet-main {
                flex-direction: column;
            }
            
            .participants-section {
                border-left: none;
                border-top: 1px solid #e0e0e0;
                min-width: 100%;
            }
            
            .video-grid {
                grid-template-columns: repeat(3, 1fr);
                row-gap: 20px;
            }
        }
        
        @media (max-width: 768px) {
            .video-grid {
                grid-template-columns: repeat(2, 1fr);
                row-gap: 15px;
            }
        }
        
        @media (max-width: 576px) {
            .video-grid {
                grid-template-columns: repeat(1, 1fr);
                row-gap: 15px;
            }
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Image Modal -->
    <div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Image Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img id="modalImage" src="" alt="Full size image" class="img-fluid">
                </div>
            </div>
        </div>
    </div>
    
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/virtual_classroom.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-video me-2"></i>
                    ভার্চুয়াল ক্লাসরুম
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / ভার্চুয়াল ক্লাসরুম
                </p>
            </div>
            
            <!-- Meet Container -->
            <div class="meet-container">
                <!-- Meet Header -->
                <div class="meet-header">
                    <div>
                        <h5 class="mb-0">ভার্চুয়াল ক্লাসরুম</h5>
                        <small class="text-muted">গণিত - বীজগণিত</small>
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-secondary" id="toggleParticipants">
                            <i class="fas fa-users me-1"></i> অংশগ্রহণকারী
                        </button>
                        <button class="btn btn-sm btn-outline-secondary ms-2" id="toggleChat">
                            <i class="fas fa-comment me-1"></i> চ্যাট
                        </button>
                    </div>
                </div>
                
                <!-- Meet Main Content -->
                <div class="meet-main">
                    <!-- Video Section -->
                    <div class="video-section">
                        <div class="video-grid">
                            <!-- Teacher/Host Video Tile -->
                            <div class="video-tile active" data-participant="host" id="hostTile">
                                <video id="localVideo" autoplay muted></video>
                                <div class="video-placeholder" id="videoPlaceholder">
                                    <i class="fas fa-user"></i>
                                    <h4>আপনি (হোস্ট)</h4>
                                </div>
                                <div class="video-label">আপনি (হোস্ট)</div>
                                <div class="video-controls">
                                    <button class="video-control-btn fullscreen-btn" title="Fullscreen">
                                        <i class="fas fa-expand"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <!-- Teacher Videos from Database (hidden by default, shown when they join) -->
                            <?php foreach ($teachers as $index => $teacher): ?>
                            <div class="video-tile" data-participant="teacher-<?php echo $teacher['id']; ?>" id="teacherTile<?php echo $teacher['id']; ?>">
                                <video id="teacherVideo<?php echo $index; ?>" autoplay></video>
                                <div class="video-placeholder">
                                    <i class="fas fa-chalkboard-teacher"></i>
                                    <h4><?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?></h4>
                                </div>
                                <div class="video-label"><?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?></div>
                                <div class="video-controls">
                                    <button class="video-control-btn fullscreen-btn" title="Fullscreen">
                                        <i class="fas fa-expand"></i>
                                    </button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            
                            <!-- Student Videos organized by class (hidden by default, shown when they join) -->
                            <?php foreach ($studentsByClass as $className => $students): ?>
                                <?php foreach ($students as $index => $student): ?>
                                <div class="video-tile" data-participant="student-<?php echo $student['id']; ?>" id="studentTile<?php echo $student['id']; ?>">
                                    <video id="studentVideo<?php echo $student['id']; ?>" autoplay></video>
                                    <div class="video-placeholder">
                                        <i class="fas fa-user-graduate"></i>
                                        <h4><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></h4>
                                    </div>
                                    <div class="video-label"><?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?></div>
                                    <div class="video-controls">
                                        <button class="video-control-btn fullscreen-btn" title="Fullscreen">
                                            <i class="fas fa-expand"></i>
                                        </button>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Notification Banner -->
                        <div class="notification-banner" id="notificationBanner" style="display: none;">
                            <i class="fas fa-info-circle me-2"></i>
                            <span id="notificationText"></span>
                        </div>
                        
                        <!-- Start Class Button -->
                        <div class="text-center mt-3">
                            <button class="btn btn-success btn-lg start-class-btn" id="startClassBtn">
                                <i class="fas fa-play-circle me-2"></i>
                                স্টার্ট ক্লাস
                            </button>
                        </div>
                    </div>
                    
                    <!-- Participants Section -->
                    <div class="participants-section">
                        <div class="p-3 border-bottom">
                            <h6 class="mb-0"><i class="fas fa-users me-2"></i> অংশগ্রহণকারী</h6>
                        </div>
                        <div class="participant-list">
                            <div class="participant-item online">
                                <div class="participant-avatar">আ</div>
                                <div class="participant-name">আপনি (হোস্ট)</div>
                                <div class="participant-status"><i class="fas fa-microphone"></i></div>
                            </div>
                            
                            <!-- Teachers Section -->
                            <div class="class-section">
                                <div class="class-section-header">
                                    <i class="fas fa-chalkboard-teacher me-2"></i> শিক্ষকগণ
                                </div>
                                <?php foreach ($teachers as $teacher): ?>
                                <div class="participant-item" id="teacherParticipant<?php echo $teacher['id']; ?>">
                                    <div class="participant-avatar">
                                        <?php 
                                        $name = $teacher['first_name'] . ' ' . $teacher['last_name'];
                                        echo mb_substr($name, 0, 1, 'UTF-8');
                                        ?>
                                    </div>
                                    <div class="participant-name">
                                        <?php echo htmlspecialchars($teacher['first_name'] . ' ' . $teacher['last_name']); ?>
                                    </div>
                                    <div class="participant-status">
                                        <i class="fas fa-microphone-slash"></i>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- Students Section organized by class -->
                            <?php foreach ($studentsByClass as $className => $students): ?>
                            <div class="class-section">
                                <div class="class-section-header">
                                    <i class="fas fa-users me-2"></i> <?php echo htmlspecialchars($className); ?>
                                </div>
                                <?php foreach ($students as $student): ?>
                                <div class="participant-item" id="studentParticipant<?php echo $student['id']; ?>">
                                    <div class="participant-avatar">
                                        <?php 
                                        $name = $student['first_name'] . ' ' . $student['last_name'];
                                        echo mb_substr($name, 0, 1, 'UTF-8');
                                        ?>
                                    </div>
                                    <div class="participant-name">
                                        <?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?>
                                    </div>
                                    <div class="participant-status">
                                        <i class="fas fa-microphone-slash"></i>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Controls Section -->
                <div class="controls-section">
                    <button class="control-button" id="toggleMic" title="মাইক্রোফোন টগল করুন">
                        <i class="fas fa-microphone"></i>
                    </button>
                    <button class="control-button" id="toggleCam" title="ক্যামেরা টগল করুন">
                        <i class="fas fa-video"></i>
                    </button>
                    <button class="control-button" id="screenShareBtn" title="স্ক্রিন শেয়ার করুন">
                        <i class="fas fa-share-alt"></i>
                    </button>
                    <button class="control-button danger" id="endClass" title="ক্লাস শেষ করুন">
                        <i class="fas fa-phone-alt"></i>
                    </button>
                </div>
                
                <!-- Chat Section -->
                <div class="chat-section" id="chatSection">
                    <div class="chat-messages" id="chatMessages">
                        <div class="chat-message">
                            <strong>সিস্টেম:</strong> ক্লাস শুরু হয়েছে। ছাত্র-ছাত্রীদের যোগ দিতে বলুন।
                        </div>
                        <div class="chat-message">
                            <strong>রহিম উদ্দিন:</strong> স্যার, আপনি শোনা পাচ্ছেন?
                        </div>
                        <div class="chat-message">
                            <strong>আপনি:</strong> হ্যাঁ, আমি শুনতে পাচ্ছি। কোন প্রশ্ন আছে?
                        </div>
                    </div>
                    <div class="chat-input">
                        <input type="text" class="form-control" id="messageInput" placeholder="মেসেজ টাইপ করুন...">
                        <button class="btn btn-primary" id="sendMessageBtn">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Add click event for images to open in modal
        document.addEventListener('click', function(e) {
            if (e.target.tagName === 'IMG' && e.target.closest('.chat-message')) {
                const modalImage = document.getElementById('modalImage');
                modalImage.src = e.target.src;
                const imageModal = new bootstrap.Modal(document.getElementById('imageModal'));
                imageModal.show();
            }
        });
        
        // WebRTC functionality for virtual classroom
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Virtual classroom JavaScript loaded');
            
            // Elements
            const startClassBtn = document.getElementById('startClassBtn');
            const localVideo = document.getElementById('localVideo');
            const videoPlaceholder = document.getElementById('videoPlaceholder');
            const toggleMic = document.getElementById('toggleMic');
            const toggleCam = document.getElementById('toggleCam');
            const screenShareBtn = document.getElementById('screenShareBtn');
            const endClass = document.getElementById('endClass');
            const notificationBanner = document.getElementById('notificationBanner');
            const notificationText = document.getElementById('notificationText');
            const toggleParticipants = document.getElementById('toggleParticipants');
            const toggleChat = document.getElementById('toggleChat');
            const chatSection = document.getElementById('chatSection');
            const messageInput = document.getElementById('messageInput');
            const sendMessageBtn = document.getElementById('sendMessageBtn');
            const chatMessages = document.getElementById('chatMessages');
            
            // Video tiles for zoom functionality
            const videoTiles = document.querySelectorAll('.video-tile');
            
            // Add click event to each video tile for zooming
            videoTiles.forEach(tile => {
                tile.addEventListener('click', function() {
                    // Remove zoom from all tiles
                    videoTiles.forEach(t => t.classList.remove('zoomed'));
                    
                    // Toggle zoom on clicked tile
                    this.classList.toggle('zoomed');
                });
            });
            
            // Add fullscreen functionality to fullscreen buttons
            document.querySelectorAll('.fullscreen-btn').forEach(button => {
                button.addEventListener('click', function(e) {
                    e.stopPropagation(); // Prevent zoom when clicking fullscreen button
                    const tile = this.closest('.video-tile');
                    toggleFullscreen(tile);
                });
            });
            
            // State variables
            let localStream = null;
            let micEnabled = true;
            let camEnabled = true;
            let isScreenSharing = false;
            let screenStream = null;
            let peerConnections = {}; // Store peer connections for each participant
            let isClassStarted = false;
            let fullscreenTile = null; // Track which tile is currently fullscreen
            
            // Show notification
            function showNotification(text) {
                notificationText.textContent = text;
                notificationBanner.style.display = 'block';
                setTimeout(() => {
                    notificationBanner.style.display = 'none';
                }, 5000);
            }
            
            // Toggle participants section
            toggleParticipants.addEventListener('click', function() {
                const participantsSection = document.querySelector('.participants-section');
                participantsSection.style.display = participantsSection.style.display === 'none' ? 'flex' : 'none';
            });
            
            // Toggle chat section
            toggleChat.addEventListener('click', function() {
                chatSection.style.display = chatSection.style.display === 'block' ? 'none' : 'block';
            });
            
            // Start class button event
            startClassBtn.addEventListener('click', async function() {
                try {
                    // Request access to camera and microphone
                    localStream = await navigator.mediaDevices.getUserMedia({ 
                        video: { facingMode: 'user' }, 
                        audio: true 
                    });
                    
                    // Show video feed
                    localVideo.srcObject = localStream;
                    localVideo.style.display = 'block';
                    videoPlaceholder.style.display = 'none';
                    
                    // Hide start button
                    startClassBtn.style.display = 'none';
                    
                    // Mark class as started
                    isClassStarted = true;
                    
                    // Update button states
                    updateButtonStates();
                    
                    showNotification('ক্লাস শুরু হয়েছে! ছাত্র-ছাত্রীদের যোগ দিতে বলুন।');
                    
                    // Simulate participants joining (in a real implementation, this would be WebRTC signaling)
                    simulateParticipantsJoining();
                } catch (error) {
                    console.error('Error accessing media devices:', error);
                    showNotification('ক্যামেরা বা মাইক্রোফোন অ্যাক্সেস করতে সমস্যা হয়েছে। অনুগ্রহ করে আপনার ডিভাইসের অনুমতি পরীক্ষা করুন।');
                }
            });
            
            // Simulate participants joining (in a real implementation, this would be WebRTC signaling)
            function simulateParticipantsJoining() {
                // Show host tile (always visible)
                document.getElementById('hostTile').classList.add('active');
                document.querySelector('.participant-item.online').classList.add('online');
                
                // Simulate some teachers joining after a delay
                setTimeout(() => {
                    // Simulate first teacher joining
                    const firstTeacherTile = document.querySelector('[data-participant^="teacher-"]');
                    if (firstTeacherTile) {
                        firstTeacherTile.classList.add('active');
                        const teacherId = firstTeacherTile.dataset.participant.split('-')[1];
                        const teacherParticipant = document.getElementById('teacherParticipant' + teacherId);
                        if (teacherParticipant) {
                            teacherParticipant.classList.add('online');
                        }
                        showNotification('জামাল স্যার ক্লাসে যোগ দিয়েছেন');
                    }
                }, 2000);
                
                // Simulate some students joining after a delay
                setTimeout(() => {
                    // Simulate first student joining
                    const firstStudentTile = document.querySelector('[data-participant^="student-"]');
                    if (firstStudentTile) {
                        firstStudentTile.classList.add('active');
                        const studentId = firstStudentTile.dataset.participant.split('-')[1];
                        const studentParticipant = document.getElementById('studentParticipant' + studentId);
                        if (studentParticipant) {
                            studentParticipant.classList.add('online');
                        }
                        showNotification('রহিম উদ্দিন ক্লাসে যোগ দিয়েছেন');
                    }
                }, 4000);
                
                // Simulate more participants joining
                setTimeout(() => {
                    // Show a few more participants
                    const teacherTiles = document.querySelectorAll('[data-participant^="teacher-"]');
                    const studentTiles = document.querySelectorAll('[data-participant^="student-"]');
                    
                    // Show up to 3 teachers
                    for (let i = 0; i < Math.min(3, teacherTiles.length); i++) {
                        teacherTiles[i].classList.add('active');
                        const teacherId = teacherTiles[i].dataset.participant.split('-')[1];
                        const teacherParticipant = document.getElementById('teacherParticipant' + teacherId);
                        if (teacherParticipant) {
                            teacherParticipant.classList.add('online');
                        }
                    }
                    
                    // Show up to 5 students
                    for (let i = 0; i < Math.min(5, studentTiles.length); i++) {
                        studentTiles[i].classList.add('active');
                        const studentId = studentTiles[i].dataset.participant.split('-')[1];
                        const studentParticipant = document.getElementById('studentParticipant' + studentId);
                        if (studentParticipant) {
                            studentParticipant.classList.add('online');
                        }
                    }
                    
                    showNotification('আরও অংশগ্রহণকারী ক্লাসে যোগ দিয়েছেন');
                }, 6000);
            }
            
            // Toggle microphone
            toggleMic.addEventListener('click', function() {
                if (localStream) {
                    micEnabled = !micEnabled;
                    localStream.getAudioTracks().forEach(track => {
                        track.enabled = micEnabled;
                    });
                    updateButtonStates();
                    showNotification(micEnabled ? 'মাইক্রোফোন চালু হয়েছে' : 'মাইক্রোফোন বন্ধ হয়েছে');
                }
            });
            
            // Toggle camera
            toggleCam.addEventListener('click', function() {
                if (localStream) {
                    camEnabled = !camEnabled;
                    localStream.getVideoTracks().forEach(track => {
                        track.enabled = camEnabled;
                    });
                    updateButtonStates();
                    showNotification(camEnabled ? 'ক্যামেরা চালু হয়েছে' : 'ক্যামেরা বন্ধ হয়েছে');
                }
            });
            
            // Screen share
            screenShareBtn.addEventListener('click', async function() {
                if (isScreenSharing) {
                    // Stop screen sharing
                    stopScreenShare();
                } else {
                    // Start screen sharing
                    try {
                        screenStream = await navigator.mediaDevices.getDisplayMedia({ 
                            video: true,
                            audio: true 
                        });
                        
                        // Replace camera stream with screen stream
                        if (localStream) {
                            localStream.getTracks().forEach(track => track.stop());
                        }
                        
                        localStream = screenStream;
                        localVideo.srcObject = screenStream;
                        
                        // Update UI
                        isScreenSharing = true;
                        screenShareBtn.classList.add('active');
                        showNotification('স্ক্রিন শেয়ার শুরু হয়েছে');
                        
                        // Stop screen sharing when user stops it manually
                        screenStream.getVideoTracks()[0].onended = function() {
                            stopScreenShare();
                        };
                    } catch (error) {
                        console.error('Error sharing screen:', error);
                        showNotification('স্ক্রিন শেয়ার করতে সমস্যা হয়েছে। অনুগ্রহ করে আপনার ডিভাইসের অনুমতি পরীক্ষা করুন।');
                    }
                }
            });
            
            // End class
            endClass.addEventListener('click', function() {
                if (confirm('আপনি কি নিশ্চিত যে ক্লাস শেষ করতে চান?')) {
                    endClassSession();
                }
            });
            
            // Send message
            sendMessageBtn.addEventListener('click', function() {
                sendMessage();
            });
            
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });
            
            // Toggle fullscreen for a video tile
            function toggleFullscreen(tile) {
                if (tile.classList.contains('fullscreen')) {
                    // Exit fullscreen
                    tile.classList.remove('fullscreen');
                    document.body.style.overflow = ''; // Restore scroll
                    fullscreenTile = null;
                } else {
                    // Enter fullscreen
                    // Exit fullscreen from any other tile first
                    if (fullscreenTile) {
                        fullscreenTile.classList.remove('fullscreen');
                    }
                    
                    tile.classList.add('fullscreen');
                    document.body.style.overflow = 'hidden'; // Prevent scrolling
                    fullscreenTile = tile;
                }
            }
            
            // Stop screen sharing function
            function stopScreenShare() {
                if (screenStream) {
                    screenStream.getTracks().forEach(track => track.stop());
                    screenStream = null;
                }
                
                // Restore camera stream
                if (localStream) {
                    localStream.getTracks().forEach(track => track.stop());
                }
                
                // Get camera stream again
                navigator.mediaDevices.getUserMedia({ 
                    video: { facingMode: 'user' }, 
                    audio: true 
                }).then(stream => {
                    localStream = stream;
                    localVideo.srcObject = stream;
                });
                
                // Update UI
                isScreenSharing = false;
                screenShareBtn.classList.remove('active');
                showNotification('স্ক্রিন শেয়ার বন্ধ হয়েছে');
            }
            
            // End class session function
            function endClassSession() {
                if (localStream) {
                    localStream.getTracks().forEach(track => track.stop());
                    localStream = null;
                }
                
                // Stop screen sharing if active
                if (screenStream) {
                    screenStream.getTracks().forEach(track => track.stop());
                    screenStream = null;
                }
                
                // Reset UI
                localVideo.style.display = 'none';
                videoPlaceholder.style.display = 'flex';
                startClassBtn.style.display = 'inline-block';
                screenShareBtn.classList.remove('active');
                
                // Hide all participant tiles except host
                document.querySelectorAll('.video-tile').forEach(tile => {
                    if (!tile.dataset.participant || tile.dataset.participant !== 'host') {
                        tile.classList.remove('active');
                    }
                    // Exit fullscreen if any tile is fullscreen
                    if (tile.classList.contains('fullscreen')) {
                        tile.classList.remove('fullscreen');
                        document.body.style.overflow = '';
                    }
                });
                
                // Remove online status from all participants except host
                document.querySelectorAll('.participant-item').forEach(item => {
                    if (!item.classList.contains('online') || item.querySelector('.participant-name').textContent.includes('হোস্ট')) {
                        return;
                    }
                    item.classList.remove('online');
                });
                
                showNotification('ক্লাস শেষ হয়েছে');
            }
            
            // Send message function
            function sendMessage() {
                const message = messageInput.value.trim();
                if (message) {
                    const chatMessage = document.createElement('div');
                    chatMessage.className = 'chat-message';
                    chatMessage.innerHTML = `<strong>আপনি:</strong> ${message}`;
                    chatMessages.appendChild(chatMessage);
                    messageInput.value = '';
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            }
            
            // Update button states
            function updateButtonStates() {
                // Update mic button
                const micIcon = toggleMic.querySelector('i');
                if (micEnabled) {
                    micIcon.className = 'fas fa-microphone';
                    toggleMic.classList.add('active');
                } else {
                    micIcon.className = 'fas fa-microphone-slash';
                    toggleMic.classList.remove('active');
                }
                
                // Update camera button
                const camIcon = toggleCam.querySelector('i');
                if (camEnabled) {
                    camIcon.className = 'fas fa-video';
                    toggleCam.classList.add('active');
                } else {
                    camIcon.className = 'fas fa-video-slash';
                    toggleCam.classList.remove('active');
                }
            }
            
            // Handle escape key to exit fullscreen
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && fullscreenTile) {
                    fullscreenTile.classList.remove('fullscreen');
                    document.body.style.overflow = '';
                    fullscreenTile = null;
                }
            });
        });
    </script>
</body>
</html>