<?php
session_start();

if (!isset($_POST['submit'])) {
	exit('Fail!');
}

include '../../conf/conn.php';

$username = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST['username']), ENT_QUOTES, "UTF-8"));
$gender = mysqlSecurity($conn, $_POST['gender']);
$firstname = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST['First_Name']), ENT_QUOTES, "UTF-8"));
$lastname = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST['Last_Name']), ENT_QUOTES, "UTF-8"));
$password = base64_encode($_POST['password']);
$email = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST['email']), ENT_QUOTES, "UTF-8"));
$phone = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST['phone']), ENT_QUOTES, "UTF-8"));
$address = mysqlSecurity($conn, htmlentities(htmlspecialchars($_POST["address"]), ENT_QUOTES, "UTF-8"));
$birthday = mysqlSecurity($conn, $_POST["birthday"]);
$created = date("Y-m-d H:i:s");
$registerIp = $_SERVER['REMOTE_ADDR'];

$appendData = '';

//Add a input field pre $_POST element.
foreach ($_POST as $key => $val) {
	if ($key === 'submit') {
		continue;
	}

	$appendData .= "<input type='hidden' name='{$key}' value='{$val}' >";
}

//Use js to submit form,passing variables back to e-shop.php
$postData = <<<EOD
<form id="passBack" action="../e-shop.php" method="POST">
	{$appendData}
</form>
<script>
	document.getElementById('passBack').submit();
</script>
EOD;

$check_query = mysqli_query($conn, "select * from clients where username='$username' limit 1");
if (mysqli_fetch_assoc($check_query)) {
	$_SESSION["page"] = 8;
	$_SESSION["fail"] = '註冊失敗，用戶名稱已被使用。';

	echo $postData;
	exit();
}

$check_query = mysqli_query($conn, "select * from clients where email='$email' limit 1");
if (mysqli_fetch_assoc($check_query)) {
	$_SESSION["page"] = 8;
	$_SESSION["fail"] = '註冊失敗，郵箱地址已被使用。';

	echo $postData;
	exit();
}

$query = "insert into clients( `username`, `first name`, `last name`, `gender`, `birthday`, `password`, `email`, `phone`, `address`, `created`, `logintime`,`registerIp`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

//prepare statment for mysql insert
$regStmt = mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($regStmt, $query)) {
	$typeString = str_pad('s', 12, 's');

	if (!mysqli_stmt_bind_param($regStmt, $typeString,
		$username,
		$firstname,
		$lastname,
		$gender,
		$birthday,
		$password,
		$email,
		$phone,
		$address,
		$created,
		$created,
		$registerIp
	)) {
		error_log(print_r($query, true) . "\r\n", 3, "../../errors.log");
	}

} else {error_log(print_r($query, true) . "\r\n", 3, "../../errors.log");}

//If execute fail and else
if (!mysqli_stmt_execute($regStmt)) {
	error_log(print_r($query, true) . "\r\n", 3, "../../errors.log");
	$_SESSION["page"] = 8;
	$_SESSION["fail"] = '註冊失敗，請檢查輸入資料并重新輸入。';

	echo $postData;
	exit();
} else {
	//close stmt
	mysqli_stmt_close($regStmt);

	if (isset($_POST['subscription'])) {
		//Subscribe user to MailChimp
		include_once '../../mailchimp/mailchimp-rest-api.php';

		$mc = new \VPS\MailChimp(MAILCHIMP_API_KEY);

		//convert birthday to accepted format
		$mc_time = strtotime($birthday);
		$mc_birthday = date('m/d', $mc_time);

		$data = [
			'email_address' => $email,
			'merge_fields' => [
				'FNAME' => $firstname, 'LNAME' => $lastname,
				'MMERGE3' => $username,
				'MMERGE4' => $gender,
				'MMERGE5' => $mc_birthday,
				'MMERGE6' => $phone,
				'MMERGE7' => $address,
			],
			'status' => 'subscribed',
		];

		$path = '/lists/' . MAILCHIMP_LIST_ID . '/members';

		$mc->post($path, $data);
	}

	$query = "select * from clients where username='$username' and password='$password' limit 1";
	$result = mysqli_query($conn, $query);
	$row = mysqli_fetch_assoc($result);
	$_SESSION['username'] = $username;
	$_SESSION['email'] = $email;
	$_SESSION['username'] = $username;
	$_SESSION['id'] = $row['id'];
	$_SESSION["phone"] = $row['phone'];
	$_SESSION["first_name"] = $row['first name'];
	$_SESSION["last_name"] = $row['last name'];
	$_SESSION["address"] = $row['address'];
	$query = "update clients set";
	$result = mysqli_query($conn, $query);
	$url = "../e-shop.php";
	echo "<script language='javascript'
	type='text/javascript'>";
	echo "window.location.href='$url'";
	echo "</script>";
	require_once '../../phpmailer/class.phpmailer.php';
	$mail = new PHPMailer(); // create a new object
	$mail->IsSMTP(); // enable SMTP
	$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
	//$mail->SMTPAuth = true; // authentication enabled
	//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
	//$mail->Host = "localhost";
	//$mail->Host = "smtp.gmail.com";
	$mail->Host = "localhost";
	//$mail->Port = 465; // or 587

	//in_sandbox() is a function in init.php which included in conn.php
	if (!in_sandbox()) {
		// $mail->AddBCC("daniel@at-creative.com");
		$mail->AddBCC("jack@at-creative.com");
		//$mail->AddBCC("edmondcheng@at-creative.com");
		// $mail->AddBCC("info@sayvour.com.hk");
		// $mail->AddBCC("catherine@sayvour.com.hk");
		// $mail->AddBCC("sayvourhongkong@gmail.com");
	}
	$mail->IsHTML(true);
	//$mail->Username = "kk@at-creative.com";
	//$mail->Password = "artech0088";
	$mail->SetFrom("info@sayvour.com.hk", "Sayvour");
	$mail->Subject = "Thank you for your signing up from Sayvour";
	$mail->Body = "                                <!-- top bar -->

                <div id=':lt' class='ii gt adP adO'>
                    <div id=':ls' class='a3s aXjCH m156312919a8bb8e9'><u></u>
                        <div style='margin:0;padding:0'>
													<div style='min-width:320px;background-color:#c2e3e3' lang='x-wrapper'>
														<div style='Margin:0 auto;max-width:560px;min-width:280px;'>
                                    <div style='border-collapse:collapse;display:table;width:100%'>
                                        <div style='Float:left;font-size:12px;line-height:19px;max-width:280px;min-width:140px;padding:10px 0 5px 0;color:#9dc4c4;font-family:Cabin,Avenir,sans-serif'></div>
                                        <div style='Float:left;font-size:12px;line-height:19px;max-width:280px;min-width:139px;padding:10px 0 5px 0;text-align:right;color:#9dc4c4;font-family:Cabin,Avenir,sans-serif'></div>
                                    </div>
                                </div>
                                <div style='Margin:0 auto;max-width:600px;min-width:320px;'>
                                    <div style='font-size:26px;line-height:32px;Margin-top:6px;Margin-bottom:20px;color:#ffffff;font-family:&quot;PT Serif&quot;,Georgia,serif;Margin-left:20px;Margin-right:20px' align='center'>
                                        <div style='font-size:0px!important;line-height:0!important' align='center'><img style='min-height:auto;width:100%;border:0;max-width:217px' src='https://ci4.googleusercontent.com/proxy/vUMxJkR_Kw9qDMrAUmEEtS4_hy8v4TztsG8zNDbLJxG0zizdPUmHdqEAaVAuRWqrT0fA9zde7TizwG9QGRXUNgPmnlhNJWJ_gzMCbqpsW3bSMaNbueUnoTh1=s0-d-e1-ft#http://i1.cmail2.com/ei/d/F9/F24/F62/203623/csfinal/sayvour-logo.png' alt='' width='217' class='CToWUd'></div>
                                    </div>
                                </div>

                <!-- end top bar -->

                <!-- Dear -->
										<div style='background-color:#FFFFFF'>
					<div style='Margin:0 auto;max-width:600px;min-width:320px;word-wrap:break-word;word-break:break-word'>
						<div style='border-collapse:collapse;display:table;width:100%'>
							<div style='max-width:600px;min-width:320px;text-align:left;FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
								<div style='Margin-left:20px;Margin-right:20px'>
									<div style='line-height:40px;font-size:1px'>&nbsp;</div>
								</div>
								<div style='Margin-left:20px;Margin-right:20px'>
									<h1 style='Margin-top:0;Margin-bottom:20px;font-style:normal;font-weight:normal;color:#499f9e;font-size:24px;line-height:32px;font-family:&quot;PT Serif&quot;,Georgia,serif;text-align:center' lang='x-size-28'>Thank you for signing up Sayvour!</h1>
								</div>

                 <div style='Margin-left:20px;Margin-right:20px'>
                    <div style='line-height:20px;font-size:1px'>&nbsp;</div>
                </div>


								<div style='Margin-left:20px;Margin-right:20px'>
									<p style='Margin-top:0;Margin-bottom:0;text-transform: capitalize'>Dear&nbsp;" . $row["first name"] . ",</p><p style='Margin-top:20px;Margin-bottom:20px'>Welcome to Sayvour! Thank you for signing up as our member.<br><br>
Now you can login to <a href='http://www.sayvour.com.hk'>Sayvour eShop</a> and order your personalised chocolates and pastries. Hope you will enjoy the shopping experience.</p>
								</div>
								<div style='Margin-left:20px;Margin-right:20px'>
									<div style='line-height:20px;font-size:1px'>&nbsp;</div>
				</div>

                <!-- End Dear -->


                <div style='Margin-left:20px;Margin-right:20px'>
                    <div style='line-height:5px;font-size:1px'>&nbsp;</div>
                </div>

                <!-- Best regards -->


				<div style='Margin-left:20px;Margin-right:25px'>
									<p style='Margin-top:0;Margin-bottom:20px;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>
									Best regards,</p>
								</div>
								<div style='font-size:12px;font-style:normal;font-weight:normal' align='left'>
									<a href='http://www.sayvour.com.hk'><img style='border:0;display:block;min-height:auto;width:100%;max-width:150px; padding-left:20px' alt='' width='249' src='https://ci4.googleusercontent.com/proxy/WhjL_vvSpLarh-zQTnIIub3yktIgmMYyzgWhl_XTAMbJQ9LIpv2A32hCNW_U3MQg3wHDHewv_AnV0ysjc7_dtTBbxdltT6OvngagFLBQ44sF8Vmw8QWrq9G8jgY=s0-d-e1-ft#http://i1.cmail2.com/ei/d/F9/F24/F62/203624/csfinal/Sayvour-logo-b.png' class='CToWUd'></a>
								</div>
								<div style='Margin-left:20px;Margin-right:20px;Margin-top:20px'>
									<p style='Margin-top:0;Margin-bottom:20px'>Sayvour | Say Your Flavour</p>
								</div>
								<div style='Margin-left:20px;Margin-right:20px'>
									<div style='line-height:5px;font-size:1px'>&nbsp;</div>
								</div>
								<div style='Margin-left:20px;Margin-right:20px'>
									<div style='line-height:5px;font-size:1px'>&nbsp;</div>
								</div>
								<div style='Margin-left:20px;Margin-right:20px'>
									<div style='line-height:5px;font-size:1px'>&nbsp;</div>
								</div>
							</div>
						</div>
					</div>
				</div>

               	<!-- End Best regards -->


                <!-- footer  -->

				<div style='Margin:0 auto;max-width:600px;min-width:320px;word-wrap:break-word;word-break:break-word'>
					<div style='border-collapse:collapse;display:table;width:100%'>
						<div style='text-align:left;font-size:12px;line-height:19px;color:#7A7A7A;font-family:Cabin,Avenir,sans-serif;Float:left;max-width:400px;min-width:320px;'>
							<div style='Margin-left:20px;Margin-right:20px;Margin-top:10px;Margin-bottom:10px'>
								<table style='border-collapse:collapse;table-layout:fixed'>
									<tbody>
										<tr>
											<td style='padding:0;width:26px'><a style='text-decoration:underline;color:#9dc4c4' href='http://kk.cmail2.com/t/d-i-ijlhttd-l-r/' target='_blank'><img style='border:0' src='https://ci4.googleusercontent.com/proxy/cdaOVwx01pydUCeWanZ5I0WsxDjvph7JzEiKY3zimkrOp-LjXcGnE1GadRLWYfIKzlmiYSOtzr-WjjHJdYebPiyRLHmWcDY2Zz_HAol546DebSYvB0BcePndD26qkP8w-AE=s0-d-e1-ft#http://i8.cmail2.com/static/eb/master/13-the-blueprint-3/images/facebook.png' width='26' height='26' class='CToWUd'></a></td>
											<td style='padding:0 0 0 3px;width:26px'><a style='text-decoration:underline;color:#9dc4c4' href='http://kk.cmail2.com/t/d-i-ijlhttd-l-y/' target='_blank'><img style='border:0' src='https://ci5.googleusercontent.com/proxy/H7Yt85uks7gPb4DmaC8HgjAqYMQhhSna9kYBtoUZr5D3lFKE-IJtZdN1MqyIopBh8YJYDX-igm7ScYklACfkd0Y1wvJ0BbBd3m1bcejcougYGa1dWg76ozQ-vG28HEqFDCbI=s0-d-e1-ft#http://i1.cmail2.com/static/eb/master/13-the-blueprint-3/images/instagram.png' width='26' height='26' class='CToWUd'></a></td>
										</tr>
									</tbody>
								</table>
								<div style='Margin-top:20px'>
									<div>Patisserie Sayvour Limited</div>
								</div>
								<div style='Margin-top:18px'>
									<div>Sayvour is an artisan confectionery specialising in handmade chocolates and pastries by using high quality ingredients from around the world.</div>
								</div>
							</div>
						</div>
						<div style='text-align:left;font-size:12px;line-height:19px;color:#9dc4c4;font-family:Cabin,Avenir,sans-serif;Float:left;max-width:320px;min-width:200px;'>
							<div style='Margin-left:20px;Margin-right:20px;Margin-top:10px;Margin-bottom:10px'></div>
						</div>
					</div>
				</div>
				<div style='Margin:0 auto;max-width:600px;min-width:320px;word-wrap:break-word;word-break:break-word'>
					<div style='border-collapse:collapse;display:table;width:100%'>
						<div style='text-align:left;font-size:12px;line-height:19px;color:#9dc4c4;font-family:Cabin,Avenir,sans-serif;max-width:600px;min-width:320px;'>
						</div>
					</div>
				</div>
				<div style='line-height:40px;font-size:40px'>&nbsp;</div>
			</div>
			<img style='overflow:hidden;display:block!important;min-height:1px!important;width:1px!important;border:0!important;margin:0!important;padding:0!important' src='https://ci4.googleusercontent.com/proxy/-HQ08vlGM2ltqJyXUtWXZlorkMV10CQ0pH8IJ2TQo0JNoLOLepN2GqRqjNvhCsxelytv0dohcw2kweEKYfPeyqw=s0-d-e1-ft#https://kk.cmail2.com/t/d-o-ijlhttd-l/o.gif' width='1' height='1' border='0' alt='' class='CToWUd'>
			<div class='yj6qo'></div>
			<div class='adL'></div>
		</div>
		<div class='adL'></div>
	</div>
</div>

                <!--End  footer  -->




		";

	$mail->AddAddress($email);
	if (!$mail->Send()) {
		error_log("Fail to send register email user:{$username} email:{$email}");
	} else {
		error_log("Register email sent user:{$username} email:{$email}");
	}

	if ($_SESSION["Tusername"]) {
		$Tusername = $_SESSION["Tusername"];
		$username = $_SESSION['username'];
		$id = $_SESSION['id'];
		$query = "UPDATE cart SET username = '$username' , id='$id' WHERE username = '$Tusername'";
		if ($result = mysqli_query($conn, $query)) {unset($_SESSION["Tusername"]);}
		$_SESSION["page"] = 2;
	}
}
?>
<html>
<head>
<!-- Facebook Pixel Code -->

<script>

!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?

n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;

n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;

t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,

document,'script','https://connect.facebook.net/en_US/fbevents.js');

fbq('init', '1251610718262776');

fbq('track', "PageView");

fbq('track', 'Lead');</script>

<noscript><img height="1" width="1" style="display:none"

src="https://www.facebook.com/tr?id=1251610718262776&ev=PageView&noscript=1"

/></noscript>

<!-- End Facebook Pixel Code -->
</head>
<body>
</body>
</html>