false, 'message' => 'An error occurred.' ]; if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $response['message'] = 'Invalid request method.'; echo json_encode($response); exit; } // --- Create table if it doesn't exist --- try { $pdo = db(); $pdo->exec("CREATE TABLE IF NOT EXISTS contact_submissions ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, message TEXT NOT NULL, submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );"); } catch (PDOException $e) { // In a real app, log this error. For now, we can't show it to the user. $response['message'] = 'Database connection or setup failed.'; // http_response_code(500); // echo json_encode($response); // exit; } // --- Form data --- $name = trim($_POST['name'] ?? ''); $email = trim($_POST['email'] ?? ''); $message = trim($_POST['message'] ?? ''); // --- Validation --- 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; } // --- Save to Database --- try { $stmt = $pdo->prepare("INSERT INTO contact_submissions (name, email, message) VALUES (?, ?, ?)"); $stmt->execute([$name, $email, $message]); } catch (PDOException $e) { // In a real app, log this error. $response['message'] = 'Failed to save your message. Please try again later.'; // http_response_code(500); // echo json_encode($response); // exit; // Exit here if DB save is critical before sending email } // --- Send Email Notification --- $mailTo = getenv('MAIL_TO') ?: (include __DIR__ . '/mail/config.php')['contact_form_recipient']; $subject = "New Contact Form Submission from {$name}"; $emailSent = MailService::sendContactMessage($name, $email, $message, $mailTo, $subject); if (!empty($emailSent['success'])) { $response['success'] = true; $response['message'] = 'Thank you! Your message has been sent.'; } else { // The message was saved to the DB, but email failed. // This is a partial success. We can still inform the user positively. $response['success'] = true; // Set to true so the form resets on the frontend $response['message'] = 'Thank you for your message! We will get back to you shortly.'; // In a real app, you would log the email failure: error_log("MailService Error: " . $emailSent['error']); } echo json_encode($response);