/** * TPU Survey - Public Survey Response Logic * รองรับ Section -> Heading -> Question */ let currentSurvey = null; async function initSurvey() { const params = new URLSearchParams(window.location.search); const link = params.get('link'); if (!link) { showError('ไม่พบลิงก์แบบสอบถาม'); return; } try { const data = await fetch(`/survey/api/surveys.php?action=getByLink&link=${encodeURIComponent(link)}`).then(r => r.json()); if (data.error) { showError(data.error); return; } currentSurvey = data.survey; renderSurvey(); } catch (err) { showError('ไม่สามารถโหลดแบบสอบถามได้'); } } function showError(msg) { document.getElementById('surveyContent').innerHTML = `
😔

${msg}

ลิงก์อาจไม่ถูกต้องหรือแบบสอบถามถูกปิดแล้ว

`; } function renderSurvey() { const container = document.getElementById('surveyContent'); let html = `
TPU Logo

${escapeHtml(currentSurvey.title)}

${currentSurvey.description ? `

${escapeHtml(currentSurvey.description)}

` : ''}
${currentSurvey.has_certificate == 1 ? `

🎓 ข้อมูลสำหรับรับเกียรติบัตร (ข้อมูลจำเป็น)

กรุณาระบุชื่อ-นามสกุลจริง และอีเมลมหาวิทยาลัยตาปี หรือ Gmail เพื่อระบบจะทำการส่งไฟล์เกียรติบัตรผ่านทางอีเมลโดยอัตโนมัติ

ชื่อ-นามสกุลจริง (ภาษาไทย เช่น นายสมชาย ใจดี) *
อีเมลสำหรับรับเกียรติบัตร (มหาวิทยาลัยตาปี หรือ Gmail) *
` : ''} `; (currentSurvey.sections || []).forEach(section => { const cleanSectionTitle = section.title.replace(/^ส่วนที่\s*[\d๑-๙]+\s*/, '').replace(/^\s*[\d๑-๙]+[\.\)\s\-:\u00A0]*\s*/, ''); html += `

${escapeHtml(cleanSectionTitle)}

${section.description ? `

${escapeHtml(section.description)}

` : ''}
`; // Render headings and their questions (section.headings || []).forEach(heading => { const cleanHeadingTitle = heading.title.replace(/^\s*[\d๑-๙]+[\.\)\s\-:\u00A0]*\s*/, ''); html += `

📑 ${escapeHtml(cleanHeadingTitle)}

${heading.description ? `

${escapeHtml(heading.description)}

` : ''}
`; (heading.questions || []).forEach(q => { html += renderQuestion(q); }); }); // Render loose questions (not in any heading) (section.questions || []).forEach(q => { html += renderQuestion(q); }); html += `
`; }); html += `
`; container.innerHTML = html; } function renderQuestion(q) { const cleanText = q.question_text.replace(/^\s*[\d๑-๙]+[\.\)\s\-:\u00A0]*\s*/, ''); let html = `
${escapeHtml(cleanText)} ${q.is_required ? '*' : ''}
`; if (q.description) { html += `

${escapeHtml(q.description)}

`; } if (q.question_type === 'radio') { if (q.options && q.options.length > 0) { html += `
`; q.options.forEach(opt => { html += ` `; }); html += `
`; } else { html += `
`; const labels = ['น้อยที่สุด', 'น้อย', 'ปานกลาง', 'มาก', 'มากที่สุด']; for (let i = 1; i <= 5; i++) { html += ` `; } html += `
`; } } else if (q.question_type === 'text') { html += ``; } else if (q.question_type === 'dropdown') { const options = q.options || []; html += ``; } else if (q.question_type === 'checkbox') { const options = q.options || []; html += `
`; options.forEach((opt, oi) => { const val = typeof opt === 'object' ? opt.value : opt; const label = typeof opt === 'object' ? opt.label : opt; html += ` `; }); html += `
`; } html += `
`; return html; } // Collect all questions flat for submission function getAllQuestions() { const questions = []; (currentSurvey.sections || []).forEach(section => { (section.headings || []).forEach(heading => { (heading.questions || []).forEach(q => questions.push(q)); }); (section.questions || []).forEach(q => questions.push(q)); }); return questions; } async function submitSurveyResponse(e) { e.preventDefault(); const btn = document.getElementById('submitBtn'); btn.disabled = true; btn.textContent = 'กำลังส่ง...'; const form = document.getElementById('surveyResponseForm'); const answers = []; const allQuestions = getAllQuestions(); allQuestions.forEach(q => { if (q.question_type === 'checkbox') { const values = []; form.querySelectorAll(`[name^="q_${q.id}_"]`).forEach(cb => { if (cb.checked) values.push(cb.value); }); answers.push({ question_id: q.id, value: values.join(', ') }); } else { const el = form.querySelector(`[name="q_${q.id}"]`); if (el) { if (el.type === 'radio') { const checked = form.querySelector(`[name="q_${q.id}"]:checked`); answers.push({ question_id: q.id, value: checked ? checked.value : '' }); } else { answers.push({ question_id: q.id, value: el.value }); } } } }); // Get respondent information const nameEl = document.getElementById('respondentName'); const emailEl = document.getElementById('respondentEmail'); const respondentName = nameEl ? nameEl.value.trim() : ''; const respondentEmail = emailEl ? emailEl.value.trim() : ''; const params = new URLSearchParams(window.location.search); try { const res = await fetch('/survey/api/responses.php?action=submit', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ survey_link: params.get('link'), answers: answers, respondent_info: { name: respondentName, email: respondentEmail } }) }); const data = await res.json(); if (data.success) { document.getElementById('surveyContent').innerHTML = `
TPU Logo
✓

ส่งแบบสอบถามสำเร็จ!

ขอบคุณที่สละเวลาตอบแบบสอบถาม

`; } else { throw new Error(data.error || 'เกิดข้อผิดพลาด'); } } catch (err) { alert('เกิดข้อผิดพลาด: ' + err.message); btn.disabled = false; btn.textContent = '📤 ส่งแบบสอบถาม'; } } function escapeHtml(text) { if (!text) return ''; const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } document.addEventListener('DOMContentLoaded', initSurvey);