<?php

declare(strict_types=1);

require_once '../config.php';
require_once '../db.php';

// Get domain without www

if ( isset( $_GET['domain']))
{
	$domain = $_GET['domain'];
	$url = $_GET['path'] ?? '';
}else{
	$domain = $_SERVER['HTTP_HOST'];
	$url = trim(strtolower($_SERVER['REQUEST_URI']), '/');
}

if (substr($domain, 0, 4) == 'www.') {
    $domain = substr($domain, 4);
}

// Get URL without slashes

$query = sprintf("SELECT * FROM `[][]domain` WHERE `domain`='%s' AND `status`='PUBLISHED'", Db::escape($domain));
$site = Db::fo($query);


if (isset($site->id)) {
    process_redirect($site, $url);
} else {
    fancyPage('Domeinnaam niet gekoppeld');
}

function process_redirect(object $siteObj,  string $url)
{
    $query = sprintf("SELECT `id`,`path`,`target`,`preserve`,`subpages`,`log` FROM `[][]rule` WHERE `forward_id`='%d' AND `status`='PUBLISHED'
	
	ORDER BY `subpages` ASC, LENGTH( `path` ) DESC", Db::e($siteObj->forward_id), Db::e($url));




    $res = Db::query_rs($query);


    foreach ($res as $result) {
        if ($result->subpages == 0) {
            // Check for exact matches
            if ($result->path == $url) {
                // Exact match -> execute now
                doRedirect($result->target, $result);
            }
        } else if (substr($url, 0, strlen($result->path ?? '')) == $result->path) {
            // Not an exact match
                if ($result->preserve == 1) {
                    $redirect_url = sprintf('%s%s', $result->target, substr($url, strlen($result->path ?? '')));
                } else {
                    $redirect_url = $result->target;
                }
                doRedirect($redirect_url, $result);
        }
    }
    // No matches whatsoever
    fancyPage('Geen adres geconfigureerd');
}

function doRedirect(string $url, object $result)
{
	if(  $result->log == 1 )
	{
		$query = sprintf("INSERT INTO `[][]stats` ( `rule_id`, `date`) VALUES( '%s', '%s' ) ON DUPLICATE KEY UPDATE `count` = `count` + 1", Db::e($result->id), Db::e( date('Y-m-d') ));
					Db::query($query);
	}

	if ( isset( $_GET['domain']))
	{
		print_r($url);
		exit;
	}
    //http_response_code( 301);
    //header("Location: ". $url );

    header('Location: '.$url, true, 301);
    echo '<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="'.$url.'">here</A>.
</BODY></HTML>';
    exit;
}

function fancyPage($message)
{
    echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
	        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
      	<meta http-equiv="Content-Type" content="text/html;charset=T.61-8BIT" />	
        <meta name="description" content=""/>
        
        <link rel="apple-touch-icon" sizes="57x57" href="https://notfound.co/3.1/favicon/apple-touch-icon-57x57.png"/>
		<link rel="apple-touch-icon" sizes="60x60" href="https://notfound.co/3.1/favicon/apple-touch-icon-60x60.png"/>
		<link rel="apple-touch-icon" sizes="72x72" href="https://notfound.co/3.1/favicon/apple-touch-icon-72x72.png"/>
		<link rel="apple-touch-icon" sizes="76x76" href="https://notfound.co/3.1/favicon/apple-touch-icon-76x76.png"/>
		<link rel="apple-touch-icon" sizes="114x114" href="https://notfound.co/3.1/favicon/apple-touch-icon-114x114.png"/>
		<link rel="apple-touch-icon" sizes="120x120" href="https://notfound.co/3.1/favicon/apple-touch-icon-120x120.png"/>
		<link rel="apple-touch-icon" sizes="144x144" href="https://notfound.co/3.1/favicon/apple-touch-icon-144x144.png"/>
		<link rel="apple-touch-icon" sizes="152x152" href="https://notfound.co/3.1/favicon/apple-touch-icon-152x152.png"/>
		<link rel="apple-touch-icon" sizes="180x180" href="https://notfound.co/3.1/favicon/apple-touch-icon-180x180.png"/>
		<link rel="icon" type="image/png" href="https://notfound.co/3.1/favicon/favicon-32x32.png" sizes="32x32"/>
		<link rel="icon" type="image/png" href="https://notfound.co/3.1/favicon/android-chrome-192x192.png" sizes="192x192"/>
		<link rel="icon" type="image/png" href="https://notfound.co/3.1/favicon/favicon-96x96.png" sizes="96x96"/>
		<link rel="icon" type="image/png" href="https://notfound.co/3.1/favicon/favicon-16x16.png" sizes="16x16"/>
		<link rel="manifest" href="https://notfound.co/3.1/favicon/manifest.json"/>
		<link rel="mask-icon" href="https://notfound.co/3.1/favicon/safari-pinned-tab.svg" color="#5bbad5"/>
		<link rel="shortcut icon" href="https://notfound.co/3.1/favicon/favicon.ico"/>
		<meta name="apple-mobile-web-app-capable" content="yes"/>
		<meta name="apple-mobile-web-app-status-bar-style" content="black"/>
		<meta name="msapplication-TileColor" content="#da532c"/>
		<meta name="msapplication-TileImage" content="https://notfound.co/3.1/favicon/mstile-144x144.png"/>
		<meta name="msapplication-config" content="https://notfound.co/3.1/favicon/browserconfig.xml"/>
		<meta name="theme-color" content="#ffffff"/>
        <meta name="google" value="notranslate"/>
          <link type="text/css" href="/style.css" rel="stylesheet" />
        
	<title>'.$message.' - NotFound Digital Creativity</title>
	
      	</head>
      	<body>
	      	<header>
	<p><a
      	href="http://www.notfound.nl/?ref=siteboss.forward" class="sk-circle">
	      <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
		 viewBox="0 0 500 500" style="enable-background:new 0 0 500 500;" xml:space="preserve">	
	<polygon id="stroke1" class="st" points="414.5,381.8 75.7,185.8 75.7,376.6 53.2,363 53.2,146.7 437,369 "/>
	<polygon id="stroke2" class="st" points="446.8,352.5 62.2,131 84.8,117.4 424.3,313.5 424.3,123.4 446.8,136.2 "/>
	<polygon id="stroke3" class="st0" points="231.2,297.7 94.5,376.6 94.5,218.8 116.3,231.6 116.3,337.5 208.7,284.2 "/>
	<polygon id="stroke4" class="st0" points="103.5,106.9 250,22.8 395.7,106.9 373.2,119.7 250,48.3 126.1,119.7 "/>
	<polygon id="stroke5" class="st0" points="395.7,392.3 250,477.2 103.5,392.3 126.1,379.6 250,450.9 373.2,379.6 "/>
	<polygon id="stroke6" class="st0" points="189.9,273.7 135.1,305.2 135.1,278.9 167.4,260.9 "/>
	<polygon id="stroke7" class="st0" points="144.9,131 250,70.1 354.4,131 331.9,143.7 250,96.4 167.4,143.7 "/>
	<polygon id="stroke8" class="st0" points="354.4,368.3 250,429.1 144.9,368.3 167.4,355.5 250,402.9 331.9,355.5 "/>
	<polygon id="stroke9" class="st0" points="268.8,202.3 405.5,123.4 405.5,281.2 382.9,268.4 382.9,161.8 291.3,215.1 "/>
	<polygon id="stroke10" class="st0" points="310.1,226.3 364.2,194.8 364.2,220.3 331.9,239.1 "/>
	</svg>
      </a></p>
	      	</header>
        <h1>'.$message.'</h1>
      	</body>
      	</html>';
    exit;
}
