isLoggedIn()) { throw new Exception('Unauthorized'); } $surveyId = isset($_POST['survey_id']) ? (int)$_POST['survey_id'] : null; $projectId = isset($_POST['project_id']) ? (int)$_POST['project_id'] : null; $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : null; if (!$surveyId || !$projectId) { throw new Exception('Survey ID and Project ID are required'); } $db = Database::getInstance(); // Check if the project exists and user has access $stmt = $db->prepare("SELECT id FROM projects WHERE id = ? AND created_by = ?"); $stmt->bind_param('ii', $projectId, $_SESSION['user_id']); $stmt->execute(); if ($stmt->get_result()->num_rows == 0) { throw new Exception('Project not found or access denied'); } // Check if the survey exists and user has access $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('Survey not found or access denied'); } // Check if already connected $stmt = $db->prepare("SELECT id FROM project_surveys WHERE project_id = ? AND survey_id = ?"); $stmt->bind_param('ii', $projectId, $surveyId); $stmt->execute(); if ($stmt->get_result()->num_rows > 0) { throw new Exception('Survey is already connected to this project'); } // Remove any existing connections for this project first (since only one survey can be connected) $stmt = $db->prepare("DELETE FROM project_surveys WHERE project_id = ?"); $stmt->bind_param('i', $projectId); $stmt->execute(); // Connect survey to project $stmt = $db->prepare("INSERT INTO project_surveys (project_id, survey_id, created_by) VALUES (?, ?, ?)"); $stmt->bind_param('iii', $projectId, $surveyId, $_SESSION['user_id']); if (!$stmt->execute()) { throw new Exception('Failed to connect survey to project'); } // Handle redirect or JSON response if ($redirect) { // Set a success message in session $_SESSION['success_message'] = 'Survey connected successfully'; redirectTo($redirect); exit; } else { // Return JSON response header('Content-Type: application/json'); echo json_encode([ 'success' => true, 'message' => 'Survey connected successfully' ]); } } catch (Exception $e) { if (isset($_POST['redirect'])) { // Set error message in session $_SESSION['error_message'] = $e->getMessage(); redirectTo($_POST['redirect']); exit; } else { // Return JSON error header('Content-Type: application/json'); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } } ?>