'Missing survey_id'], 400); } // Check access $db = getDB(); if (!isAdmin()) { $stmt = $db->prepare("SELECT user_id FROM surveys WHERE id = ?"); $stmt->execute([$surveyId]); $survey = $stmt->fetch(); if (!$survey || $survey['user_id'] != $_SESSION['user_id']) { header('Content-Type: application/json; charset=utf-8'); jsonResponse(['error' => 'ไม่มีสิทธิ์'], 403); } } // Get statistics data $statsData = getStatsData($surveyId); switch ($action) { case 'pdf': exportPDF($statsData); break; case 'word': exportWord($statsData); break; default: header('Content-Type: application/json; charset=utf-8'); jsonResponse(['error' => 'Invalid action'], 400); } function getStatsData($surveyId) { $db = getDB(); // Survey info $stmt = $db->prepare("SELECT s.*, u.full_name as creator_name FROM surveys s LEFT JOIN users u ON s.user_id = u.id WHERE s.id = ?"); $stmt->execute([$surveyId]); $survey = $stmt->fetch(); // Total responses $stmt = $db->prepare("SELECT COUNT(*) as total FROM survey_responses WHERE survey_id = ?"); $stmt->execute([$surveyId]); $totalResponses = (int)$stmt->fetch()['total']; // Get sections with questions & stats $stmt = $db->prepare("SELECT * FROM survey_sections WHERE survey_id = ? ORDER BY section_number"); $stmt->execute([$surveyId]); $sections = $stmt->fetchAll(); foreach ($sections as &$section) { // Load headings $hStmt = $db->prepare("SELECT * FROM survey_headings WHERE section_id = ? ORDER BY order_num"); $hStmt->execute([$section['id']]); $headings = $hStmt->fetchAll(); $qStmt = $db->prepare("SELECT * FROM survey_questions WHERE section_id = ? ORDER BY order_num"); $qStmt->execute([$section['id']]); $questions = $qStmt->fetchAll(); foreach ($questions as &$q) { if ($q['question_type'] === 'radio' && empty($q['options'])) { $aStmt = $db->prepare(" SELECT answer_value, COUNT(*) as cnt FROM response_answers WHERE question_id = ? AND answer_value REGEXP '^[0-9]+$' GROUP BY answer_value "); $aStmt->execute([$q['id']]); $freqData = $aStmt->fetchAll(); $values = []; $freq = []; for ($i = 1; $i <= 5; $i++) $freq[$i] = 0; foreach ($freqData as $fd) { $val = (int)$fd['answer_value']; if ($val >= 1 && $val <= 5) { $freq[$val] = (int)$fd['cnt']; for ($j = 0; $j < (int)$fd['cnt']; $j++) $values[] = $val; } } $mean = count($values) > 0 ? array_sum($values) / count($values) : 0; $sd = 0; if (count($values) > 1) { $sumSq = 0; foreach ($values as $v) $sumSq += pow($v - $mean, 2); $sd = sqrt($sumSq / (count($values) - 1)); } $q['mean'] = round($mean, 2); $q['sd'] = round($sd, 2); $q['frequencies'] = $freq; $q['total_answers'] = count($values); if ($mean >= 4.51) $q['interpretation'] = 'มากที่สุด'; elseif ($mean >= 3.51) $q['interpretation'] = 'มาก'; elseif ($mean >= 2.51) $q['interpretation'] = 'ปานกลาง'; elseif ($mean >= 1.51) $q['interpretation'] = 'น้อย'; else $q['interpretation'] = 'น้อยที่สุด'; } elseif (in_array($q['question_type'], ['dropdown', 'checkbox', 'radio'])) { $aStmt = $db->prepare("SELECT answer_value, COUNT(*) as cnt FROM response_answers WHERE question_id = ? GROUP BY answer_value ORDER BY cnt DESC"); $aStmt->execute([$q['id']]); $q['frequencies'] = $aStmt->fetchAll(); } if ($q['question_type'] === 'text') { $aStmt = $db->prepare("SELECT answer_value FROM response_answers WHERE question_id = ? AND answer_value != ''"); $aStmt->execute([$q['id']]); $q['text_responses'] = array_column($aStmt->fetchAll(), 'answer_value'); } } unset($q); // Break the reference to prevent overwriting last element // Group questions by heading $looseQuestions = []; $headingQuestionsMap = []; foreach ($questions as $q) { if (!empty($q['heading_id'])) { $headingQuestionsMap[$q['heading_id']][] = $q; } else { $looseQuestions[] = $q; } } foreach ($headings as &$h) { $h['questions'] = $headingQuestionsMap[$h['id']] ?? []; } $section['headings'] = $headings; $section['questions'] = $looseQuestions; } return [ 'survey' => $survey, 'total_responses' => $totalResponses, 'sections' => $sections ]; } function generateHTML($data) { $survey = $data['survey']; $totalResponses = $data['total_responses']; $sections = $data['sections']; $html = '
'; $html .= ''; $html .= 'ผู้สร้าง: ' . htmlspecialchars($survey['creator_name'] ?? '') . '
'; $html .= 'จำนวนผู้ตอบ: ' . $totalResponses . ' คน
'; $html .= 'วันที่: ' . date('d/m/Y', strtotime($survey['created_at'])) . '
'; foreach ($sections as $section) { $cleanSectionTitle = preg_replace('/^ส่วนที่\s*[\d๑-๙]+\s*/u', '', $section['title']); $cleanSectionTitle = preg_replace('/^\s*[\d๑-๙]+[\.\)\s\-:\x{00A0}]*\s*/u', '', $cleanSectionTitle); $html .= '' . htmlspecialchars($heading['description']) . '
'; } $html .= renderQuestionsHTML($heading['questions']); } } } // Render loose questions if (!empty($section['questions'])) { $html .= renderQuestionsHTML($section['questions']); } } $html .= ''; return $html; } function renderQuestionsHTML($questions) { $html = ''; $hasRating = false; foreach ($questions as $q) { if ($q['question_type'] === 'radio' && empty($q['options'])) { $hasRating = true; break; } } if ($hasRating) { $html .= '| รายการประเมิน | ระดับความคิดเห็น (ความถี่) | X̄ | S.D. | แปลผล | ||||
|---|---|---|---|---|---|---|---|---|
| 5 | 4 | 3 | 2 | 1 | ||||
| ' . htmlspecialchars($cleanText) . ' | '; for ($i = 5; $i >= 1; $i--) { $html .= '' . ($q['frequencies'][$i] ?? 0) . ' | '; } $html .= '' . number_format($q['mean'] ?? 0, 2) . ' | '; $html .= '' . number_format($q['sd'] ?? 0, 2) . ' | '; $html .= '' . ($q['interpretation'] ?? '-') . ' | '; $html .= '||||
| รวมเฉลี่ย | '; $html .= ' | ' . number_format($avgMean, 2) . ' | '; $html .= '' . number_format($avgSD, 2) . ' | '; $html .= '' . $avgInterp . ' | '; $html .= '||||
' . htmlspecialchars($cleanText) . '
'; $html .= '| ตัวเลือก | ความถี่ | ร้อยละ |
|---|---|---|
| ' . htmlspecialchars($f['answer_value']) . ' | ' . $f['cnt'] . ' | ' . $percent . '% |
' . htmlspecialchars($cleanText) . '
'; foreach ($q['text_responses'] as $i => $text) { $html .= '