isLoggedIn()) { throw new Exception('Unauthorized'); } // Get and validate input $surveyId = isset($_POST['survey_id']) ? (int)$_POST['survey_id'] : null; $questionId = isset($_POST['question_id']) ? (int)$_POST['question_id'] : null; $questionType = isset($_POST['questionType']) ? $_POST['questionType'] : null; $questionText = isset($_POST['questionText']) ? trim($_POST['questionText']) : null; $helpText = isset($_POST['helpText']) ? trim($_POST['helpText']) : ''; $isRequired = isset($_POST['isRequired']) ? 1 : 0; if (!$surveyId || !$questionType || !$questionText) { throw new Exception('Missing required fields'); } // Verify user has access to this survey $db = Database::getInstance(); $stmt = $db->prepare("SELECT id FROM surveys WHERE id = ? AND created_by = ?"); $stmt->bind_param('ii', $surveyId, $_SESSION['user_id']); $stmt->execute(); if ($stmt->get_result()->num_rows === 0) { throw new Exception('Access denied'); } // Process options for choice questions $options = null; if (in_array($questionType, ['single_choice', 'multiple_choice', 'dropdown'])) { $options = $_POST['options'] ?? null; } // Process configuration $config = $_POST['config'] ?? null; // Get max order for new questions $questionOrder = 0; if (!$questionId) { $sql = "SELECT MAX(question_order) as max_order FROM survey_questions WHERE survey_id = ?"; $stmt = $db->prepare($sql); $stmt->bind_param('i', $surveyId); $stmt->execute(); $result = $stmt->get_result()->fetch_assoc(); $questionOrder = ($result['max_order'] ?? 0) + 1; } if ($questionId) { // Update existing question $sql = "UPDATE survey_questions SET question_text = ?, question_type = ?, help_text = ?, options = ?, config = ?, is_required = ? WHERE id = ? AND survey_id = ?"; $stmt = $db->prepare($sql); $stmt->bind_param('sssssiis', $questionText, $questionType, $helpText, $options, $config, $isRequired, $questionId, $surveyId ); } else { // Create new question $sql = "INSERT INTO survey_questions (survey_id, question_text, question_type, help_text, options, config, is_required, question_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $stmt = $db->prepare($sql); $stmt->bind_param('isssssii', $surveyId, $questionText, $questionType, $helpText, $options, $config, $isRequired, $questionOrder ); } if (!$stmt->execute()) { throw new Exception("Failed to save question: " . $db->getLastError()); } $newId = $questionId ?: $db->getLastInsertId(); echo json_encode([ 'success' => true, 'question_id' => $newId, 'message' => 'Question saved successfully' ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>