<?php
/**
 * Kontaktformular mit PHPMailer
 * Sicherer und moderner E-Mail-Versand
 */

// Nur POST-Requests erlauben
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die('Methode nicht erlaubt');
}

// CSRF-Schutz durch Ajax-Anforderung
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || 
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    http_response_code(403);
    die('Nur Ajax-Anfragen erlaubt');
}

// Konfiguration laden
if (!file_exists(__DIR__ . '/config.php')) {
    http_response_code(500);
    die('Konfigurationsdatei nicht gefunden');
}
$config = require __DIR__ . '/config.php';

// PHPMailer laden
require_once __DIR__ . '/../assets/vendor/phpmailer/PHPMailer.php';
require_once __DIR__ . '/../assets/vendor/phpmailer/SMTP.php';
require_once __DIR__ . '/../assets/vendor/phpmailer/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Eingaben validieren und säubern
$name = filter_var($_POST['name'] ?? '', FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'] ?? '', FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'] ?? '', FILTER_SANITIZE_STRING);

// Validierung
if (empty($name) || strlen($name) < 2) {
    die('Bitte geben Sie Ihren Namen ein');
}

if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die('Bitte geben Sie eine gültige E-Mail-Adresse ein');
}

if (empty($subject) || strlen($subject) < 3) {
    die('Bitte geben Sie ein Thema ein');
}

if (empty($message) || strlen($message) < 10) {
    die('Ihre Nachricht ist zu kurz (mindestens 10 Zeichen)');
}

try {
    $mail = new PHPMailer(true);
    
    // Server-Einstellungen
    $mail->isSMTP();
    $mail->Host = $config['smtp_host'];
    $mail->SMTPAuth = true;
    $mail->Username = $config['smtp_username'];
    $mail->Password = $config['smtp_password'];
    $mail->SMTPSecure = $config['smtp_encryption'];
    $mail->Port = $config['smtp_port'];
    $mail->CharSet = 'UTF-8';
    
    // Absender
    $mail->setFrom($config['from_email'], $config['from_name']);
    $mail->addReplyTo($email, $name);
    
    // Empfänger
    $mail->addAddress($config['to_email'], $config['to_name']);
    
    // Inhalt
    $mail->isHTML(true);
    $mail->Subject = 'Kontaktformular: ' . $subject;
    
    $htmlMessage = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #37517e; color: white; padding: 15px; border-radius: 5px 5px 0 0; }
            .content { background: #f8f9fa; padding: 20px; border-radius: 0 0 5px 5px; }
            .field { margin-bottom: 15px; }
            .label { font-weight: bold; color: #37517e; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>Neue Kontaktanfrage</h2>
            </div>
            <div class='content'>
                <div class='field'>
                    <div class='label'>Name:</div>
                    <div>" . htmlspecialchars($name) . "</div>
                </div>
                <div class='field'>
                    <div class='label'>E-Mail:</div>
                    <div>" . htmlspecialchars($email) . "</div>
                </div>
                <div class='field'>
                    <div class='label'>Thema:</div>
                    <div>" . htmlspecialchars($subject) . "</div>
                </div>
                <div class='field'>
                    <div class='label'>Nachricht:</div>
                    <div>" . nl2br(htmlspecialchars($message)) . "</div>
                </div>
            </div>
        </div>
    </body>
    </html>
    ";
    
    $mail->Body = $htmlMessage;
    $mail->AltBody = "Name: $name\nE-Mail: $email\nThema: $subject\n\nNachricht:\n$message";
    
    // E-Mail senden
    $mail->send();
    echo 'OK';
    
} catch (Exception $e) {
    error_log('PHPMailer Error: ' . $mail->ErrorInfo);
    http_response_code(500);
    die('Fehler beim Senden der Nachricht. Bitte versuchen Sie es später erneut.');
}
?>
