30971-vm/contact.php
Flatlogic Bot f2c0bb39c0 v1
2025-10-16 13:19:27 +00:00

60 lines
2.3 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/mail/MailService.php';
// Run migrations to ensure table exists
try {
run_migrations();
} catch (Exception $e) {
// Log error but don't block execution if table already exists
error_log('Migration failed: ' . $e->getMessage());
}
$response = ['success' => false, 'error' => 'Invalid request'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
if (empty($name) || empty($email) || empty($message)) {
$response['error'] = 'Please fill in all fields.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response['error'] = 'Invalid email format.';
} else {
try {
// 1. Save to database
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO contact_submissions (name, email, message) VALUES (?, ?, ?)");
$stmt->execute([$name, $email, $message]);
// 2. Send email notification
$mail_to = getenv('MAIL_TO') ?: 'owner@example.com'; // Fallback email
$subject = 'New Contact Form Submission from ' . $name;
$email_body = "You have a new message from your website contact form.\n\n" .
"Name: {$name}\n" .
"Email: {$email}\n" .
"Message:\n{$message}";
MailService::sendMail($mail_to, $subject, nl2br(htmlspecialchars($email_body)), $email_body, ['reply_to' => $email]);
$response['success'] = true;
unset($response['error']);
} catch (PDOException $e) {
error_log('Database Error: ' . $e->getMessage());
$response['error'] = 'Could not save your message. Please try again later.';
} catch (Exception $e) {
error_log('Mail Error: ' . $e->getMessage());
// The message was saved to DB, so we can consider this a partial success.
// For the user, it's a full success, but we log the mail error.
$response['success'] = true;
unset($response['error']);
}
}
}
echo json_encode($response);