<?php
// Simple and reliable email handler based on the successful test
$success = false;
$errorMessage = '';

// Log all incoming requests
error_log("Email form submission received at " . date('Y-m-d H:i:s'));
error_log("REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);

// Process form data from either GET or POST
$data = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

// Sanitize and validate inputs
$name = isset($data['name']) ? htmlspecialchars($data['name']) : '';
$email = isset($data['email']) ? filter_var($data['email'], FILTER_SANITIZE_EMAIL) : '';
$phone = isset($data['phone']) ? htmlspecialchars($data['phone']) : '';
$message = isset($data['message']) ? htmlspecialchars($data['message']) : '';
$subjectField = isset($data['subject']) ? htmlspecialchars($data['subject']) : '';

// Log the received data
error_log("Form data received - Name: $name, Email: $email, Phone: $phone");

// Basic validation
if (empty($name) || empty($email) || empty($message) || empty($subjectField)) {
    $errorMessage = 'Bitte füllen Sie alle Pflichtfelder aus.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errorMessage = 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
} else {
    // Format the email body
    $emailBody = $message;
    if (!empty($phone)) {
        $emailBody .= "\n\nTelefonnummer: $phone";
    }
    
    // Email details
    $to = "kontakt@luftglanz.de";
    $subject = $subjectField ?: "Neue Kontaktanfrage von $name";
    $headers = "From: $name <luftglanz@egonetix.de>\r\n";
    $headers .= "Reply-To: $name <$email>\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    
    // Send the email using the mail() function that we confirmed works
    $success = mail($to, $subject, $emailBody, $headers);
    
    if (!$success) {
        $errorMessage = 'Es gab ein Problem beim Senden Ihrer Nachricht. Bitte versuchen Sie es später erneut.';
        error_log("Mail sending failed for $email");
    } else {
        error_log("Email sent successfully to $to from $email");
    }
}

// Redirect back to the form with status
if ($success) {
    header('Location: index.html?form_success=1#contact');
} else {
    header('Location: index.html?form_error=' . urlencode($errorMessage) . '#contact');
}
exit;
?>
