<?php

$host = $_SERVER['HTTP_HOST'];

$host = strtolower($host);
$isSubdomain = preg_match("/(.*)\.developerhub\.(dev|io)/", $host, $matches);
$tld = 'io';
if ($isSubdomain) {
  $identifier = $matches[1];
  $tld = $matches[2];
} else {
  $identifier = $host;
}

$requestUri = array_key_exists('HTTP_X_FORWARDED_URI', $_SERVER) ? $_SERVER['HTTP_X_FORWARDED_URI'] : $_SERVER['REQUEST_URI'];
$requestUri = parse_url(str_replace('/sitemap.xml', '', $requestUri), PHP_URL_PATH);
$params = ['path' => $requestUri];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, getApiUrl() . '/generate-sitemap-xml/' . $identifier . '?' . http_build_query($params));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);

if (($err = curl_error($curl))) {
  echo $err;
}

echo ($result);
curl_close($curl);

function getApiUrl() {
  global $host, $tld, $isSubdomain;

  if ($host === "dev.z-proj.com") {
    return 'https://api.developerhub.dev';
  } if (!$isSubdomain) {
    return 'https://api.developerhub.io';
  } else {
    return 'https://api.developerhub.' . $tld;
  }
}
?>
