isLoggedIn()) { throw new Exception('Unauthorized'); } $projectId = isset($_GET['project_id']) ? (int)$_GET['project_id'] : null; if (!$projectId) { throw new Exception('Project ID is 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'); } // Get surveys that are not already connected to this project // First, create a SQL query to get all active surveys that aren't already connected $sql = "SELECT s.* FROM surveys s LEFT JOIN project_surveys ps ON s.id = ps.survey_id AND ps.project_id = ? WHERE s.status = 'active' AND s.created_by = ? AND ps.id IS NULL ORDER BY s.created_at DESC"; $stmt = $db->prepare($sql); $stmt->bind_param('ii', $projectId, $_SESSION['user_id']); $stmt->execute(); $result = $stmt->get_result(); $surveys = []; while ($row = $result->fetch_assoc()) { // Add additional data to each survey $questionsCount = $db->query("SELECT COUNT(*) as count FROM survey_questions WHERE survey_id = " . $row['id'])->fetch_assoc()['count']; $tokensCount = $db->query("SELECT COUNT(*) as count FROM survey_tokens WHERE survey_id = " . $row['id'])->fetch_assoc()['count']; $responsesCount = $db->query("SELECT COUNT(*) as count FROM survey_tokens WHERE survey_id = " . $row['id'] . " AND is_completed = 1")->fetch_assoc()['count']; $row['questions_count'] = $questionsCount; $row['tokens_count'] = $tokensCount; $row['responses_count'] = $responsesCount; $surveys[] = $row; } echo json_encode([ 'success' => true, 'surveys' => $surveys ]); } catch (Exception $e) { echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } ?>