<?php
if (session_status() == PHP_SESSION_NONE) { session_start(); }
@include_once '../db_connect.php'; 
@include_once '../theme_lang_loader.php';

// 1. قراءة المتغيرات من الرابط أولاً (هذا هو السطر الذي كان متأخراً)
$sid = $_GET['sid'] ?? '';
$tid = $_GET['tid'] ?? '';
preg_match('/\d+/', $tid, $matches);
$clean_tid = $matches[0] ?? '';

// 2. البحث عن اسم الطالب الحقيقي من جدول students بناءً على الـ sid
$student_real_name = "طالب";
if (!empty($sid) && isset($conn)) {
    $s_query = $conn->query("SELECT student_name FROM students WHERE student_id = '".$conn->real_escape_string($sid)."' LIMIT 1");
    if ($s_query && $s_query->num_rows > 0) {
        $s_row = $s_query->fetch_assoc();
        $student_real_name = !empty($s_row['student_name']) ? $s_row['student_name'] : "طالب";
    }
}

// 3. جلب بيانات المدرس
$teacher_name = "الأستاذ";
$subject_name = "حصة مباشرة تفاعلية";

if (!empty($clean_tid) && isset($conn)) {
    $t_query = $conn->query("SELECT display_name, specialization FROM teachers WHERE teacher_name LIKE '%$clean_tid%' LIMIT 1");
    if ($t_query && $t_query->num_rows > 0) {
        $t_row = $t_query->fetch_assoc();
        $teacher_name = !empty($t_row['display_name']) ? $t_row['display_name'] : $teacher_name;
        $subject_name = !empty($t_row['specialization']) ? $t_row['specialization'] : $subject_name;
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lang['std_board_title']; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="css/responsive_mobile.css">
    <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/3.5.0/model-viewer.min.js"></script>
    <style>
        :root { --maroon: #6b1024; --white: #ffffff; --bg-gray: #f0f2f5; }
        body { font-family: 'Segoe UI', sans-serif; background: var(--bg-gray); margin: 0; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
        
        .live-header { background: var(--maroon); color: white; padding: 12px 30px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 10px rgba(0,0,0,0.1); z-index: 10; }
        .exit-btn { background: #9f1239; color: white; text-decoration: none; padding: 8px 18px; border-radius: 8px; font-weight: bold; transition: 0.3s; display: flex; align-items: center; gap: 8px; border: 1px solid #fda4af; }
        .exit-btn:hover { background: #ef4444; }

        .video-container { flex: 1; background: #ffffff; margin: 15px; border-radius: 20px; position: relative; display: flex; justify-content: center; align-items: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2); border: 3px solid var(--maroon); overflow: hidden; }
        #remoteVideo { width: 100%; height: 100%; object-fit: contain; }
        .status-msg { color: white; font-size: 1.2rem; position: absolute; z-index: 5; background: rgba(0,0,0,0.5); padding: 10px 20px; border-radius: 10px; }

        .draggable-video-wrapper { position: absolute; bottom: 20px; right: 20px; width: 200px; height: 150px; background: #1e293b; border-radius: 12px; border: 2px solid var(--maroon); box-shadow: 0 10px 30px rgba(0,0,0,0.4); display: none; flex-direction: column; overflow: hidden; resize: both; z-index: 100; min-width: 120px; min-height: 90px; max-width: 500px; max-height: 400px; }
        .video-drag-header { background: rgba(107, 16, 36, 0.9); color: white; font-size: 11px; padding: 5px; text-align: center; cursor: move; user-select: none; display: flex; justify-content: space-between; align-items: center; }
        #localVideo { width: 100%; height: calc(100% - 25px); object-fit: cover; background: #000; }

        .chat-panel-wrapper { position: absolute; bottom: 80px; left: 20px; width: 300px; height: 400px; background: #ffffff; border-radius: 12px; border: 2px solid var(--maroon); box-shadow: 0 10px 30px rgba(0,0,0,0.3); display: none; flex-direction: column; overflow: hidden; resize: both; z-index: 101; min-width: 250px; min-height: 300px; }
        .chat-header { background: var(--maroon); color: white; font-size: 14px; padding: 10px; font-weight: bold; cursor: move; user-select: none; display: flex; justify-content: space-between; align-items: center; }
        .chat-messages { flex: 1; padding: 15px; overflow-y: auto; background: #f8fafc; display: flex; flex-direction: column; gap: 10px; }
        .chat-input-area { padding: 10px; background: #fff; border-top: 1px solid #e2e8f0; display: flex; gap: 8px; }
        .chat-input-area input { flex: 1; padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 20px; outline: none; font-family: inherit; }
        .chat-input-area button { background: var(--maroon); color: white; border: none; width: 35px; height: 35px; border-radius: 50%; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: 0.3s; }
        
        .msg-bubble { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 13px; line-height: 1.4; word-wrap: break-word; }
        .msg-teacher { background: #fee2e2; border: 1px solid #fca5a5; color: #7f1d1d; align-self: flex-start; border-top-right-radius: 2px; }
        .msg-student { background: var(--maroon); color: white; align-self: flex-end; border-top-left-radius: 2px; }
        .msg-sender { font-size: 10px; font-weight: bold; margin-bottom: 3px; display: block; opacity: 0.8; }

        .student-toolbar { background: var(--bg-gray); padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; }
        .tools-wrapper { background: var(--white); padding: 8px 15px; display: flex; justify-content: center; align-items: center; gap: 12px; border-radius: 10px; border: 1px solid var(--maroon); flex: 1; margin: 0 20px; box-shadow: 0 4px 10px rgba(0,0,0,0.05); }

        .btn { background: white; color: var(--maroon); border: 1px solid var(--maroon); padding: 6px 15px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-weight: bold; transition: 0.3s; font-size: 14px; }
        .btn.active { background: var(--maroon); color: white; }
        
        .chat-btn, .color-btn, .ai-assistant-btn { background: white; color: var(--maroon); border: 1px solid var(--maroon); padding: 6px 15px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-weight: bold; transition: 0.3s; font-size: 14px; position: relative; }
        .chat-btn:hover { background: #fff1f2; }
        .notification-badge { position: absolute; top: -6px; right: -6px; background: #ef4444; color: white; font-size: 10px; width: 18px; height: 18px; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-weight: bold; box-shadow: 0 2px 5px rgba(0,0,0,0.2); animation: pop 0.3s ease-out; }
        
        #color-picker { opacity: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; cursor: pointer; }
        .ai-assistant-btn { color: #3b82f6; border: 1px solid #3b82f6; }
        .size-control { display: flex; align-items: center; gap: 10px; color: var(--maroon); font-weight: bold; direction: ltr; font-size: 14px; }
        input[type=range] { cursor: pointer; accent-color: var(--maroon); width: 80px; }

        .media-controls { display: flex; gap: 12px; }
        .sync-icon-btn { width: 45px; height: 45px; border-radius: 50%; border: none; color: white; display: flex; justify-content: center; align-items: center; font-size: 1.2rem; transition: 0.3s; box-shadow: 0 4px 10px rgba(0,0,0,0.1); cursor: pointer; }
        
        .state-disabled { background: #94a3b8; opacity: 0.8; }
        .state-ready { background: #22c55e; } 

        .floating-text-box { position: absolute !important; background: #ffffff; border: 2px solid #6b1024; padding: 10px; border-radius: 10px; box-shadow: 0 10px 25px rgba(0,0,0,0.3); z-index: 9999 !important; cursor: move; }
        .floating-text-box textarea { width: 150px; height: 80px; border: 1px solid #ccc; display: block; margin-top: 5px; }
        .confirm-text-btn { background: #6b1024; color: white; border: none; padding: 5px 10px; border-radius: 4px; margin-top: 5px; cursor: pointer; }
  </style>
</head>
<body>

    <header class="live-header">
        <div>
            <h2 style="margin: 0; font-size: 1.6rem;"><?php echo htmlspecialchars($subject_name); ?></h2>
            <p style="margin: 5px 0 0 0; font-size: 14px; opacity: 0.9;"><?php echo $lang['std_board_js_teacher']; ?>: <?php echo htmlspecialchars($teacher_name); ?></p>
        </div>
        <div style="display:flex; align-items:center; gap:20px;">
            <a href="../student_dashboard.php?sid=<?php echo urlencode($sid); ?>" class="exit-btn">
                <?php echo $lang['std_board_leave']; ?> <i class="fas fa-sign-out-alt"></i>
            </a>
            <span style="background: #ef4444; padding: 6px 20px; border-radius: 20px; font-weight: bold; font-size: 15px; display: flex; align-items: center; gap: 8px;">
                <i class="fas fa-circle" style="font-size: 10px;"></i> <?php echo $lang['std_board_live_now']; ?>
            </span>
        </div>
    </header>

    <div class="video-container">
        <div id="status-msg" class="status-msg" style="display:none;"><?php echo $lang['std_board_waiting']; ?></div>
        <div id="student-media-layer" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; background: #ffffff; display: flex; justify-content: center; align-items: center; border-radius: 17px; overflow: hidden;"></div>
<canvas id="whiteboard" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 900 !important; border-radius: 17px; cursor: crosshair; background: transparent; touch-action: none; pointer-events: auto;"></canvas>
        <div id="teacher-cam-panel" class="draggable-video-wrapper" style="display: flex; visibility: hidden; opacity: 0; flex-direction: column; position: fixed; top: 20px; left: 20px; border: 2px solid #10b981; z-index: 9999; width: 240px; height: 180px; background: #000; border-radius: 8px; overflow: hidden; resize: both; transition: opacity 0.3s ease;">
            <div class="video-drag-header" id="teacher-cam-drag-handle" style="background: #10b981; color: white; padding: 5px; font-size: 12px; display: flex; justify-content: space-between; align-items: center; height: 25px; cursor: move; user-select: none;">
                <span><i class="fas fa-chalkboard-teacher"></i> <?php echo $lang['std_board_teacher_cam']; ?></span>
                <i class="fas fa-expand-arrows-alt" style="opacity: 0.7;"></i>
            </div>
            <video id="remoteVideo" autoplay playsinline style="width: 100%; flex: 1; object-fit: cover; background: #000;"></video>
        </div>
        
        <div id="local-video-container" class="draggable-video-wrapper">
            <div class="video-drag-header" id="video-drag-handle">
                <span><?php echo $lang['std_board_you_student']; ?></span>
                <i class="fas fa-expand-arrows-alt" style="opacity: 0.7;"></i>
            </div>
            <video id="localVideo" autoplay playsinline muted></video>
        </div>

        <div id="chat-panel" class="chat-panel-wrapper">
            <div class="chat-header" id="chat-drag-handle">
                <span><i class="fas fa-comments"></i> <?php echo $lang['std_board_chat_title']; ?></span>
                <i class="fas fa-times" style="cursor:pointer;" onclick="ChatModule.toggleChat()"></i>
            </div>
            <div class="chat-messages" id="chat-messages">
                </div>
            <div class="chat-input-area">
                <input type="text" id="chat-input" placeholder="<?php echo $lang['std_board_chat_placeholder']; ?>" onkeypress="if(event.key === 'Enter') ChatModule.sendMessage()">
                <button onclick="ChatModule.sendMessage()"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>

        <div id="ai-panel" class="chat-panel-wrapper" style="display:none; bottom: 80px; right: 240px; border-color: #3b82f6; z-index: 105;">
            <div class="chat-header" style="background: #3b82f6;" id="ai-drag-handle">
                <span><i class="fas fa-robot"></i> <?php echo $lang['std_board_ai_title']; ?></span>
                <i class="fas fa-times" style="cursor:pointer;" onclick="AIModule.togglePanel()"></i>
            </div>
            <div class="chat-messages" id="ai-chat-box">
                <div class="msg-bubble msg-teacher" style="background: #eff6ff; border: 1px solid #bfdbfe; color: #1e3a8a;">
                    <span class="msg-sender"><?php echo $lang['std_board_js_ai_name']; ?></span>
                    <?php echo $lang['std_board_ai_welcome']; ?>
                </div>
            </div>
            <div class="chat-input-area">
                <input type="text" id="ai-input-field" placeholder="<?php echo $lang['std_board_ai_placeholder']; ?>" onkeypress="if(event.key === 'Enter') AIModule.sendMessage()">
                <button onclick="AIModule.sendMessage()" style="background: #3b82f6;"><i class="fas fa-paper-plane"></i></button>
            </div>
            <div id="screen-share-container" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 9999; display: none; background: black;">
    <video id="screen-share-video" autoplay playsinline style="width: 100%; height: 100%; object-fit: contain;"></video>
    <button onclick="document.getElementById('screen-share-container').style.display='none'" style="position: absolute; top: 10px; right: 10px;"><?php echo $lang['std_board_btn_hide']; ?></button>
</div>
        </div>
    </div>

    <div class="student-toolbar">
        <div class="tools-wrapper tool-group">
            <button class="chat-btn" onclick="ChatModule.toggleChat()">
                <?php echo $lang['std_board_btn_chat']; ?> <i class="fas fa-comment-dots"></i>
                <span id="chat-badge" class="notification-badge" style="display:none;">0</span>
            </button>

            <button class="btn active" id="tool-pen"> <?php echo $lang['std_board_btn_pen']; ?> <i class="fas fa-pen"></i></button>
            <button class="btn" id="tool-text"> <?php echo $lang['std_board_btn_text']; ?> <i class="fas fa-font"></i></button>
            
            <label class="color-btn" title="<?php echo $lang['std_board_color_title']; ?>"> <?php echo $lang['std_board_color_label']; ?> 
                <span id="color-preview" style="display:inline-block; width:12px; height:12px; background:#000000; border-radius:50%; margin-right:5px;"></span>
                <input type="color" id="color-picker" value="#000000">
            </label>
            
            <button class="btn" id="tool-eraser"> <?php echo $lang['std_board_btn_eraser']; ?> <i class="fas fa-eraser" style="color:#eab308"></i></button>
            <button id="tool-hand" class="btn" title="<?php echo $lang['std_board_tool_hand_title']; ?>"><i class="fas fa-hand-paper"></i></button>
            
            <div class="size-control">
                <span id="width-val">3px</span>
                <input type="range" id="pen-width" min="1" max="20" value="3">
                <span><?php echo $lang['std_board_size_label']; ?></span>
            </div>
            
            <button class="ai-assistant-btn" onclick="AIModule.togglePanel()"><i class="fas fa-robot"></i> <?php echo $lang['std_board_btn_ai']; ?></button>
        </div>

        <div class="media-controls">
            <button id="mic-btn-icon" class="sync-icon-btn state-disabled" title="<?php echo $lang['std_board_mic_title']; ?>" onclick="StudentMedia.toggleMic()"><i class="fas fa-microphone-slash"></i></button>
            <button id="cam-btn-icon" class="sync-icon-btn state-disabled" title="<?php echo $lang['std_board_cam_title']; ?>" onclick="StudentMedia.toggleCam()"><i class="fas fa-video-slash"></i></button>
        </div>
        
    </div>

    
 <script src="/academy/live_v2/js/modules/whiteboard.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/whiteboard_sync.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/webrtc_core.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/student_cam_broadcaster.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/students_grid_webrtc.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/screen_share_core.js?v=<?php echo time(); ?>"></script>
    <script src="/academy/live_v2/js/modules/media_sync.js?v=<?php echo time(); ?>"></script>
   
    
    <script>
        const phpSid = "<?php echo addslashes($sid); ?>";
        const phpTid = "<?php echo addslashes($clean_tid); ?>";

        window.userRole = 'student';
        window.canStudentDraw = true;

        const ChatModule = {
            isOpen: false,
            lastMsgId: 0,
            roomTid: phpTid,
            studentName: "<?php echo addslashes($student_real_name); ?>",

            toggleChat: function() {
                const panel = document.getElementById('chat-panel');
                this.isOpen = !this.isOpen;
                panel.style.display = this.isOpen ? 'flex' : 'none';
                if (this.isOpen) { this.resetBadge(); this.scrollToBottom(); }
            },

            sendMessage: function() {
                const input = document.getElementById('chat-input');
                const text = input.value.trim();
                if (!text) return;

                let formData = new FormData();
                formData.append('sender', this.studentName);
                formData.append('msg', text);

                fetch(`../zoom_api/chat_api.php?action=send&tid=${this.roomTid}`, {
                    method: 'POST',
                    body: formData
                });
                
                input.value = '';
            },

            fetchUpdates: function() {
                if (!this.roomTid) return;
                fetch(`../zoom_api/chat_api.php?action=fetch&tid=${this.roomTid}&t=${Date.now()}`)
                .then(res => res.json())
                .then(messages => {
                    if (messages && messages.length > 0) {
                        const container = document.getElementById('chat-messages');
                        
                        if (this.lastMsgId === 0) container.innerHTML = ''; 

                        let unreadCount = 0;
                        let hasNew = false;

                        messages.forEach(msg => {
                            if (parseInt(msg.id) > this.lastMsgId) {
                                this.lastMsgId = parseInt(msg.id);
                                hasNew = true;

                                const isMe = (msg.sender_name === this.studentName);
                                const isTeacher = (msg.sender_name === 'الأستاذ' || msg.sender_name === '<?php echo $lang['t_board_js_ai_you']; ?>' || msg.sender_name === 'Teacher');
                                
                                let cssClass = isMe ? 'msg-student' : 'msg-teacher'; 
                                const senderDisplay = isMe ? '<?php echo $lang['std_board_js_you']; ?>' : msg.sender_name;

                                container.innerHTML += `
                                    <div class="msg-bubble ${cssClass}">
                                        <span class="msg-sender">${senderDisplay}</span>
                                        ${msg.message}
                                    </div>`;

                                if (!this.isOpen && !isMe) unreadCount++;
                            }
                        });

                        if (unreadCount > 0) {
                            const badge = document.getElementById('chat-badge');
                            if(badge) {
                                badge.innerText = parseInt(badge.innerText || 0) + unreadCount;
                                badge.style.display = 'flex';
                            }
                        }
                        if (hasNew) this.scrollToBottom();
                    }
                });
            },

            resetBadge: function() { 
                const badge = document.getElementById('chat-badge');
                if(badge) { badge.style.display = 'none'; badge.innerText = '0'; }
            },
            
            scrollToBottom: function() { 
                const container = document.getElementById('chat-messages'); 
                if(container) container.scrollTop = container.scrollHeight; 
            }
        };

        const AIModule = {
            togglePanel: function() {
                const panel = document.getElementById('ai-panel');
                if (panel) { panel.style.display = (panel.style.display === 'flex') ? 'none' : 'flex'; } 
            },
            appendMessage: function(sender, text, cssClass) {
                const container = document.getElementById('ai-chat-box');
                if (!container) return;
                container.innerHTML += `<div class="msg-bubble ${cssClass}"><span class="msg-sender">${sender}</span>${text}</div>`;
                container.scrollTop = container.scrollHeight;
            },
            sendMessage: async function() {
                const input = document.getElementById('ai-input-field');
                const msg = input.value.trim();
                if(!msg) return;
                
                this.appendMessage('<?php echo $lang['std_board_js_you']; ?>', msg, 'msg-student');
                input.value = '';
                this.appendMessage('<?php echo $lang['std_board_js_ai_name']; ?>', '<i class="fas fa-spinner fa-spin"></i> <?php echo $lang['std_board_js_ai_thinking']; ?>', 'msg-teacher');
                
                try {
                    const response = await fetch('../live_v2/roozmari_ai.php', {
                        method: 'POST', headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ prompt: msg }) 
                    });
                    const data = await response.json();
                    const container = document.getElementById('ai-chat-box');
                    if (container.lastElementChild && container.lastElementChild.innerHTML.includes('fa-spinner')) container.lastElementChild.remove();
                    if (data.candidates && data.candidates[0]) this.appendMessage('<?php echo $lang['std_board_js_ai_name']; ?>', data.candidates[0].content.parts[0].text, 'msg-teacher');
                    else this.appendMessage('<?php echo $lang['std_board_js_ai_name']; ?>', '<?php echo $lang['std_board_js_ai_error']; ?>', 'msg-teacher');
                } catch(e) {
                    const container = document.getElementById('ai-chat-box');
                    if (container.lastElementChild && container.lastElementChild.innerHTML.includes('fa-spinner')) container.lastElementChild.remove();
                    this.appendMessage('<?php echo $lang['std_board_js_ai_name']; ?>', '<?php echo $lang['std_board_js_ai_net_error']; ?>', 'msg-teacher');
                }
            }
        };

        const StudentMedia = {
            localStream: new MediaStream(),
            camState: 0, 
            teacherAllowsCam: true, 
            teacherAllowsMic: true,
            dummyCanvas: null,

            getDummyTrack: function() {
                if (!this.dummyCanvas) {
                    this.dummyCanvas = document.createElement('canvas');
                    this.dummyCanvas.width = 640; this.dummyCanvas.height = 480;
                    const ctx = this.dummyCanvas.getContext('2d');
                    ctx.fillRect(0, 0, 640, 480);
                    setInterval(() => {
                        ctx.fillStyle = '#000000';
                        ctx.fillRect(0, 0, 640, 480);
                    }, 1000);
                }
                return this.dummyCanvas.captureStream(15).getVideoTracks()[0];
            },

            initStream: async function() {
                try {
                    const audioStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
                    const audioTrack = audioStream.getAudioTracks()[0];
                    const dummyTrack = this.getDummyTrack();

                    this.localStream.addTrack(audioTrack);
                    this.localStream.addTrack(dummyTrack);

                    const locVid = document.getElementById('localVideo');
                    if(locVid) locVid.srcObject = this.localStream;
                    this.camState = 0; 
                    
                    const micBtn = document.getElementById('mic-btn-icon');
                    if (micBtn) { micBtn.className = 'sync-icon-btn state-ready'; micBtn.innerHTML = '<i class="fas fa-microphone"></i>'; }
                    const camBtn = document.getElementById('cam-btn-icon');
                    if (camBtn) { camBtn.className = 'sync-icon-btn state-disabled'; camBtn.innerHTML = '<i class="fas fa-video-slash"></i>'; }

                    setTimeout(() => {
                        if (typeof StudentCamBroadcaster !== 'undefined') {
                            StudentCamBroadcaster.startBroadcast(phpTid, phpSid, this.localStream);
                        }
                    }, 1500);
                } catch (e) { console.error("<?php echo $lang['std_board_js_media_error']; ?>", e); }
            },

            toggleMic: function() {
                if (!this.teacherAllowsMic) return;
                const track = this.localStream.getAudioTracks()[0];
                if (track) { 
                    track.enabled = !track.enabled; 
                    const btn = document.getElementById('mic-btn-icon'); 
                    btn.className = track.enabled ? 'sync-icon-btn state-ready' : 'sync-icon-btn state-disabled'; 
                    btn.innerHTML = track.enabled ? '<i class="fas fa-microphone"></i>' : '<i class="fas fa-microphone-slash"></i>'; 
                }
            },

            toggleCam: function() {
                if (!this.teacherAllowsCam) return;
                if (this.camState === 1) { this.turnOffCameraHardware(); } else { this.turnOnCameraHardware(); }
            },

            turnOffCameraHardware: function() {
                const realTracks = this.localStream.getVideoTracks();
                realTracks.forEach(track => {
                    track.stop();
                    this.localStream.removeTrack(track);
                });

                const dummyTrack = this.getDummyTrack();
                this.localStream.addTrack(dummyTrack);

                document.getElementById('local-video-container').style.display = 'none'; 
                this.camState = 0;
                const btn = document.getElementById('cam-btn-icon'); 
                if(btn) { btn.className = 'sync-icon-btn state-disabled'; btn.innerHTML = '<i class="fas fa-video-slash"></i>'; }

                if (typeof StudentCamBroadcaster !== 'undefined' && StudentCamBroadcaster.pc) {
                    const senders = StudentCamBroadcaster.pc.getSenders();
                    const sender = senders.find(s => s.track && s.track.kind === 'video');
                    if (sender) sender.replaceTrack(dummyTrack).catch(e=>console.log(e));
                }
            },

            turnOnCameraHardware: async function() {
                try {
                    const newStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
                    const newVideoTrack = newStream.getVideoTracks()[0];
                    
                    this.localStream.getVideoTracks().forEach(t => {
                        t.stop();
                        this.localStream.removeTrack(t);
                    });
                    
                    this.localStream.addTrack(newVideoTrack);
                    
                    const locVid = document.getElementById('localVideo');
                    if(locVid) {
                        locVid.srcObject = this.localStream;
                        locVid.play().catch(e=>{});
                    }
                    
                    document.getElementById('local-video-container').style.display = 'flex';
                    this.camState = 1;
                    
                    const btn = document.getElementById('cam-btn-icon'); 
                    if(btn) { btn.className = 'sync-icon-btn state-ready'; btn.innerHTML = '<i class="fas fa-video"></i>'; }

                    if (typeof StudentCamBroadcaster !== 'undefined' && StudentCamBroadcaster.pc) {
                        const senders = StudentCamBroadcaster.pc.getSenders();
                        const sender = senders.find(s => s.track && s.track.kind === 'video');
                        if (sender) sender.replaceTrack(newVideoTrack).catch(e=>console.log(e));
                    }
                } catch (e) { alert("<?php echo $lang['std_board_js_cam_permission']; ?>"); }
            }
        };

        const StudentRadar = {
            init: function() { if (phpSid && phpTid) setInterval(() => this.pollTeacher(), 3000); },
            pollTeacher: function() {
                fetch(`../zoom_api/waiting_room_api.php?action=get_student_state&sid=${phpSid}&tid=${phpTid}`)
                .then(res => res.json())
                .then(data => {
                    if (data.can_draw !== undefined) window.canStudentDraw = (data.can_draw == 1);
                    if (data.can_cam !== undefined) {
                        if (data.can_cam == 0) {
                            StudentMedia.teacherAllowsCam = false;
                            if (StudentMedia.camState === 1) StudentMedia.turnOffCameraHardware();
                        } else { StudentMedia.teacherAllowsCam = true; }
                    }
                }).catch(err => {});
            }
        };

        const WhiteboardTools = {
            init: function() {
                const bindTool = (id, toolName) => {
                    const el = document.getElementById(id);
                    if (el) el.onclick = (e) => this.selectTool(toolName, e.currentTarget);
                };
                bindTool('tool-pen', 'pen');
                bindTool('tool-text', 'text');
                bindTool('tool-eraser', 'eraser');
                
                const colorPicker = document.getElementById('color-picker');
                if (colorPicker) colorPicker.oninput = (e) => { 
                    document.getElementById('color-preview').style.background = e.target.value;
                    if (typeof WhiteboardModule !== 'undefined') WhiteboardModule.currentColor = e.target.value;
                };
                const penWidth = document.getElementById('pen-width');
                if (penWidth) penWidth.oninput = (e) => { 
                    document.getElementById('width-val').innerText = e.target.value + 'px';
                    if (typeof WhiteboardModule !== 'undefined') WhiteboardModule.currentLineWidth = e.target.value;
                };
            },
            selectTool: function(toolName, btnElement) {
                if (!window.canStudentDraw) return;
                if (typeof WhiteboardModule !== 'undefined') WhiteboardModule.currentTool = toolName;
                document.querySelectorAll('.btn').forEach(b => b.classList.remove('active'));
                btnElement.classList.add('active');
            }
        };

        function makeDraggableSafe(elmnt, header) {
            if (!elmnt || !header) return;
            var startX, startY, initialX, initialY;
            header.style.cursor = 'grab';
            header.onmousedown = dragMouseDown;
            header.ontouchstart = dragTouchStart; 

            function dragMouseDown(e) { e.preventDefault(); header.style.cursor = 'grabbing'; startX = e.clientX; startY = e.clientY; preparePanel(); document.onmouseup = closeDragElement; document.onmousemove = elementDrag; }
            function dragTouchStart(e) { if (e.cancelable) e.preventDefault(); header.style.cursor = 'grabbing'; startX = e.touches[0].clientX; startY = e.touches[0].clientY; preparePanel(); document.ontouchend = closeDragElement; document.ontouchmove = elementDragTouch; }
            function preparePanel() { 
                const rect = elmnt.getBoundingClientRect(); 
                initialX = rect.left; 
                initialY = rect.top; 
                elmnt.style.setProperty('width', rect.width + 'px', 'important'); 
                elmnt.style.setProperty('position', 'absolute', 'important'); 
                elmnt.style.setProperty('margin', '0', 'important'); 
                elmnt.style.setProperty('transform', 'none', 'important'); 
                elmnt.style.setProperty('right', 'auto', 'important');
                elmnt.style.setProperty('bottom', 'auto', 'important');
                elmnt.style.setProperty('left', initialX + 'px', 'important'); 
                elmnt.style.setProperty('top', initialY + 'px', 'important'); 
            }
            function elementDrag(e) { e.preventDefault(); elmnt.style.setProperty('left', (initialX + (e.clientX - startX)) + 'px', 'important'); elmnt.style.setProperty('top', (initialY + (e.clientY - startY)) + 'px', 'important'); }
            function elementDragTouch(e) { if (e.cancelable) e.preventDefault(); elmnt.style.setProperty('left', (initialX + (e.touches[0].clientX - startX)) + 'px', 'important'); elmnt.style.setProperty('top', (initialY + (e.touches[0].clientY - startY)) + 'px', 'important'); }
            function closeDragElement() { header.style.cursor = 'grab'; document.onmouseup = null; document.onmousemove = null; document.ontouchend = null; document.ontouchmove = null; }
        }

        window.addEventListener('DOMContentLoaded', () => {
            if (typeof WhiteboardModule !== 'undefined') { 
                WhiteboardModule.init('student'); 
                WhiteboardModule.resize = function() { this.canvas.width = this.canvas.offsetWidth; this.canvas.height = this.canvas.offsetHeight; };
                WhiteboardModule.attachEvents();
                setTimeout(() => { WhiteboardModule.currentColor = '#000000'; WhiteboardModule.currentTool = 'pen'; }, 500);
            }
            WhiteboardTools.init();

            if (typeof WhiteboardSync !== 'undefined' && phpTid) WhiteboardSync.startStudentSync(phpTid);
            if (typeof WebRTCModule !== 'undefined' && phpTid) WebRTCModule.init('student', phpTid);
            
            StudentMedia.initStream();
            StudentRadar.init();
            if (phpSid && phpTid) fetch(`../zoom_api/waiting_room_api.php?action=join&sid=${phpSid}&tid=${phpTid}`).catch(err => {});
            
            makeDraggableSafe(document.getElementById('ai-panel'), document.getElementById('ai-drag-handle'));
            makeDraggableSafe(document.getElementById('chat-panel'), document.getElementById('chat-drag-handle'));
            makeDraggableSafe(document.getElementById('local-video-container'), document.getElementById('video-drag-handle'));
            makeDraggableSafe(document.getElementById('teacher-cam-panel'), document.getElementById('teacher-cam-drag-handle'));
            
            setInterval(() => ChatModule.fetchUpdates(), 1500);

            const canvas = document.getElementById('whiteboard');
            if (canvas) {
                const bindCanvasEvent = (id, pointerState, zIndexWindow) => { 
                    const btn = document.getElementById(id); 
                    if (btn) {
                        btn.addEventListener('click', () => {
                            canvas.style.setProperty('pointer-events', pointerState, 'important');
                            document.querySelectorAll('.draggable-video-wrapper').forEach(win => {
                                if (win.id !== 'teacher-cam-panel' && win.id !== 'local-video-container') {
                                    win.style.setProperty('z-index', zIndexWindow, 'important');
                                }
                            });
                        });
                    }
                };
                bindCanvasEvent('tool-hand', 'none', '950'); 
                bindCanvasEvent('tool-pen', 'auto', '10'); 
                bindCanvasEvent('tool-text', 'auto', '10'); 
                bindCanvasEvent('tool-eraser', 'auto', '10');
            }
        });

        // 🚀 المحرك النقي والموحد والوحيد للمزامنة (يمنع التعارض وسواد الكاميرا تماماً)
        if (window.syncGuardInterval) clearInterval(window.syncGuardInterval);
        window.syncGuardInterval = setInterval(async () => {
            try {
                if (!phpTid) return;
                const response = await fetch(`../zoom_api/media_sync_api.php?action=get_command&tid=${phpTid}`);
                const text = await response.text(); 
                if (!text || text.trim() === '' || text.includes('"action":"none"')) return; 
                
                const command = JSON.parse(text);
                const actionName = (command && command.action) ? command.action.toUpperCase() : '';
                const data = (command.data && typeof command.data === 'string') ? JSON.parse(command.data) : command.data;
                
                // 1. استقبال وإنشاء المجسم العائم القابل للسحب والتفاعل من الطالب المباشر
                if (actionName === 'LOAD_FILE' || actionName === 'LOAD_MODEL') {
                    const uniqueId = data.id;
                    if (document.getElementById(uniqueId)) return; 

                    const mediaWindow = document.createElement('div');
                    mediaWindow.id = uniqueId;
                    mediaWindow.className = 'draggable-video-wrapper';
                    
                    const leftPos = data.left !== undefined ? data.left : '20%';
                    const topPos = data.top !== undefined ? data.top : '15%';

                    mediaWindow.style.cssText = `position: absolute; top: ${topPos}; left: ${leftPos}; width: ${data.width || '50%'}; height: ${data.height || '60%'}; z-index: 890 !important; background: #fff; border: 2px solid #6b1024; border-radius: 8px; overflow: hidden; resize: both; box-shadow: 0 5px 15px rgba(0,0,0,0.3); flex-direction: column; display: flex; pointer-events: auto;`;

                    mediaWindow.innerHTML = `
                        <div id="drag-${uniqueId}" style="background: #6b1024; color: white; padding: 5px 10px; display: flex; justify-content: space-between; align-items: center; font-size: 12px; cursor: move; user-select: none;">
                            <span><i class="fas fa-cube"></i> ${data.title || '<?php echo $lang['std_board_js_edu_tool']; ?>'}</span>
                        </div>
                        <div id="content-${uniqueId}" style="width: 100%; flex: 1; position: relative; background: #f0f2f5;"></div>
                    `;

                    const whiteboard = document.getElementById('whiteboard');
                    if (whiteboard && whiteboard.parentNode) whiteboard.parentNode.insertBefore(mediaWindow, whiteboard);
                    else document.body.appendChild(mediaWindow);

                    if (typeof makeDraggableSafe === 'function') {
                        makeDraggableSafe(mediaWindow, document.getElementById(`drag-${uniqueId}`));
                    }

                    const contentArea = document.getElementById(`content-${uniqueId}`);
                    if (data.type === '3D' || (data.url && data.url.toLowerCase().endsWith('.glb'))) {
                        contentArea.innerHTML = `<model-viewer src="${data.url}" camera-controls style="width:100%; height:100%; outline:none; background: transparent;"></model-viewer>`;
                    } else if (data.type === 'IMAGE') {
                        contentArea.innerHTML = `<img src="${data.url}" style="width:100%; height:100%; object-fit:contain;">`;
                    }
                } 
                
                // 2. مزامنة أبعاد وحركة النافذة العائمة لحظة بلحظة
                else if (actionName === 'MOVE_MEDIA') {
                    const targetEl = document.getElementById(data.id);
                    if (targetEl) {
                        targetEl.style.left = data.left; targetEl.style.top = data.top;
                        if (data.width) targetEl.style.width = data.width;
                        if (data.height) targetEl.style.height = data.height;
                    }
                }
                
                // 3. مزامنة الكاميرا الداخلية بالمليمتر (الدوران والزوم الصريح fovStr)
                else if (actionName === 'SYNC_3D') { 
                    const modelViewer = document.querySelector(`#content-${data.id} model-viewer`);
                    if (modelViewer) {
                        modelViewer.removeAttribute('auto-rotate');
                        if (data.orbitStr) modelViewer.setAttribute('camera-orbit', data.orbitStr);
                        if (data.targetStr) modelViewer.setAttribute('camera-target', data.targetStr);
                        if (data.fovStr) modelViewer.setAttribute('field-of-view', data.fovStr);
                        if (typeof modelViewer.jumpCameraToGoal === 'function') modelViewer.jumpCameraToGoal();
                    }
                }

                // 4. إظهار وإخفاء الكاميرا مع حماية تدفق مسار الصوت والصورة النقي للـ WebRTC بدون حذفه
                else if (actionName === 'TEACHER_CAM') {
                    const camPanel = document.getElementById('teacher-cam-panel'); 
                    const remoteVid = document.getElementById('remoteVideo');
                    
                    if (camPanel) {
                        if (data.state === 'off') {
                            camPanel.style.setProperty('visibility', 'hidden', 'important');
                            camPanel.style.setProperty('opacity', '0', 'important');
                            if(remoteVid) remoteVid.pause();
                        } else if (data.state === 'on') {
                            camPanel.style.setProperty('display', 'flex', 'important');
                            camPanel.style.setProperty('visibility', 'visible', 'important');
                            camPanel.style.setProperty('opacity', '1', 'important');
                            camPanel.style.setProperty('z-index', '999999', 'important'); 
                            
                            if (remoteVid) {
                                // دمج وحماية البث القادم عبر webrtc_core بدون إنشاء ميديا ستريم ناقصة تحذف الصوت
                                if (typeof WebRTCModule !== 'undefined' && WebRTCModule.peerConnection) {
                                    const receivers = WebRTCModule.peerConnection.getReceivers();
                                    const videoReceiver = receivers.find(r => r.track && r.track.kind === 'video');
                                    
                                    if (videoReceiver && videoReceiver.track && videoReceiver.track.readyState === 'live') {
                                        // إذا كان الفيديو متوقفاً أو غير مربوط، نقوم بتحديثه رغماً عن المتصفح ليعمل فوراً
                                        if (remoteVid.paused || !remoteVid.srcObject) {
                                            remoteVid.setAttribute('playsinline', 'true');
                                            remoteVid.setAttribute('autoplay', 'true');
                                            remoteVid.muted = true; // صامت للحظة لكسر الحماية التلقائية لكروم
                                            remoteVid.play().then(() => { remoteVid.muted = false; }).catch(e => {});
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 5. مسح وتصفير وسائل العرض الشبحية
                else if (actionName === 'CLEAR_MEDIA' || actionName === 'CLEAR') {
                    document.querySelectorAll('.draggable-video-wrapper[id^="media-"]').forEach(el => el.remove());
                    document.querySelectorAll('.draggable-video-wrapper[id^="student-win-"]').forEach(el => el.remove());
                }
            } catch (e) { console.error("Sync Error:", e); }
        }, 1000);

        // إنهاء الجلسة
        window.addEventListener('beforeunload', function () {
            if (phpSid && phpTid) {
                const formData = new FormData();
                formData.append('action', 'leave');
                formData.append('sid', phpSid);
                formData.append('tid', phpTid);
                navigator.sendBeacon('../zoom_api/waiting_room_api.php', formData);
            }
        });
    </script>
     <?php include __DIR__ . '/../dynamic_watermark.php'; ?>
</body>
</html>