<?php
$language = !empty($_GET["intgrtn_language"]) ? $_GET["intgrtn_language"] : null;
$country = !empty($_GET["country"]) ? $_GET["country"] : null;
$queryString = "";

$availableLanguages = array("en", "pl", "de","it");
$availableCountries = array("EN", "PL", "DE","IT");

if (!empty($_SERVER['QUERY_STRING'])) {
	$queryString = '?' . $_SERVER['QUERY_STRING'];
}
if ($language) {
	$language = checkCountryLanguageAllegiance(null, $language);
	if (in_array($language, $availableLanguages)) {
		header('Location: ' . $language . '/index.php' . $queryString);
		exit();
	}
}
if ($country) {
	$country = strtoupper(checkCountryLanguageAllegiance($country, null));
	if (in_array($country, $availableCountries)) {
		header('Location: ' . strtolower($country) . '/index.php' . $queryString);
		exit();
	}
}

header('Location: en/index.php' . $queryString);
exit();

function checkCountryLanguageAllegiance($country, $language)
{
	$countryIso = $country != null ? strtolower($country) : $language;
	switch ($countryIso) {
		case "cn":
		case "hk":
		case "tw":
			return "cn";
		case "ar":
		case "bo":
		case "cl":
		case "co":
		case "cu":
		case "cr":
		case "do":
		case "ec":
		case "gt":
		case "gq":
		case "hn":
		case "mx":
		case "ni":
		case "pa":
		case "pe":
		case "pr":
		case "sv":
		case "uy":
		case "ve":
			return "es";
		case "be":
			return "fr";
		case "gb":
			return "en";
		case "at":
		case "ch":
		case "li":
		case "lu":
			return "de";
		case "ae":
		case "om":
		case "kw":
		case "qa":
		case "bh":
		case "sa":
		case "gcc":
			return "gcc";
		default:
			return $countryIso;
	}
}
