35089-vm/contact_handler.php
Flatlogic Bot e7d7877d01 first
2025-10-21 23:13:27 +00:00

57 lines
2.2 KiB
PHP

<?php
ini_set('display_errors', 0); // Do not display errors to the user
header('Content-Type: application/json');
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/mail/MailService.php';
$response = ['success' => false];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$message = trim($_POST['message'] ?? '');
// Server-side validation
if (empty($name) || empty($email) || empty($message)) {
$response['error'] = 'Please fill out all fields.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response['error'] = 'Please provide a valid email address.';
} 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
// The recipient email address should be configured in the .env file (MAIL_TO)
// For this example, we let the MailService use its default.
$mailResult = MailService::sendContactMessage($name, $email, $message);
if (!empty($mailResult['success'])) {
$response['success'] = true;
} else {
// Log the error, but don't expose it to the client
error_log('MailService Error: ' . ($mailResult['error'] ?? 'Unknown error'));
// Even if email fails, we saved the submission, so we can consider it a partial success.
// For the user, we'll report full success as their data is captured.
$response['success'] = true;
}
} catch (PDOException $e) {
error_log('Database Error: ' . $e->getMessage());
$response['error'] = 'A server error occurred. Please try again later.';
} catch (Exception $e) {
error_log('General Error: ' . $e->getMessage());
$response['error'] = 'A server error occurred. Please try again later.';
}
}
} else {
$response['error'] = 'Invalid request method.';
}
echo json_encode($response);