isLoggedIn()) { throw new Exception('Unauthorized'); } $surveyId = isset($_GET['survey_id']) ? (int)$_GET['survey_id'] : null; $questionId = isset($_GET['question_id']) ? (int)$_GET['question_id'] : null; if (!$surveyId) { throw new Exception('Survey ID is required'); } $db = Database::getInstance(); // Check if survey exists and user has access $stmt = $db->prepare("SELECT * FROM surveys WHERE id = ? AND created_by = ?"); $stmt->bind_param('ii', $surveyId, $_SESSION['user_id']); $stmt->execute(); $survey = $stmt->get_result()->fetch_assoc(); if (!$survey) { throw new Exception('Survey not found or access denied'); } // Get questions if ($questionId) { // Get specific question $stmt = $db->prepare("SELECT * FROM survey_questions WHERE id = ? AND survey_id = ?"); $stmt->bind_param('ii', $questionId, $surveyId); $stmt->execute(); $question = $stmt->get_result()->fetch_assoc(); if (!$question) { throw new Exception('Question not found'); } // Parse JSON fields if (!empty($question['options'])) { $question['options'] = json_decode($question['options'], true); } if (!empty($question['config'])) { $question['config'] = json_decode($question['config'], true); } echo json_encode([ 'success' => true, 'question' => $question ]); } else { // Get all questions $stmt = $db->prepare("SELECT * FROM survey_questions WHERE survey_id = ? ORDER BY question_order ASC"); $stmt->bind_param('i', $surveyId); $stmt->execute(); $result = $stmt->get_result(); $questions = []; while ($question = $result->fetch_assoc()) { // Parse JSON fields if (!empty($question['options'])) { $question['options'] = json_decode($question['options'], true); } if (!empty($question['config'])) { $question['config'] = json_decode($question['config'], true); } $questions[] = $question; } echo json_encode([ 'success' => true, 'questions' => $questions ]); } } catch (Exception $e) { echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>