<?php
namespace Page;

use IgShared\Http\Process\RenderWebpage;

use IgShared\Webpage\Model\Composite\WebpageComposite;
use Tool\Environment\Model\EnvironmentWebpage as Environment;
use IgShared\ErrorHandling\Process\ExceptionHandler;
use Tool\Environment\Model\SimpleComposite;
use Tool\Db\Process\ConnectionLoader;
use IgShared\UrlShortener\Process\UrlShortenerProcess;

include 'vendor/autoload.php';

$basePath = realpath(dirname(__FILE__).'/..');

define('APPLICATION_NAME', 'url-shortener');
define('LOCALE', 'de_DE');    

/*
if (isset($_GET['test'])) {
	header('content-type:text/plain');
	var_export($_SERVER);
	die();
} */

//if (($_SERVER['SERVER_NAME'] == 'plus.io' || strpos($_SERVER['SERVER_NAME'], 'plusio') !== false || strpos($_SERVER['SERVER_NAME'], 'plus-io') !== false) && 

list($path) = explode('?', $_SERVER['REQUEST_URI']);

if (isset($_GET['debug'])) {
    header('Content-type: text/plain; charset=utf-8');
    var_export($_SERVER); die();
}

if (($path == '/' || empty($path))) {
    
    $addRequest = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
    
    if (strpos($addRequest, "\n") !== false || strpos($addRequest, "\r") !== false) {
     	header("Location: https://www.plusserver.com");
    }
    
    header("HTTP/1.1 301 Moved Permanently");
    if ($_SERVER['SERVER_NAME'] == 'plus.one') {        
        header("Location: https://www.plusserver.com/multi-cloud-tarif" . $addRequest);
 	} elseif ($_SERVER['SERVER_NAME'] == 'plus.io') {        
        header("Location: https://www.plusserver.com/managed-cloud/multi-cloud" . $addRequest);        
    } else {        
        header("Location: https://www.plusserver.com" . $addRequest);
    }
    header("Connection: close");
    exit();
}

try {
    $environment = new Environment();
    $environment->setBasePath($basePath);

    $composite = new WebpageComposite();
    $composite
    ->setEnvironment($environment)
    ->setLocale(LOCALE);

    $renderer = new RenderWebpage();
	$renderer->init($composite);
	
	$UrlShortenerProcess = new UrlShortenerProcess();
	$UrlShortenerProcess->forward();
}
catch (\Exception $e) {
    error_log($e);

    $composite = new SimpleComposite();
    $exceptionHandler = new ExceptionHandler($composite);
    $exceptionHandler->sendException($e);

    header('500 Internal Server Error', true, 500);    
}


