<script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/1.4.7/peerjs.min.js"></script>
<script src="student-logic.js"></script>
<?php
if (session_status() == PHP_SESSION_NONE) { session_start(); }
include_once '../db_connect.php';

// 1. اصطياد هوية الطالب
$php_sid = $_GET['sid'] ?? $_SESSION['student_id'] ?? '';

// 2. 🚀 الرادار السحري: اصطياد معرف المدرس (tid) الذي يبث حالياً لربط الطالب بغرفته إجبارياً
$active_tid = '';
if (!empty($php_sid)) {
    $st_q = $conn->query("SELECT teacher_name FROM students WHERE student_id = '$php_sid' LIMIT 1");
    if ($st_q && $st_q->num_rows > 0) {
        $row = $st_q->fetch_assoc();
        preg_match('/\d{5,}/', $row['teacher_name'], $m);
        if (!empty($m[0])) { $active_tid = $m[0]; }
    }
}
// خطة بديلة: إذا لم نعرف مدرسه، نرسله لآخر بث مفتوح
if (empty($active_tid)) {
    $last_meet = $conn->query("SELECT teacher_id FROM zoom_active_meetings ORDER BY updated_at DESC LIMIT 1");
    if ($last_meet && $last_meet->num_rows > 0) {
        $active_tid = $last_meet->fetch_assoc()['teacher_id'];
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>غرفة البث المباشر | أكاديمية روزماري</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --bg-color: #f0f2f5;
            --maroon: #6b1437;
            --maroon-dark: #4a0d26;
        }

        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--bg-color); height: 100vh; display: flex; flex-direction: column; overflow: hidden; }

        .live-header { background: var(--maroon); color: white; padding: 15px 30px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 10px rgba(0,0,0,0.1); z-index: 10; }
        
        /* 🚀 تعديل زر المغادرة ليكون زراً برمجياً */
        .back-btn { color: white; text-decoration: none; font-size: 1.1rem; background: rgba(255,255,255,0.2); padding: 8px 15px; border-radius: 8px; transition: 0.3s; border: none; cursor: pointer; font-family: inherit; }
        .back-btn:hover { background: rgba(239, 68, 68, 0.8); }
        
        .live-badge { background: #ef4444; padding: 5px 15px; border-radius: 20px; font-weight: bold; animation: pulse 2s infinite; }

        #video-container { 
            flex: 1; position: relative; background: #000; margin: 20px; border-radius: 15px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.15); border: 2px solid #e2e8f0; 
            overflow: hidden; display: flex; justify-content: center; align-items: center; 
        }
        #remoteVideo { width: 100%; height: 100%; object-fit: contain; cursor: pointer; display: none; } 
        
        /* شاشة الانتظار */
        .waiting-room-overlay { position: absolute; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.9); z-index: 50; display:flex; flex-direction:column; align-items:center; justify-content:center; color:white; text-align:center; }
        .spinner-ring { border: 4px solid rgba(255,255,255,0.1); border-left-color: #3b82f6; border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite; margin-bottom: 20px; }
        
        .overlay-msg { position: absolute; color: white; background: rgba(0,0,0,0.7); padding: 10px 20px; border-radius: 10px; pointer-events: none; z-index: 5; text-align: center; font-weight: bold; display: none; }

        .student-toolbar { position: absolute; top: 20px; left: 50%; transform: translateX(-50%); background: white; padding: 10px 20px; border-radius: 30px; box-shadow: 0 5px 20px rgba(0,0,0,0.15); display: none; gap: 15px; border: 1px solid var(--maroon); z-index: 20; }
        .student-toolbar button { background: none; border: none; font-size: 1.2rem; color: #64748b; cursor: pointer; transition: 0.3s; }
        .student-toolbar button:hover, .student-toolbar button.active { color: var(--maroon); transform: scale(1.1); }

        .floating-actions { position: fixed; bottom: 30px; width: 100%; display: flex; justify-content: space-between; padding: 0 40px; box-sizing: border-box; pointer-events: none; z-index: 100; display: none; } 
        .action-btn { width: 60px; height: 60px; border-radius: 50%; border: none; font-size: 1.5rem; color: white; cursor: pointer; display: flex; justify-content: center; align-items: center; box-shadow: 0 10px 20px rgba(0,0,0,0.2); pointer-events: auto; transition: 0.3s; }
        .action-btn:hover { transform: translateY(-5px) scale(1.05); }
        .hand-btn { background: #3b82f6; }
        .hand-btn.raised { background: #f59e0b; animation: shake 0.5s infinite; }
        .chat-btn { background: var(--maroon); }

        .chat-panel { position: fixed; bottom: 100px; right: 40px; width: 320px; height: 400px; background: white; border-radius: 15px; box-shadow: 0 15px 40px rgba(0,0,0,0.15); display: none; flex-direction: column; overflow: hidden; z-index: 99; border: 1px solid #e2e8f0; }
        .chat-header { background: var(--maroon); color: white; padding: 15px; font-weight: bold; display: flex; justify-content: space-between; }
        
        #messages { flex: 1; padding: 15px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; background: #f8fafc; }
        #messages div { background: #e2e8f0; padding: 10px; border-radius: 10px; font-size: 0.9rem; align-self: flex-start; max-width: 80%; }
        #messages div strong { color: var(--maroon); display: block; margin-bottom: 5px; }

        .chat-input-area { display: flex; padding: 10px; background: white; border-top: 1px solid #e2e8f0; }
        #msg { flex: 1; padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; outline: none; }
        .chat-input-area button { background: var(--maroon); color: white; border: none; padding: 10px 15px; margin-right: 10px; border-radius: 8px; cursor: pointer; }

        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); } 70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); } 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }
        @keyframes shake { 0% { transform: rotate(0deg); } 25% { transform: rotate(-10deg); } 50% { transform: rotate(0deg); } 75% { transform: rotate(10deg); } 100% { transform: rotate(0deg); } }
        @keyframes spin { 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>

    <header class="live-header">
        <div>
            <h2 style="margin: 0;">الغرفة التفاعلية</h2>
            <p style="margin: 5px 0 0 0; font-size: 13px; opacity: 0.8;">السبورة الذكية</p>
        </div>
        <div style="display: flex; align-items: center; gap: 20px;">
            <span class="live-badge" id="liveIndicator" style="display: none;"><i class="fas fa-circle"></i> مباشر</span>
            <button onclick="leaveRoom()" class="back-btn"><i class="fas fa-sign-out-alt"></i> مغادرة</button>
        </div>
    </header>

    <div id="video-container">
        <div id="waitingRoom" class="waiting-room-overlay">
            <div class="spinner-ring"></div>
            <h2 style="margin: 0 0 10px 0;">تم إرسال طلب الانضمام!</h2>
            <p style="color: #94a3b8; font-size: 1.1rem; max-width: 400px; line-height: 1.5;">يرجى الانتظار في هذه الصفحة، سيقوم الأستاذ بالسماح لك بالدخول قريباً.</p>
        </div>

        <div id="status-msg" class="overlay-msg">جاري الاتصال بالبث...</div>
        <video id="remoteVideo" autoplay playsinline controls></video>
        
        <div class="student-toolbar" id="studentToolbar">
            <button class="active" title="قلم"><i class="fas fa-pen"></i></button>
            <button title="ممحاة"><i class="fas fa-eraser"></i></button>
            <button title="نص"><i class="fas fa-font"></i></button>
            <button title="مسح الكل" style="color: #ef4444;"><i class="fas fa-trash"></i></button>
        </div>
    </div>

    <div class="floating-actions" id="actionButtons">
        <button class="action-btn hand-btn" id="handBtn" onclick="toggleHand()" title="طلب المشاركة على السبورة">
            <i class="fas fa-hand-paper"></i>
        </button>
        <button class="action-btn chat-btn" onclick="toggleChat()" title="فتح الدردشة">
            <i class="fas fa-comment-dots"></i>
        </button>
    </div>

    <div class="chat-panel" id="chatPanel">
        <div class="chat-header">
            <span><i class="fas fa-comments"></i> الدردشة العامة</span>
            <i class="fas fa-times" style="cursor: pointer;" onclick="toggleChat()"></i>
        </div>
        <div id="messages"></div>
        <div class="chat-input-area">
            <input type="text" id="msg" placeholder="اكتب رسالتك...">
            <button onclick="send()"><i class="fas fa-paper-plane"></i></button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    const urlParams = new URLSearchParams(window.location.search);
    const studentId = urlParams.get('sid') || localStorage.getItem('student_sync_id'); 
    window.targetTeacherId = urlParams.get('tid') || ''; 
    let realStudentName = "طالب";

    function leaveRoom() {
        window.location.href = '../student_dashboard.php?sid=' + encodeURIComponent(studentId);
    }

    if (!studentId || !window.targetTeacherId) {
        leaveRoom();
    } else {
        // 🚀 تسجيل الحضور في قاعدة البيانات لكي لا يظهر (0) للمدرس
        fetch(`waiting_room_api.php?action=join&sid=${encodeURIComponent(studentId)}&tid=${encodeURIComponent(window.targetTeacherId)}`)
        .then(res => res.json())
        .then(data => {
            if(data.name) realStudentName = data.name;
            enterLiveRoom();
        })
        .catch(e => { enterLiveRoom(); });
    }

    function enterLiveRoom() {
        document.getElementById('waitingRoom').style.display = 'none';
        document.getElementById('remoteVideo').style.display = 'block';
        document.getElementById('actionButtons').style.display = 'flex';
        
        let script = document.createElement('script');
        script.src = "student-logic.js"; 
        document.body.appendChild(script);

        // 🚨 رادار الطرد المضمون
        setInterval(() => {
            fetch(`waiting_room_api.php?action=get_student_state&sid=${encodeURIComponent(studentId)}&tid=${encodeURIComponent(window.targetTeacherId)}`)
            .then(res => res.json())
            .then(data => {
                if(data.is_kicked == '1') {
                    if (typeof peer !== 'undefined' && peer) peer.destroy(); 
                    alert("🔴 تم إنهاء جلستك وإخراجك من البث من قبل الأستاذ.");
                    window.location.href = '../student_dashboard.php?sid=' + encodeURIComponent(studentId);
                }
            }).catch(e => {});
        }, 2000);
    }

    function toggleChat() {
        let panel = document.getElementById('chatPanel');
        panel.style.display = (panel.style.display === 'flex') ? 'none' : 'flex';
    }

    function send() {
        const msgInput = document.getElementById("msg");
        const text = msgInput.value.trim();
        if(!text) return;
        const formData = new FormData();
        formData.append('action', 'send');
        formData.append('tid', window.targetTeacherId);
        formData.append('sender', realStudentName); 
        formData.append('msg', text);
        fetch('chat_api.php', { method: 'POST', body: formData });
        msgInput.value = '';
    }

    // 💬 🔔 رادار الشات (نسخة واحدة فقط) مع الإشعارات والوميض الذكي!
    let lastMsgCount = 0; 
    setInterval(() => {
        fetch(`chat_api.php?action=fetch&tid=${window.targetTeacherId}`)
        .then(res => res.json())
        .then(data => {
            const chatBox = document.getElementById('messages');
            if(chatBox){
                chatBox.innerHTML = '';
                data.forEach(m => {
                    let isMe = (m.sender_name === realStudentName);
                    let align = isMe ? 'left' : 'right';
                    let bg = isMe ? '#e0f2fe' : '#f1f5f9';
                    let nameColor = m.sender_name.includes('الأستاذ') ? '#e11d48' : '#1e293b';
                    chatBox.innerHTML += `<div style="text-align:${align}; margin-bottom:8px;"><span style="display:inline-block; padding:8px 12px; background:${bg}; border-radius:10px; font-size:13px;"><b style="color:${nameColor};">${m.sender_name}:</b> <br>${m.message}</span></div>`;
                });
                chatBox.scrollTop = chatBox.scrollHeight; 

                // 🔔 إطلاق الوميض والاهتزاز إذا زاد عدد الرسائل (رسالة جديدة!)
                if (data.length > lastMsgCount && lastMsgCount !== 0) {
                    const chatBtn = document.querySelector('.chat-btn');
                    if (chatBtn) {
                        chatBtn.classList.add('raised'); // يجعل الزر يهتز ويضيء
                        setTimeout(() => { chatBtn.classList.remove('raised'); }, 4000); 
                    }
                }
                lastMsgCount = data.length; 
            }
        }).catch(e => {});
    }, 2000);

    function toggleHand() {
        alert("✋ تم تنبيه الأستاذ.");
        const formData = new FormData();
        formData.append('field', 'hand_raised');
        formData.append('value', 1);
        fetch(`waiting_room_api.php?action=update_state&sid=${studentId}&tid=${window.targetTeacherId}`, { method: 'POST', body: formData });
    }
    
    const msgInput = document.getElementById("msg");
    if(msgInput) msgInput.addEventListener("keyup", function(event) { if (event.key === "Enter") send(); });
</script>
<?php include __DIR__ . '/../dynamic_watermark.php'; ?>
</body>
</html>