false, 'error' => 'Invalid request']; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = trim($_POST['name'] ?? ''); $email = trim($_POST['email'] ?? ''); $survey_id = trim($_POST['survey_id'] ?? ''); $answers = $_POST['answers'] ?? []; if (empty($name) || empty($email) || empty($survey_id) || empty($answers)) { $response['error'] = 'Please fill out all fields.'; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $response['error'] = 'Invalid email format.'; } else { $pdo = db(); try { $pdo->beginTransaction(); // Insert into feedback_submissions $stmt = $pdo->prepare("INSERT INTO feedback_submissions (name, email, survey_id) VALUES (?, ?, ?)"); $stmt->execute([$name, $email, $survey_id]); $submission_id = $pdo->lastInsertId(); // Insert into survey_answers $answer_stmt = $pdo->prepare("INSERT INTO survey_answers (submission_id, question_id, answer_text) VALUES (?, ?, ?)"); foreach ($answers as $question_id => $answer_text) { if (!empty($answer_text)) { $answer_stmt->execute([$submission_id, $question_id, $answer_text]); } } $pdo->commit(); $response['success'] = true; unset($response['error']); // Send email notification require_once __DIR__ . '/mail/MailService.php'; $survey_stmt = $pdo->prepare("SELECT title FROM surveys WHERE id = ?"); $survey_stmt->execute([$survey_id]); $survey_title = $survey_stmt->fetchColumn(); $subject = "New Submission for Survey: " . $survey_title; $submission_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . '/view_submission.php?id=' . $submission_id; $htmlBody = "

A new submission has been received for the survey: {$survey_title}

\n

Submitter: {$name} ({$email})

\n

Click here to view the full submission.

"; $textBody = "A new submission has been received for the survey: {$survey_title}. Submitter: {$name} ({$email}). View the submission here: {$submission_url}"; MailService::sendMail(null, $subject, $htmlBody, $textBody); } catch (PDOException $e) { $pdo->rollBack(); error_log($e->getMessage()); $response['error'] = 'Database error. Could not submit feedback.'; } } } echo json_encode($response);