<?php

// SQL Information and Related
$SQL = array();
$SQL['Host']		= "database.svc.xaymar.com";
$SQL['Database']	= "com.xaymar.www";
$SQL['Username']	= "com.xaymar.www";
$SQL['Password']	= "G_5R_ZXm6Uek9DEt";
$SQL['Persistent']	= true; // Persistent database connection. (Recommended)

{ // MySQL Database Connection
	// Try and connect to the database (otherwise die).
	ini_set("mysqli.allow_persistent", $SQL['Persistent']);
	mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
	$SQL['Handle']		= new mysqli($SQL['Host'], $SQL['Username'], $SQL['Password'], $SQL['Database']);
	if ($SQL['Handle']->connect_errno) {
		header("500 Internal Server Error");
		die($SQL['Handle']->connect_errno." ".$SQL['Handle']->connect_error);
	}
}

{ // Prepare a few statements.
	$STATEMENTS = array();
	$STATEMENTS["LookUp"] = <<<STR
SELECT `target`
FROM `redirects`
WHERE
	(`disabled` = false)
	AND (`path` = ?)
ORDER BY
	`date_created` DESC
STR;
	$STATEMENTS["Insert"] = <<<STR
INSERT INTO `redirects`
SET
	`path` = ?
STR;

	// Convert text into actual prepared statements.
	foreach($STATEMENTS as $k => $v) {
		$STATEMENTS[$k] = $SQL['Handle']->prepare($v);
	}
}

// Redirect the user according to found information
$name = urldecode($_SERVER['REQUEST_URI']);
$STATEMENTS['LookUp']->bind_param('s', $name);
if(!$STATEMENTS['LookUp']->execute()) {
	header("Service Unavailable", true, 503);
	die($SQL['Handle']->errno." ".$SQL['Handle']->error);
}

//
$res = $STATEMENTS['LookUp']->get_result();
if ($res->num_rows == 0) {
	// Insert the undiscovered URL into the redirect database.
	$STATEMENTS['Insert']->bind_param('s', $name);
	if (!$STATEMENTS['Insert']->execute()) {
		header("Service Unavailable", true, 503);
		die($SQL['Handle']->errno." ".$SQL['Handle']->error);
	} else {
		if (!$STATEMENTS['Insert']->get_result()) {
			header("Service Unavailable", true, 503);
			die($SQL['Handle']->errno." ".$SQL['Handle']->error);
		}
	}
	header("Location: https://www.xaymar.com/404.html");
} else {
	while($obj = $res->fetch_object()) {
		if ($obj->target != null) {
			header("Location: ".$obj->target, true, 307);
		} else {
			header("Location: https://www.xaymar.com/404.html");
		}
	}
}
$res->close();

die();