<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");

require_once "../config.php";

function generateRandomString ($length) {
	$characters = array_merge(range('A', 'Z'), range('0', '9'));
	shuffle($characters);
	$randomString = implode('', array_splice($characters, 0, $length));
	return $randomString;
}

$json = file_get_contents("php://input");
$data = json_decode($json);

$name = $data->name;
$nameZh = $data->nameZh;
$email = $data->email;
$contact = $data->contact;
$dob = $data->dob;
$xingzuo = $data->xingzuo;
$username = $data->username;
$password = $data->password;
$referrer = $data->referrer;

$conn = connect_db();

$res = array();

if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
} else {
	$referralCode = generateRandomString(6);
	$matchedReferralCode = FASLE;

	do {
		$checkReferralCodeSql = "
			SELECT * FROM `user`
			WHERE referral_code = '" . $referralCode . "'
		";
		$result = $conn->query($checkReferralCodeSql);

		if ($result->num_rows > 0) {
			$matchedReferralCode = TRUE;
		} else {
			$matchedReferralCode = FALSE;

			$sql = "
				INSERT INTO `user` 
				(username, password, name, nameZh, email, contact, dob, xingzuo, referrer, referral_code, status)
				VALUES
				(
					'" . $username . "', 
					'" . md5(md5(AUTH_SECRET1 . $password . AUTH_SECRET2)) . "', 
					'" . $name . "', 
					'" . $nameZh . "', 
					'" . $email . "', 
					'" . $contact . "', 
					'" . $dob . "', 
					'" . $referrer . "', 
					'" . $referralCode . "', 
					'" . $xingzuo . "', 
					1
				)
			";
		
			if ($conn->query($sql) === TRUE) {
				$res["success"] = "Registration Successful";
			} else {
				$res["failed"] = "Registration Failed";
			}
		}
	} while ($matchedReferralCode === TRUE);	
}

$conn->close();
echo json_encode($res);
