/** * TPU Survey - Teacher Dashboard Logic */ let teacherSurveys = []; async function initTeacher() { const loggedIn = await Auth.check(); if (!loggedIn || !Auth.isTeacher()) { if (Auth.isAdmin()) { window.location.href = 'admin.html'; return; } window.location.href = 'index.html'; return; } document.getElementById('userName').textContent = Auth.user.full_name; document.getElementById('userRole').textContent = 'อาจารย์ / เจ้าของโครงการ'; document.getElementById('userAvatar').textContent = Auth.user.full_name.charAt(0); showTeacherView('mySurveys'); } function showTeacherView(view) { document.querySelectorAll('.view-section').forEach(s => s.classList.add('hidden')); document.getElementById(`view-${view}`)?.classList.remove('hidden'); document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active')); document.querySelector(`.nav-item[data-view="${view}"]`)?.classList.add('active'); const titles = { mySurveys: 'แบบสอบถามของฉัน', profile: 'ข้อมูลส่วนตัว' }; document.getElementById('pageTitle').textContent = titles[view] || ''; if (view === 'mySurveys') loadTeacherSurveys(); else if (view === 'profile') loadProfile(); } async function loadTeacherSurveys() { try { const data = await API.get('surveys.php?action=list'); teacherSurveys = data.surveys || []; renderTeacherSurveys(); } catch (err) { Toast.error(err.message); } } function renderTeacherSurveys() { const container = document.getElementById('teacherSurveysList') || document.getElementById('teacherSurveysBody'); if (!container) return; if (teacherSurveys.length === 0) { const emptyHtml = `

ยังไม่มีแบบสอบถาม กดปุ่ม "สร้างแบบสอบถาม" เพื่อเริ่มต้น

`; if (container.tagName === 'TBODY') { container.innerHTML = `ยังไม่มีแบบสอบถาม กดปุ่ม "สร้างแบบสอบถาม" เพื่อเริ่มต้น`; } else { container.innerHTML = emptyHtml; } return; } const statusMap = { active: { label: 'เปิดใช้งาน', bg: 'bg-emerald-100 text-emerald-800 border-emerald-300' }, draft: { label: 'ฉบับร่าง', bg: 'bg-amber-100 text-amber-800 border-amber-300' }, closed: { label: 'ปิดแล้ว', bg: 'bg-rose-100 text-rose-800 border-rose-300' } }; container.innerHTML = teacherSurveys.map(s => { const st = statusMap[s.status] || { label: s.status || 'เปิดใช้งาน', bg: 'bg-emerald-100 text-emerald-800 border-emerald-300' }; return `
${st.label}

${escapeHtml(s.title)}

${s.response_count || 0} คำตอบ ${formatDate(s.created_at)}
`; }).join(''); } async function teacherDeleteSurvey(id, title) { if (!confirm(`คุณต้องการลบแบบสอบถาม "${title}" ใช่หรือไม่?`)) return; try { await API.get(`surveys.php?action=delete&id=${id}`); Toast.success('ลบแบบสอบถามเรียบร้อยแล้ว'); loadTeacherSurveys(); } catch (err) { Toast.error(err.message); } } function showTeacherCreateModal() { const html = `
`; const footer = ` `; Modal.create('สร้างแบบสอบถามใหม่', html, footer); document.querySelector('.modal-overlay:last-child').id = 'tCreateModal'; } async function submitTeacherCreate() { const form = document.getElementById('teacherSurveyForm'); const fd = new FormData(form); const data = Object.fromEntries(fd); if (!data.title) { Toast.warning('กรุณากรอกชื่อ'); return; } // Pre-fill 3 sections data.sections = [ { section_number: 1, title: 'ส่วนที่ ข้อมูลทั่วไป', category: 'general', questions: [ { question_text: 'เพศ', question_type: 'radio', options: ['ชาย', 'หญิง'], is_required: 1 }, { question_text: 'ช่วงอายุ', question_type: 'dropdown', options: ['18-25 ปี', '26-35 ปี', '36-45 ปี', '46-55 ปี', '56 ปีขึ้นไป'], is_required: 1 } ] }, { section_number: 2, title: 'ส่วนที่ การประเมินความพึงพอใจ', category: 'rating', questions: [ { question_text: 'ด้านเนื้อหาของการจัดโครงการ', question_type: 'radio', is_required: 1 }, { question_text: 'ด้านวิทยากร / ผู้บรรยาย', question_type: 'radio', is_required: 1 } ] }, { section_number: 3, title: 'ส่วนที่ ข้อเสนอแนะอื่นๆ', category: 'suggestions', questions: [ { question_text: 'ข้อเสนอแนะเพิ่มเติม', question_type: 'text', is_required: 0 } ] } ]; try { const result = await API.post('surveys.php?action=create', data); Toast.success('สร้างแบบสอบถามสำเร็จ'); Modal.hide('tCreateModal'); document.getElementById('tCreateModal').remove(); loadTeacherSurveys(); setTimeout(() => teacherEditSurvey(result.id), 500); } catch (err) { Toast.error(err.message); } } function teacherEditSurvey(id) { window.open(`edit.html?id=${id}`, '_blank'); } function buildTeacherQEditor(si, qi, q = {}) { const qType = q.question_type || 'radio'; const qText = q.question_text || ''; const qOptions = Array.isArray(q.options) ? q.options.join('\n') : ''; const showOptions = ['radio', 'checkbox', 'dropdown'].includes(qType); const qDescription = q.description || ''; return `
⋮⋮ คำถาม
เว้นว่างสำหรับระดับ 1-5 (Radio)
`; } function addTeacherSection() { const container = document.getElementById('additionalTeacherSections'); if (!container) return; const si = document.querySelectorAll('.card[data-section]').length; const html = `
`; container.insertAdjacentHTML('beforeend', html); // Add one initial question to the new section addTeacherQ(si); } function toggleTeacherOptions(select) { const group = select.closest('.question-builder').querySelector('.q-options-group'); if (['radio', 'checkbox', 'dropdown'].includes(select.value)) { group.style.display = 'block'; } else { group.style.display = 'none'; } } function addTeacherQ(si, afterEl = null) { const container = document.getElementById(`t-questions-${si}`); if (!container) return; // Create temporary div to parse HTML const tempDiv = document.createElement('div'); tempDiv.innerHTML = buildTeacherQEditor(si, 0); const newQ = tempDiv.firstElementChild; if (afterEl) { afterEl.after(newQ); } else { container.appendChild(newQ); } reindexTeacherQuestions(si); } function removeTeacherQ(btn, si) { if (!confirm('ยืนยันลบคำถามนี้?')) return; btn.closest('.question-builder').remove(); reindexTeacherQuestions(si); } function reindexTeacherQuestions(si) { const container = document.getElementById(`t-questions-${si}`); if (!container) return; container.querySelectorAll('.question-builder').forEach((qEl, idx) => { const label = qEl.querySelector('.q-number-label'); if (label) label.textContent = `คำถาม`; }); } async function submitTeacherEdit() { const form = document.getElementById('tEditForm'); const id = form.querySelector('[name="id"]').value; const title = form.querySelector('[name="title"]').value; const description = form.querySelector('[name="description"]').value; const sections = []; form.querySelectorAll('.card[data-section]').forEach((sectionEl, si) => { const sTitleInput = sectionEl.querySelector('input[data-field^="section-title"]'); const sCategorySelect = sectionEl.querySelector('select[data-field^="section-category"]'); const sTitle = sTitleInput ? sTitleInput.value : `ส่วนที่ ${si+1}`; const sCategory = sCategorySelect ? sCategorySelect.value : 'rating'; const questions = []; sectionEl.querySelectorAll('.question-builder').forEach((qEl, qi) => { const qTextInput = qEl.querySelector('.q-text-input'); const qDescInput = qEl.querySelector('.q-desc-input'); const qTypeSelect = qEl.querySelector('.q-type-select'); const qOptionsArea = qEl.querySelector('.q-options-input'); const qText = qTextInput ? qTextInput.value : ''; const qDescription = qDescInput ? qDescInput.value : ''; const qType = qTypeSelect ? qTypeSelect.value : 'radio'; const qOptionsRaw = qOptionsArea ? qOptionsArea.value : ''; const options = qOptionsRaw.split('\n').map(o => o.trim()).filter(o => o !== ''); if (qText.trim()) { questions.push({ question_text: qText.trim(), description: qDescription.trim() || null, question_type: qType, order_num: qi, is_required: 1, options: options.length > 0 ? options : null }); } }); sections.push({ section_number: si + 1, title: sTitle, category: sCategory, questions }); }); try { await API.post('surveys.php?action=update', { id: parseInt(id), title, description, sections }); Toast.success('บันทึกสำเร็จ'); Modal.hide('tEditModal'); document.getElementById('tEditModal').remove(); loadTeacherSurveys(); } catch (err) { Toast.error(err.message); } } async function teacherDuplicateSurvey(id) { if (!confirm('ยืนยันสร้างสำเนาแบบสอบถามนี้?')) return; try { await API.post('surveys.php?action=duplicate', { id }); Toast.success('คัดลอกสำเร็จ'); loadTeacherSurveys(); } catch (err) { Toast.error(err.message); } } async function teacherGenerateLink(id) { try { const data = await API.post('surveys.php?action=generateLink', { id }); const basePath = window.location.pathname.includes('/survey') ? '/survey' : ''; const fullUrl = data.full_url || `${window.location.origin}${basePath}/respond.php?link=${data.unique_link}`; // Find survey title const survey = teacherSurveys.find(s => s.id == id); const surveyTitle = survey ? survey.title : 'แบบสอบถาม'; const html = ` `; Modal.create('🔗 ลิงก์และ QR Code', html, '', 'modal-lg'); // Generate QR Code using QRCodeJS setTimeout(() => { const container = document.getElementById('qrCodeContainer'); if (container && typeof QRCode !== 'undefined') { new QRCode(container, { text: fullUrl, width: 280, height: 280, colorDark: '#1e3a8a', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.H }); } }, 100); } catch (err) { Toast.error(err.message); } } function copyTeacherLink(btnEl) { const text = document.getElementById('surveyLinkText')?.textContent?.trim(); if (text) { const btn = btnEl || document.querySelector('.link-display .copy-btn'); copyTextToClipboard(text, btn); } } function getTeacherQRImage() { const container = document.getElementById('qrCodeContainer'); if (!container) return null; return container.querySelector('canvas') || container.querySelector('img'); } function teacherDownloadQR() { const qrEl = getTeacherQRImage(); const title = document.getElementById('qrSurveyTitle')?.textContent || 'survey'; if (!qrEl) return; let qrDataUrl; if (qrEl.tagName === 'CANVAS') { qrDataUrl = qrEl.toDataURL('image/png'); } else { qrDataUrl = qrEl.src; } const exportCanvas = document.createElement('canvas'); const qrSize = 280; const padding = 40; const titleHeight = 60; const footerHeight = 40; exportCanvas.width = qrSize + padding * 2; exportCanvas.height = qrSize + padding * 2 + titleHeight + footerHeight; const ctx = exportCanvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, exportCanvas.width, exportCanvas.height); ctx.fillStyle = '#1a1a2e'; ctx.font = 'bold 16px sans-serif'; ctx.textAlign = 'center'; const maxTitleWidth = exportCanvas.width - 40; let displayTitle = title; if (ctx.measureText(displayTitle).width > maxTitleWidth) { while (ctx.measureText(displayTitle + '...').width > maxTitleWidth && displayTitle.length > 0) { displayTitle = displayTitle.slice(0, -1); } displayTitle += '...'; } ctx.fillText(displayTitle, exportCanvas.width / 2, padding + 20); const img = new Image(); img.onload = function() { ctx.drawImage(img, padding, padding + titleHeight, qrSize, qrSize); ctx.fillStyle = '#6b7280'; ctx.font = '12px sans-serif'; ctx.fillText('สแกนเพื่อตอบแบบสอบถาม — TPU Survey', exportCanvas.width / 2, exportCanvas.height - 16); const link = document.createElement('a'); const safeName = title.replace(/[^a-zA-Z0-9ก-๙]/g, '_').substring(0, 50); link.download = `QR_${safeName}.png`; link.href = exportCanvas.toDataURL('image/png'); link.click(); Toast.success('ดาวน์โหลด QR Code สำเร็จ'); }; img.src = qrDataUrl; } function teacherPrintQR() { const qrEl = getTeacherQRImage(); const title = document.getElementById('qrSurveyTitle')?.textContent || 'แบบสอบถาม'; const linkText = document.getElementById('surveyLinkText')?.textContent || ''; if (!qrEl) return; let qrDataUrl; if (qrEl.tagName === 'CANVAS') { qrDataUrl = qrEl.toDataURL('image/png'); } else { qrDataUrl = qrEl.src; } const printWindow = window.open('', '_blank'); printWindow.document.write(` พิมพ์ QR Code

${title}

สแกน QR Code เพื่อตอบแบบสอบถาม