<?php
// Maximum error reporting and debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Store logs in a variable to display on the page
$debug_logs = [];
function debug_log($message) {
    global $debug_logs;
    $debug_logs[] = $message;
    error_log($message);
}

// Enhanced error logging settings
ini_set('log_errors', 1);
ini_set('error_log', 'form_errors.log');
debug_log("Log file location: " . ini_get('error_log'));
debug_log("======= New Form Submission Attempt: " . date('Y-m-d H:i:s') . " =======");
debug_log("Request Method: " . $_SERVER['REQUEST_METHOD']);
debug_log("Server Software: " . $_SERVER['SERVER_SOFTWARE']);
debug_log("HTTP_ACCEPT: " . $_SERVER['HTTP_ACCEPT']);

// Debug all inputs received
foreach ($_REQUEST as $key => $value) {
    debug_log("Request parameter: $key = $value");
}

// If direct access without POST, offer a helpful message
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "<html><head><title>Form Processing Error</title>";
    echo "<style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #d33; }
        .message { background: #f8f8f8; border: 1px solid #ddd; padding: 15px; margin: 20px 0; }
        .button { display: inline-block; padding: 10px 15px; background: #4CAF50; color: white; text-decoration: none; border-radius: 4px; }
    </style></head><body>";
    echo "<h1>Form Submission Error</h1>";
    echo "<div class='message'><p>This page is meant to be accessed via a form submission.</p>";
    echo "<p>It appears you're trying to access it directly. Please submit the form instead.</p>";
    echo "<p>Current request method: " . $_SERVER['REQUEST_METHOD'] . " (should be POST)</p></div>";
    echo "<a href='index.html#contact' class='button'>Go to Contact Form</a>";
    echo "<a href='form-test.html' class='button' style='margin-left: 10px;'>Try Test Form</a>";
    echo "</body></html>";
    exit;
}

// Contact form processing script
$success = false;
$error_message = '';

// Capture PHP warnings
function captureWarning($errno, $errstr, $errfile, $errline) {
    debug_log("WARNING [$errno]: $errstr in $errfile:$errline");
    return true;
}
set_error_handler("captureWarning", E_WARNING);

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Log all received POST data
    debug_log("Form submission received - POST data: " . print_r($_POST, true));
    
    // Get form data and sanitize inputs
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);
    $message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
    $subjectField = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);

    // Log sanitized inputs
    debug_log("Sanitized form data: Name: $name, Email: $email, Phone: $phone, Message length: " . strlen($message));

    // Basic validation
    if (empty($name) || empty($email) || empty($message) || empty($subjectField)) {
        $error_message = 'Bitte füllen Sie alle Pflichtfelder aus.';
        debug_log("Validation error: $error_message");
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
        debug_log("Validation error: $error_message");
    } else {
        // Prepare email content
        $to = "monitor@egonetix.de"; // Recipient email address
        $subject = $subjectField ?: "Neue Kontaktanfrage von luftglanz.de";
        
        // Only use the message as the email body, but add phone if present
        $email_body = $message;
        if (!empty($phone)) {
            $email_body .= "\n\nTelefonnummer: $phone";
        }
        
        // Additional headers
        $headers = "From: $name <luftglanz@egonetix.de>\r\n" .
            "Reply-To: $email\r\n" .
            "X-Mailer: PHP/" . phpversion();
        
        debug_log("Email headers: " . $headers);
        debug_log("Preparing to send email to: $to");
        debug_log("Email subject: $subject");
        debug_log("Email body: $email_body");
        
        try {
            // SMTP settings
            debug_log("Setting SMTP server to: srvdc01");
            ini_set("SMTP", "srvdc01");
            debug_log("SMTP after setting: " . ini_get("SMTP"));
            
            debug_log("Setting smtp_port to: 25");
            ini_set("smtp_port", "25");
            debug_log("smtp_port after setting: " . ini_get("smtp_port"));
            
            debug_log("Setting sendmail_from to: luftglanz@egonetix.de");
            ini_set("sendmail_from", "luftglanz@egonetix.de");
            debug_log("sendmail_from after setting: " . ini_get("sendmail_from"));
            
            // Set authentication for sending the email
            $auth = base64_encode("luftglanz:dDmws12*");
            debug_log("Setting SMTP authentication");
            ini_set("smtp_auth", $auth);
            
            debug_log("About to call mail() function");
            
            // Try to send the email with debugging
            ob_start(); // Start output buffering to capture any output or warnings
            $mail_result = mail($to, $subject, $email_body, $headers);
            $output = ob_get_clean(); // Get the buffered output
            
            debug_log("mail() function output: " . $output);
            debug_log("mail() function result: " . ($mail_result ? "TRUE" : "FALSE"));
            
            if ($mail_result) {
                $success = true;
                debug_log("Email appears to have been sent successfully");
            } else {
                $error = error_get_last();
                $error_message = 'Es gab ein Problem beim Senden Ihrer Nachricht. Bitte versuchen Sie es später erneut.';
                debug_log("Mail function failed. PHP Error: " . ($error ? print_r($error, true) : 'Unknown error'));
            }
        } catch (Exception $e) {
            $error_message = 'Ein Fehler ist aufgetreten: ' . $e->getMessage();
            debug_log("Exception caught: " . $e->getMessage());
            debug_log("Exception trace: " . $e->getTraceAsString());
        }
    }
}

// If not successful, display debugging information
if (!$success) {
    // Return error with debugging logs for AJAX requests
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
        debug_log("Returning JSON response with debug info");
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false, 
            'message' => $error_message,
            'debug_logs' => $debug_logs
        ]);
        exit;
    }
    
    // Display debug information directly on the page
    echo "<html><head><title>Form Submission Debug</title>";
    echo "<style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #d33; }
        .debug-container { background: #f8f8f8; border: 1px solid #ddd; padding: 15px; margin: 20px 0; }
        .debug-log { font-family: monospace; white-space: pre-wrap; background: #333; color: #fff; padding: 10px; max-height: 400px; overflow: auto; }
        .error-message { color: #d33; font-weight: bold; margin: 20px 0; }
        .button { display: inline-block; padding: 10px 15px; background: #4CAF50; color: white; text-decoration: none; border-radius: 4px; }
    </style></head><body>";
    echo "<h1>Form Submission Debugging Output</h1>";
    echo "<div class='error-message'>Error: $error_message</div>";
    
    echo "<div class='debug-container'>";
    echo "<h2>Debug Logs:</h2>";
    echo "<div class='debug-log'>";
    foreach ($debug_logs as $log) {
        echo htmlspecialchars($log) . "\n";
    }
    echo "</div></div>";
    
    echo "<a href='index.html#contact' class='button'>Back to Contact Form</a>";
    echo "</body></html>";
    exit;
}

// For successful AJAX requests
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
    debug_log("Returning successful JSON response");
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'message' => '']);
    exit;
}

// For successful non-AJAX requests, redirect back to the form
debug_log("Redirecting to form with success message");
header('Location: index.html?form_success=1#contact');
debug_log("======= End of Form Submission Processing =======\n");
exit;
?>
