<?php 

$url = strtolower($_SERVER['REQUEST_URI']);

$contentType = 'Content-Type: application/json';
$statusCode = 400;
$responseBody = '{"message": "Invalid Data"}';

if ($url == '/autodiscover/autodiscover.xml') {

    try {

        $xml = file_get_contents('autodiscover-template.xml');
        $raw = file_get_contents('php://input');
        $matches = array();
        preg_match('/<EMailAddress>(.*)<\/EMailAddress>/', $raw, $matches);

        if (isset($matches[1])) {

            $email = $matches[1];
            $domain = explode('@', $email)[1];

            $xml = str_replace('[$domain$]', $domain, $xml);
            $xml = str_replace('[$email$]', $email, $xml);

            $statusCode = 200;
            $contentType = 'Content-Type: application/xml';

            $responseBody = $xml;
        }
    } catch(\Exception $e) {}

}

http_response_code($statusCode);
header($contentType);
echo $responseBody;

?>
