<?php
/**
 * Kontaktformular Mail-Script mit PHPMailer
 * Baumer Maschinenverleih
 */

// Fehlerberichterstattung
error_reporting(E_ALL);
ini_set('display_errors', 0);  // Auf dem Live-Server auf 0 setzen
ini_set('log_errors', 1);

// Session für Rate Limiting
session_start();

// Konfiguration laden
require_once 'config.php';

// PHPMailer laden
require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

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

// Funktion für sichere Ausgabe
function clean($data) {
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

// Funktion für Rate Limiting
function checkRateLimit() {
    $ip = $_SERVER['REMOTE_ADDR'];
    $now = time();
    
    if (isset($_SESSION['last_submit_' . $ip])) {
        $timeSinceLastSubmit = $now - $_SESSION['last_submit_' . $ip];
        if ($timeSinceLastSubmit < RATE_LIMIT_SECONDS) {
            return false;
        }
    }
    
    $_SESSION['last_submit_' . $ip] = $now;
    return true;
}

// Nur POST-Anfragen erlauben
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: kontakt.html');
    exit;
}

// Rate Limiting prüfen
if (!checkRateLimit()) {
    header('Location: ' . ERROR_URL . '&reason=rate_limit');
    exit;
}

// Honeypot-Spam-Schutz (verstecktes Feld - sollte leer sein)
if (!empty($_POST[HONEYPOT_FIELD])) {
    // Spam erkannt - still ablehnen
    header('Location: ' . SUCCESS_URL);
    exit;
}

// Formulardaten validieren
$name = isset($_POST['name']) ? clean($_POST['name']) : '';
$email = isset($_POST['email']) ? clean($_POST['email']) : '';
$phone = isset($_POST['phone']) ? clean($_POST['phone']) : '';
$maschine = isset($_POST['maschine']) ? clean($_POST['maschine']) : '';
$zeitraum = isset($_POST['zeitraum']) ? clean($_POST['zeitraum']) : '';
$nachricht = isset($_POST['nachricht']) ? clean($_POST['nachricht']) : '';

// Pflichtfelder prüfen
if (empty($name) || empty($email) || empty($nachricht)) {
    header('Location: ' . ERROR_URL . '&reason=missing_fields');
    exit;
}

// E-Mail-Format validieren
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Location: ' . ERROR_URL . '&reason=invalid_email');
    exit;
}

// PHPMailer initialisieren
$mail = new PHPMailer(true);

try {
    // Server-Einstellungen
    $mail->CharSet = 'UTF-8';
    
    if (USE_SMTP) {
        $mail->isSMTP();
        $mail->Host = SMTP_HOST;
        $mail->SMTPAuth = true;
        $mail->Username = SMTP_USERNAME;
        $mail->Password = SMTP_PASSWORD;
        $mail->SMTPSecure = SMTP_SECURE;
        $mail->Port = SMTP_PORT;
    }
    
    // Empfänger
    $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
    $mail->addAddress(MAIL_TO, 'Andreas Baumer');
    $mail->addReplyTo($email, $name);
    
    // Inhalt
    $mail->isHTML(true);
    $mail->Subject = 'Neue Anfrage über Kontaktformular';
    
    // E-Mail-Body
    $mailBody = '
    <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: #2c5f2d; color: white; padding: 20px; text-align: center; }
            .content { background: #f8f9fa; padding: 20px; margin: 20px 0; }
            .field { margin-bottom: 15px; padding: 10px; background: white; border-left: 3px solid #2c5f2d; }
            .label { font-weight: bold; color: #2c5f2d; }
            .value { margin-top: 5px; }
            .footer { text-align: center; color: #666; font-size: 12px; margin-top: 20px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>Neue Kontaktanfrage</h2>
                <p>Baumer Maschinenverleih</p>
            </div>
            
            <div class="content">
                <div class="field">
                    <div class="label">Name:</div>
                    <div class="value">' . $name . '</div>
                </div>
                
                <div class="field">
                    <div class="label">E-Mail:</div>
                    <div class="value"><a href="mailto:' . $email . '">' . $email . '</a></div>
                </div>
                
                ' . (!empty($phone) ? '
                <div class="field">
                    <div class="label">Telefon:</div>
                    <div class="value"><a href="tel:' . $phone . '">' . $phone . '</a></div>
                </div>
                ' : '') . '
                
                ' . (!empty($maschine) ? '
                <div class="field">
                    <div class="label">Gewünschte Maschine:</div>
                    <div class="value">' . $maschine . '</div>
                </div>
                ' : '') . '
                
                ' . (!empty($zeitraum) ? '
                <div class="field">
                    <div class="label">Gewünschter Zeitraum:</div>
                    <div class="value">' . $zeitraum . '</div>
                </div>
                ' : '') . '
                
                <div class="field">
                    <div class="label">Nachricht:</div>
                    <div class="value">' . nl2br($nachricht) . '</div>
                </div>
            </div>
            
            <div class="footer">
                <p>Diese E-Mail wurde über das Kontaktformular auf baumer.traidendorf.de gesendet</p>
                <p>IP-Adresse: ' . $_SERVER['REMOTE_ADDR'] . ' | Zeitpunkt: ' . date('d.m.Y H:i:s') . '</p>
            </div>
        </div>
    </body>
    </html>
    ';
    
    $mail->Body = $mailBody;
    
    // Alternative Text-Version (für E-Mail-Clients ohne HTML)
    $mail->AltBody = 
        "Neue Kontaktanfrage - Baumer Maschinenverleih\n\n" .
        "Name: $name\n" .
        "E-Mail: $email\n" .
        ($phone ? "Telefon: $phone\n" : "") .
        ($maschine ? "Gewünschte Maschine: $maschine\n" : "") .
        ($zeitraum ? "Gewünschter Zeitraum: $zeitraum\n" : "") .
        "\nNachricht:\n$nachricht\n\n" .
        "---\n" .
        "IP: " . $_SERVER['REMOTE_ADDR'] . "\n" .
        "Zeitpunkt: " . date('d.m.Y H:i:s');
    
    // E-Mail senden
    $mail->send();
    
    // Erfolg - weiterleiten
    header('Location: ' . SUCCESS_URL);
    exit;
    
} catch (Exception $e) {
    // Fehler loggen
    error_log("Mail-Fehler: {$mail->ErrorInfo}");
    
    // Fehlerseite
    header('Location: ' . ERROR_URL . '&reason=send_error');
    exit;
}
?>
