<?php
// Set a specific response status code for form processing files
http_response_code(200);

// 1. Check if the request method is POST
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    // Redirect or display an error if the script is accessed directly
    header("Location: contact.php?status=error_access");
    exit();
}

// 2. Define the recipient email address for your messages
$to_email = "info@reliparcel.com";
$subject_prefix = "[CONTACT FORM] ";
$redirect_success = "contact.php?status=success";
$redirect_error = "contact.php?status=error";

// 3. Collect and Sanitize input data
// Use trim() to remove leading/trailing whitespace and htmlspecialchars() to prevent XSS
$name    = htmlspecialchars(trim($_POST['name'] ?? ''));
$email   = htmlspecialchars(trim($_POST['email'] ?? ''));
$subject = htmlspecialchars(trim($_POST['subject'] ?? ''));
$message = htmlspecialchars(trim($_POST['message'] ?? ''));

// 4. Basic Validation
if (empty($name) || empty($email) || empty($subject) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Redirect if required fields are missing or email is invalid
    header("Location: " . $redirect_error . "&msg=validation_failed");
    exit();
}

// 5. Construct the Email Body
$email_subject = $subject_prefix . $subject;
$email_body = "You have received a new message from your website contact form.\n\n";
$email_body .= "Name: $name\n";
$email_body .= "Email: $email\n";
$email_body .= "Subject: $subject\n";
$email_body .= "Message:\n$message\n";

// 6. Set Email Headers
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: " . $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

// 7. Save to Database
try {
    require_once 'config.php';
    $stmt = $pdo->prepare("INSERT INTO contact_messages (name, email, subject, message) VALUES (?, ?, ?, ?)");
    $stmt->execute([$name, $email, $subject, $message]);
} catch (PDOException $e) {
    // Log error or handle it silently for now
}

// 8. Send the Email (Mailing function disabled)
if (true || mail($to_email, $email_subject, $email_body, $headers)) {
    // Success: Redirect with a success message
    header("Location: " . $redirect_success);
} else {
    // Failure: Redirect with an error message
    header("Location: " . $redirect_error . "&msg=mail_failed");
}
exit();
?>