<?

require_once('altauth_lib.php');

function do_register()
{
	$regcodes_file = 'altauth_regcodes.txt';
	$regcode = trim($_REQUEST['regcode']);
	
	if ( ! file_exists($regcodes_file) || ! $regcode || ! in_array($regcode, split("\n", trim(join('', file($regcodes_file))))) )
	{
		print "<center><b style='color:red'>Invalid registration code</b></center><br>";
		return 0;
	}
	
	$username = strtolower($_REQUEST['username']);
	$password = $_REQUEST['password'];
	
	if ( ! $username || ! $password )
	{
		print '<center><b style="color:red">* Both Username and Password fields are required</b></center><br>';
		return 0;
	}

	if (has_user($username))
	{
		print "<center><b style='color:red'>* User with username $username is already registered</b></center><br>";
	}
	else
	{
		save_user($username, $password);
		$userdb = load_userdb();
		$userdb[$username]['regdate'] = date("Y-m-d G:i:s");
		$userdb[$username]['regcode'] = $regcode;
		save_userdb($userdb);
		
		$afterreg_file = 'altauth_afterregister.txt';
		$afterreg_url = file_exists($afterreg_file)
			? preg_replace('/\\s+/', '', join('', file($afterreg_file)))
			: preg_replace('/\/[^\/]+$/', '', $_SERVER['PHP_SELF']);
		
		print "<center><b style='color:blue'>Thank you for joining us! <a href='$afterreg_url'>Click here to continue</a></b></center><br>";
		
		return 1;
	}
}

//---------------------------------------- M A I N --------------------------------------
if (file_exists('altauth_header.php')) print file_get_contents('altauth_header.php');

print "<style type='text/css'>\n";
print file_get_contents('altauth_style.css');
print "</style>\n";

if( ! isset($_REQUEST['do_register']) || ! do_register() )
{
	include('altauth_registerscreen.php');
}

if (file_exists('altauth_footer.php')) print file_get_contents('altauth_footer.php');

print_copyright();

?>
