<?php
// Simple form handler with minimal dependencies
$success = false;
$error = '';

// Log information regardless of method
error_log("Request received at " . date('Y-m-d H:i:s'));
error_log("REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);

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

// Check if we have data
if (!empty($data)) {
    error_log("Form data received: " . print_r($data, true));
    
    // Get the name from form data
    $name = isset($data['name']) ? $data['name'] : 'Unbekannt';
    
    // Prepare message
    $message = isset($data['message']) ? $data['message'] : '';
    
    if (!empty($data['phone'])) {
        $message .= "\n\nTelefonnummer: " . $data['phone'];
    }
    
    // Get the subject from form data
    $subjectField = isset($data['subject']) ? $data['subject'] : '';
    
    // Use basic PHP mail() function with correct sender address
    $to = "kontakt@luftglanz.de";
    $subject = $subjectField ?: "Neue Kontaktanfrage von $name";
    $headers = "From: $name <luftglanz@egonetix.de>\r\n" .
               "Reply-To: " . ($data['email'] ?? 'luftglanz@egonetix.de') . "\r\n" .
               "X-Mailer: PHP/" . phpversion();
    
    try {
        $success = mail($to, $subject, $message, $headers);
        error_log("Mail sent: " . ($success ? "Success" : "Failed"));
    } catch (Exception $e) {
        error_log("Mail exception: " . $e->getMessage());
        $error = $e->getMessage();
    }
}

// Redirect back to index.html instead of showing debug page
header('Location: index.html?form_status=' . ($success ? 'success' : 'error') . 
       ($error ? '&error_message=' . urlencode($error) : ''));
exit;
?>
