<?php
// Alternative form handler using GET method
// This file works around servers that block POST to PHP files

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log to help with debugging
error_log("Form-GET-Handler received request: " . date('Y-m-d H:i:s'));
error_log("REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD']);

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

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

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

// Simple validation
$success = false;
$errorMessage = '';

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 {
    // Construct message for the email
    $emailBody = $message;
    if (!empty($phone)) {
        $emailBody .= "\n\nTelefonnummer: $phone";
    }
    
    // Email details
    $to = "kontakt@luftglanz.de";
    $subject = $subjectField ?: "Neue Kontaktanfrage von $name";
    
    // Attempt to send email via internal mail function
    $mailSent = mail($to, $subject, $emailBody, 
        "From: $name <luftglanz@egonetix.de>\r\n" . 
        "Reply-To: $email\r\n" . 
        "X-Mailer: PHP/" . phpversion()
    );
    
    if ($mailSent) {
        $success = true;
    } else {
        $errorMessage = 'Es gab ein Problem beim Senden Ihrer Nachricht. Bitte versuchen Sie es später erneut.';
        error_log("Mail sending failed");
    }
}

// Handle the response
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Ajax request - return JSON
    header('Content-Type: application/json');
    echo json_encode([
        'success' => $success,
        'message' => $errorMessage
    ]);
} else {
    // Regular form submission - redirect with status
    if ($success) {
        header('Location: index.html?form_success=1#contact');
    } else {
        header('Location: index.html?form_error=' . urlencode($errorMessage) . '#contact');
    }
}
?>
