<?php
header("Content-Type: application/xml; charset=utf-8");

// Standard-Fallback (wird nur genutzt, wenn absolut nichts im POST-Body steht)
$email = "nicky@seiler-busswil.ch";

// POST-Body von Outlook einlesen
$postData = file_get_contents("php://input");

if (!empty($postData)) {
    // Unterdrückt Warnungen, falls Outlook korruptes XML senden sollte
    libxml_use_internal_errors(true);
    
    // Lädt den POST-Body als XML-Objekt
    $xmlData = simplexml_load_string($postData);
    
    if ($xmlData !== false) {
        // Registriert den offiziellen Autodiscover-Namespace, um die Elemente sauber zu finden
        $namespaces = $xmlData->getDocNamespaces();
        $xmlData->registerXPathNamespace('ns', current($namespaces));
        
        // Sucht flexibel nach dem E-Mail-Tag, egal wo es im Baum liegt
        $result = $xmlData->xpath('//ns:EMailAddress | //EMailAddress | //ns:EmailAddress | //EmailAddress');
        
        if (!empty($result)) {
            $email = htmlspecialchars(trim((string)$result[0]));
        }
    }
    libxml_clear_errors();
}

echo '<?xml version="1.0" encoding="utf-8" ?>';
echo "\n";
?>
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">
    <Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">
        <Account>
            <AccountType>email</AccountType>
            <Action>settings</Action>

            <!-- Posteingang (IMAP - Implizites SSL/TLS) -->
            <Protocol>
                <Type>IMAP</Type>
                <Server>mail.erhardt-fbt.de</Server>
                <Port>993</Port>
                <LoginName><?php echo $email; ?></LoginName>
                <SSL>on</SSL>
                <EncryptionRequired>on</EncryptionRequired>
                <SPA>off</SPA>
            </Protocol>

            <!-- Postausgang (SMTP - Explizites STARTTLS) -->
            <Protocol>
                <Type>SMTP</Type>
                <Server>mail.erhardt-fbt.de</Server>
                <Port>587</Port>
                <LoginName><?php echo $email; ?></LoginName>
                <SSL>on</SSL>
                <EncryptionRequired>on</EncryptionRequired>
                <EncryptionMethod>TLS</EncryptionMethod>
                <SPA>off</SPA>
            </Protocol>
        </Account>
    </Response>
</Autodiscover>
