isLoggedIn()) { throw new Exception('Unauthorized'); } // Get input data $input = json_decode(file_get_contents('php://input'), true); if (!isset($input['question_id']) || !isset($input['direction'])) { throw new Exception('Missing required parameters'); } $questionId = (int)$input['question_id']; $direction = $input['direction']; if (!in_array($direction, ['up', 'down'])) { throw new Exception('Invalid direction'); } $db = Database::getInstance(); // Get question details $stmt = $db->prepare("SELECT * FROM survey_questions WHERE id = ?"); $stmt->bind_param('i', $questionId); $stmt->execute(); $question = $stmt->get_result()->fetch_assoc(); if (!$question) { throw new Exception('Question not found'); } $surveyId = $question['survey_id']; $currentOrder = $question['question_order']; // Verify user has access to this survey $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'); } // Find the question to swap with if ($direction === 'up') { $sql = "SELECT * FROM survey_questions WHERE survey_id = ? AND question_order < ? ORDER BY question_order DESC LIMIT 1"; } else { $sql = "SELECT * FROM survey_questions WHERE survey_id = ? AND question_order > ? ORDER BY question_order ASC LIMIT 1"; } $stmt = $db->prepare($sql); $stmt->bind_param('ii', $surveyId, $currentOrder); $stmt->execute(); $targetQuestion = $stmt->get_result()->fetch_assoc(); if (!$targetQuestion) { echo json_encode([ 'success' => true, 'message' => 'No change needed' ]); exit; } // Swap order values $targetOrder = $targetQuestion['question_order']; $db->query("START TRANSACTION"); $stmt = $db->prepare("UPDATE survey_questions SET question_order = ? WHERE id = ?"); $stmt->bind_param('ii', $targetOrder, $questionId); $stmt->execute(); $stmt = $db->prepare("UPDATE survey_questions SET question_order = ? WHERE id = ?"); $stmt->bind_param('ii', $currentOrder, $targetQuestion['id']); $stmt->execute(); $db->query("COMMIT"); echo json_encode([ 'success' => true, 'message' => 'Question moved successfully' ]); } catch (Exception $e) { if (isset($db) && $db->inTransaction()) { $db->query("ROLLBACK"); } echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>