57 lines
1.8 KiB
PHP
57 lines
1.8 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
|
|
require_once __DIR__ . '/db/config.php';
|
|
require_once __DIR__ . '/mail/MailService.php';
|
|
|
|
$response = ['success' => false, 'message' => 'An unexpected error occurred.'];
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
$response['message'] = 'Invalid request method.';
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
$name = trim($_POST['name'] ?? '');
|
|
$email = trim($_POST['email'] ?? '');
|
|
$message = trim($_POST['message'] ?? '');
|
|
|
|
if (empty($name) || empty($email) || empty($message)) {
|
|
$response['message'] = 'Please fill out all fields.';
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
$response['message'] = 'Invalid email format.';
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("INSERT INTO contact_submissions (name, email, message) VALUES (?, ?, ?)");
|
|
$stmt->execute([$name, $email, $message]);
|
|
|
|
// Send email notification
|
|
$mailResult = MailService::sendContactMessage($name, $email, $message);
|
|
|
|
if ($mailResult['success']) {
|
|
$response['success'] = true;
|
|
$response['message'] = 'Message sent successfully!';
|
|
} else {
|
|
// Still a success for the user, but log the email error
|
|
error_log("MailService Error: " . ($mailResult['error'] ?? 'Unknown error'));
|
|
$response['success'] = true;
|
|
$response['message'] = 'Message saved, but could not send notification email.';
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
error_log("Database Error: " . $e->getMessage());
|
|
$response['message'] = 'Error saving your message to the database.';
|
|
} catch (Exception $e) {
|
|
error_log("General Error: " . $e->getMessage());
|
|
$response['message'] = 'An unexpected error occurred.';
|
|
}
|
|
|
|
echo json_encode($response); |