// js/modules/attendance_manager.js
const AttendanceModule = {
    init: function() {
        this.createWindow();
        setInterval(() => this.refreshData(), 3000);
    },

    createWindow: function() {
        if (document.getElementById('attendance-floating-window')) return;
        const div = document.createElement('div');
        div.id = 'attendance-floating-window';
        div.className = 'floating-attendance-window';
        div.style.display = 'none';
        div.style.position = 'fixed';
        div.style.zIndex = '999999';
        div.innerHTML = `
            <div class="att-header" id="att-drag-handle" style="cursor: move; background: #6b1024; color: white; padding: 10px; display: flex; justify-content: space-between;">
                <span>👥 قائمة الحضور الفعلي</span>
                <span style="cursor:pointer" onclick="AttendanceModule.toggleWindow()">✖</span>
            </div>
            <div class="att-body" id="att-content" style="padding: 10px; background: white; border: 1px solid #6b1024; max-height: 400px; overflow-y: auto;">
                <div id="students-container">
                    <p style="text-align:center; color:#94a3b8;">جاري تحميل الطلاب...</p>
                </div>
            </div>
        `;
        document.body.appendChild(div);
        this.makeDraggable(div, document.getElementById('att-drag-handle'));
    },

    toggleWindow: function() {
        const win = document.getElementById('attendance-floating-window');
        win.style.display = (win.style.display === 'flex') ? 'none' : 'flex';
        if (win.style.display === 'flex') this.refreshData();
    },

    refreshData: function() {
        const urlParams = new URLSearchParams(window.location.search);
        const tid = urlParams.get('tid') || localStorage.getItem('roozmari_teacher_id') || '0';
        
        fetch(`../zoom_api/waiting_room_api.php?action=get_pending&tid=${tid}`)
        .then(res => res.json())
        .then(data => {
            const container = document.getElementById('students-container');
            if (!container) return;
            const accepted = data.accepted || [];
            
            if (accepted.length === 0) {
                container.innerHTML = '<p style="text-align:center; color:#94a3b8; padding:20px;">لا يوجد طلاب منضمين</p>';
                return;
            }
            
            let html = '';
            accepted.forEach(student => {
                const micIcon = student.can_mic == 1 ? 'fa-microphone' : 'fa-microphone-slash';
                const camIcon = student.can_cam == 1 ? 'fa-video' : 'fa-video-slash';
                const drawIcon = student.can_draw == 1 ? 'fa-pen-nib' : 'fa-pen';
                
                const micBtnStyle = student.can_mic == 1 ? 'background:#22c55e;' : 'background:#64748b;';
                const camBtnStyle = student.can_cam == 1 ? 'background:#22c55e;' : 'background:#64748b;';
                const drawBtnStyle = student.can_draw == 1 ? 'background:#22c55e;' : 'background:#64748b;';

                html += `
                <div style="display:flex; justify-content:space-between; align-items:center; padding:8px; border-bottom:1px solid #f1f5f9;">
                    <span style="font-weight:bold; font-size:13px; color:#1e293b;">${student.student_name || 'طالب'}</span>
                    <div style="display:flex; gap:4px;">
                        <button onclick="AttendanceModule.performAction('${student.student_id}', 'can_mic', ${student.can_mic == 1 ? 0 : 1})" style="${micBtnStyle} color:white; border:none; width:28px; height:28px; border-radius:4px; cursor:pointer;" title="مايك"><i class="fas ${micIcon}"></i></button>
                        <button onclick="AttendanceModule.performAction('${student.student_id}', 'can_cam', ${student.can_cam == 1 ? 0 : 1})" style="${camBtnStyle} color:white; border:none; width:28px; height:28px; border-radius:4px; cursor:pointer;" title="كاميرا"><i class="fas ${camIcon}"></i></button>
                        <button onclick="AttendanceModule.performAction('${student.student_id}', 'can_draw', ${student.can_draw == 1 ? 0 : 1})" style="${drawBtnStyle} color:white; border:none; width:28px; height:28px; border-radius:4px; cursor:pointer;" title="رسم"><i class="fas ${drawIcon}"></i></button>
                        <button onclick="AttendanceModule.kickStudent('${student.student_id}')" style="background:#ef4444; color:white; border:none; width:28px; height:28px; border-radius:4px; cursor:pointer;" title="طرد"><i class="fas fa-user-times"></i></button>
                    </div>
                </div>`;
            });
            container.innerHTML = html;
        }).catch(err => console.error("خطأ في جلب البيانات:", err));
    },

    performAction: function(sid, field, value) {
        const urlParams = new URLSearchParams(window.location.search);
        const tid = urlParams.get('tid') || localStorage.getItem('roozmari_teacher_id') || '0';
        
        let formData = new FormData();
        formData.append('field', field);
        formData.append('value', value);
        
        fetch(`../zoom_api/waiting_room_api.php?action=update_state&sid=${sid}&tid=${tid}`, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            console.log("رد السيرفر على التعديل:", data);
            if (data.success) {
                this.refreshData(); // تحديث الأيقونات فوراً
            }
        }).catch(err => console.error("خطأ في إرسال الأمر:", err));
    },

    kickStudent: function(sid) {
        if(confirm("هل أنت متأكد من طرد هذا الطالب؟")) {
            this.performAction(sid, 'is_kicked', 1);
        }
    },

    endBroadcast: function() {
        const urlParams = new URLSearchParams(window.location.search);
        const tid = urlParams.get('tid') || localStorage.getItem('roozmari_teacher_id') || '0';
        
        fetch(`../zoom_api/waiting_room_api.php?action=end_broadcast&tid=${tid}`)
        .then(() => {
            alert("تم إنهاء البث ومسح قائمة الحضور.");
            window.location.reload();
        });
    },

    makeDraggable: function(el, handle) {
        let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
        handle.onmousedown = (e) => {
            e.preventDefault();
            pos3 = e.clientX; pos4 = e.clientY;
            document.onmouseup = () => { document.onmouseup = null; document.onmousemove = null; };
            document.onmousemove = (e) => {
                pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY;
                pos3 = e.clientX; pos4 = e.clientY;
                el.style.position = 'fixed';
                el.style.top = (el.offsetTop - pos2) + "px";
                el.style.left = (el.offsetLeft - pos1) + "px";
                el.style.bottom = "auto"; el.style.right = "auto";
            };
        };
    }
};