false, 'error' => 'An unknown error occurred.']; 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 out all fields.'; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $response['error'] = 'Please provide a valid email address.'; } else { $subject = 'New Contact Form Submission from ' . htmlspecialchars($name); // Using MailService to send the contact message. // The user's email is automatically set as the Reply-To address. // The recipient is determined by the MailService configuration (defaults to MAIL_TO in .env). $result = MailService::sendContactMessage($name, $email, $message, null, $subject); if (!empty($result['success'])) { $response['success'] = true; unset($response['error']); } else { // For security, we don't expose detailed mailer errors to the client. // The error is logged on the server for debugging. error_log('MailService Error: ' . ($result['error'] ?? 'Unknown error while sending email.')); $response['error'] = 'Sorry, there was an issue sending your message. Please try again later.'; } } } else { http_response_code(405); // Method Not Allowed $response['error'] = 'Invalid request method.'; } echo json_encode($response);