65 lines
2.1 KiB
PHP
65 lines
2.1 KiB
PHP
<?php
|
|
// Basic security: disable direct access
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
|
|
require_once __DIR__ . '/db/config.php';
|
|
require_once __DIR__ . '/mail/MailService.php';
|
|
|
|
// --- Form data ---
|
|
$name = trim($_POST['name'] ?? '');
|
|
$email = trim($_POST['email'] ?? '');
|
|
$message = trim($_POST['message'] ?? '');
|
|
|
|
// --- Validation ---
|
|
if (empty($name) || empty($email) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
header('Location: index.php?status=validation_error#contact');
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
// --- Database Persistence ---
|
|
$pdo = db(); // Get PDO instance from db/config.php
|
|
|
|
// Idempotent table creation
|
|
$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,
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
)");
|
|
|
|
// Insert the new submission
|
|
$stmt = $pdo->prepare("INSERT INTO contact_submissions (name, email, message) VALUES (?, ?, ?)");
|
|
$stmt->execute([$name, $email, $message]);
|
|
|
|
// --- Email Notification ---
|
|
// The recipient email address. If null, MailService will use MAIL_TO from .env
|
|
$recipient = null;
|
|
$subject = "New Contact Form Submission from " . htmlspecialchars($name);
|
|
|
|
$mailResult = MailService::sendContactMessage($name, $email, $message, $recipient, $subject);
|
|
|
|
if (!empty($mailResult['success'])) {
|
|
header('Location: index.php?status=success#contact');
|
|
} else {
|
|
// Log error if you have a logging system
|
|
// error_log("Mail sending failed: " . $mailResult['error']);
|
|
header('Location: index.php?status=error#contact');
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
// Log database error
|
|
// error_log("Database error: " . $e->getMessage());
|
|
header('Location: index.php?status=error#contact');
|
|
exit;
|
|
} catch (Exception $e) {
|
|
// Log other errors (e.g., mailer)
|
|
// error_log("General error: " . $e->getMessage());
|
|
header('Location: index.php?status=error#contact');
|
|
exit;
|
|
}
|