'Unauthorized']); exit; } $action = $_GET['action'] ?? ''; switch ($action) { case 'submissions_per_survey': $stmt = db()->query("SELECT s.title, COUNT(fs.id) as submission_count FROM surveys s LEFT JOIN feedback_submissions fs ON s.id = fs.survey_id GROUP BY s.id"); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $labels = array_column($results, 'title'); $values = array_column($results, 'submission_count'); echo json_encode(['labels' => $labels, 'values' => $values]); break; case 'survey_question_analytics': $surveys_stmt = db()->query("SELECT id, title FROM surveys"); $surveys = $surveys_stmt->fetchAll(PDO::FETCH_KEY_PAIR); $questions_stmt = db()->query("SELECT survey_id, id, question_text, question_type FROM survey_questions WHERE question_type = 'rating' OR question_type = 'multiple-choice'"); $questions = $questions_stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC); $answers_stmt = db()->query("SELECT q.id as question_id, a.answer_text FROM survey_answers a JOIN survey_questions q ON a.question_id = q.id WHERE q.question_type = 'rating' OR q.question_type = 'multiple-choice'"); $answers_by_question = $answers_stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN); $response = []; foreach ($surveys as $survey_id => $survey_title) { $survey_data = [ 'id' => $survey_id, 'title' => $survey_title, 'questions' => [] ]; if (isset($questions[$survey_id])) { foreach ($questions[$survey_id] as $question) { $question_id = $question['id']; $question_data = [ 'id' => $question_id, 'question_text' => $question['question_text'], 'type' => $question['question_type'], ]; $answers = $answers_by_question[$question_id] ?? []; if ($question['question_type'] == 'multiple-choice') { $answer_counts = []; foreach ($answers as $answer_row) { $options = preg_split('/,\s*/', $answer_row); foreach ($options as $option) { $trimmed_option = trim($option); if (!empty($trimmed_option)) { if (!isset($answer_counts[$trimmed_option])) { $answer_counts[$trimmed_option] = 0; } $answer_counts[$trimmed_option]++; } } } $question_data['answers'] = [ 'labels' => array_keys($answer_counts), 'values' => array_values($answer_counts) ]; } else { // rating $answer_counts = array_count_values($answers); $question_data['answers'] = [ 'labels' => array_keys($answer_counts), 'values' => array_values($answer_counts) ]; } $survey_data['questions'][] = $question_data; } } $response[] = $survey_data; } echo json_encode($response); break; default: echo json_encode(['error' => 'Invalid action']); break; }