34760-vm/submit_feedback.php
Flatlogic Bot 6255e8b900 charts
2025-10-07 22:38:32 +00:00

65 lines
2.9 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db/config.php';
$response = ['success' => 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($survey_id) || empty($answers)) {
$response['error'] = 'Please fill out all fields.';
} 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 (is_array($answer_text)) {
$answer_text = implode(', ', $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;
$safe_name = htmlspecialchars($name);
$safe_email = htmlspecialchars($email);
$htmlBody = "<p>A new submission has been received for the survey: <strong>{$survey_title}</strong></p>\n <p><strong>Submitter:</strong> {$safe_name} ({$safe_email})</p>\n <p><a href=\"{$submission_url}\">Click here to view the full submission.</a></p>";
$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);