/**
* 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 basePath = window.location.pathname.includes('/survey') ? '/survey' : '';
const data = await fetch(`${basePath}/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 = `
${escapeHtml(q.question_text)}
${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 basePath = window.location.pathname.includes('/survey') ? '/survey' : '';
const res = await fetch(`${basePath}/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 = `
✓
ส่งแบบสอบถามสำเร็จ!
ขอบคุณที่สละเวลาตอบแบบสอบถาม
`;
} 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);