isLoggedIn()) { throw new Exception('Unauthorized'); } // Get input data $input = json_decode(file_get_contents('php://input'), true); if (!isset($input['question_id'])) { throw new Exception('Question ID is required'); } $questionId = (int)$input['question_id']; $db = Database::getInstance(); // Get survey ID for this question $stmt = $db->prepare("SELECT survey_id FROM survey_questions WHERE id = ?"); $stmt->bind_param('i', $questionId); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 0) { throw new Exception('Question not found'); } $surveyId = $result->fetch_assoc()['survey_id']; // 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'); } // Delete the question $stmt = $db->prepare("DELETE FROM survey_questions WHERE id = ?"); $stmt->bind_param('i', $questionId); if (!$stmt->execute()) { throw new Exception('Failed to delete question'); } // Reorder remaining questions $stmt = $db->prepare(" SET @rank = 0; UPDATE survey_questions SET question_order = @rank := @rank + 1 WHERE survey_id = ? ORDER BY question_order "); $stmt->bind_param('i', $surveyId); $stmt->execute(); echo json_encode([ 'success' => true, 'message' => 'Question deleted successfully' ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } ?>