<?php

session_start();

//檢查來�?
if (!isset($_POST['submit'])) {
	exit('Fail!');
}
include '../../conf/conn.php';

include_once "../../includes/core/initNoSession.php";

function errorHandler() {
	$params = '';
	if (func_num_args() > 0) {
		$params = implode(' , ', func_get_args());
	}
	$errorMsg = __FILE__ . __LINE__ . "\r\n" . $params . "\r\n";
	error_log($errorMsg, 3, "./errors.log");
	header("Location:http://" . $_SERVER['HTTP_HOST'] . "/en/404.html");
	die();
}

if (!isset($_POST['token'])) {
	errorHandler("No token", $_SESSION['username']);
}

//Find error/unknown entry/breach etc.
if (!isset($_SESSION['id'])) {
	error_log("Unrecognized user in paypal_checkout.php: '" . implode(" , ", $_SESSION) . "' \r\n", 0, "./errors.log");
	header("Location:http://" . $_SERVER['HTTP_HOST'] . "/en/404.html");
	die();
}
//The query is list as ascend because we need the last result
$cartCheckSql = "SELECT `time` from `cart` WHERE `username`= ? ORDER BY `time` ASC";
$cartCheckStmt = mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($cartCheckStmt, $cartCheckSql)) {

	mysqli_stmt_bind_param($cartCheckStmt, "s", $_SESSION['username']);
	mysqli_stmt_execute($cartCheckStmt);
	mysqli_stmt_bind_result($cartCheckStmt, $cartTime);

	$stmtResponse = mysqli_stmt_fetch($cartCheckStmt);
	if (empty($stmtResponse) || !$stmtResponse) {
		errorHandler('Unknown error', $_SESSION['username']);
	}
	if (!Token::check_PerForm($cartTime, $_POST['token'])) {
		errorHandler("Wrong Token", $_SESSION['username'], $cartTime, $_SESSION['tokenName'], $_POST['token']);
	}

	mysqli_stmt_close($cartCheckStmt);
} else {
	errorHandler();
}

//Temp reaction for verifty breach
$registerIp = $_SERVER['REMOTE_ADDR'];

//檢查來�?結�?
//?��?facebook pixel
echo "
<!DOCTYPE html>
<html lang=\"en\">
<head>
<style>
.hidden {
    display: none !important;
}
</style>

<!-- 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', {
em: 'insert_email_variable,'
});
fbq('track', 'PageView');

fbq('track', 'InitiateCheckout');


</script>
<noscript><img height=\"1\" width=\"1\" style=\"display:none\"
src=\"https://www.facebook.com/tr?id=1251610718262776&ev=PageView&noscript=1\"
/></noscript>
<!-- DO NOT MODIFY -->
<!-- End Facebook Pixel Code -->
</head>
";

//封�??��??��???
//清�??��??�數
function test_input($data) {
	$data = trim($data);
	$data = stripslashes($data);
	$data = implode("", explode("\\", $data));
	$data = htmlentities($data, ENT_QUOTES, "UTF-8");
	return $data;
}

$username = mysqlSecurity($conn, $_SESSION["username"]);
//$time=test_input($_POST["time"]);
$time = date("Y-m-d H:i:s");
//檢查?�否?��?輸入
$query = "select `record` from `orders` where username='$username' and time='$time' and `status` != 'delete';";
$result = mysqli_query($conn, $query);
if (mysqli_affected_rows($conn) > 0) {
	$_SESSION["page"] = 11;
	echo "
<script>
window.location.href=\"../e-shop.php\";
</script>
";
	exit();
}
//?��??�用?��??��?
//$query="select record from `orders` where username='$username' order by `orders`.`record` DESC limit 1";
$query = "select record from `orders` order by `orders`.`record` DESC limit 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rowinput = $row["record"] + 1;

$paypal = "SRI" . date("y") . "-" . sprintf("%'05d", $rowinput);
//檢查交�?類�?
if ($_GET["Payment_Type"] == 'Bank_Transfer') {
	$status = "bank";
} elseif ($_GET["Payment_Type"] == 'paypal') {
	$status = "perpare";
}
//檢查?�否?�使?�coupon
if ($_POST["discount_rate"] < 1) {
	$coupon_code = mysqlSecurity($conn, $_POST["code"]);

	//驗�?coupon
	$query = "select * from `coupon` where code='$coupon_code' and `status` != 'delete';";
	$result = mysqli_query($conn, $query);
	$row = mysqli_fetch_assoc($result);

	$sql_coupon_query = ",\r\n  `coupon_name`,\r\n  `coupon_code`";
	$sql_coupon_value = ",\r\n  '" . $row["coupon_name"] . "',\r\n  '" . $coupon_code . "'";

	$coupon_name = $row["coupon_name"];
	$usage_count = $row["usage_count"];
	$discount_rate = $row["discount_rate"];
} else {
	$discount_rate = 1;

	$sql_coupon_query = NULL;
	$sql_coupon_value = NULL;
}
$bought_items = test_input($_POST["bought_items"]);
$total = test_input($_POST["total"]);
$customer_first_name = test_input($_POST["customer_Fname"]);
$customer_last_name = test_input($_POST["customer_Lname"]);
$customer_email = test_input($_POST["customer_email"]);
$customer_phone = test_input($_POST["customer_phone"]);
$customer_address = preg_replace("/\r\n/", '<br>', test_input($_POST["customer_address"]));
$company_name = str_replace("*Optional", "", test_input($_POST["company_name"]));
$recipient_first_name = test_input($_POST["recipient_Fname"]);
$recipient_last_name = test_input($_POST["recipient_Lname"]);
$recipient_email = str_replace("*Optional", "", test_input($_POST["email"]));
$recipient_phone = test_input($_POST["phone"]);
$recipient_address = preg_replace("/\r\n/", '<br>', test_input($_POST["address"]));
$delivery_date = test_input($_POST["delivery_date"]);
$delivery_time = test_input($_POST["delivery_time"]);
$remarks = test_input($_POST["remarks"]);
$delivery_methods = test_input($_POST["delivery_methods"]);
//記�?購物車數??
//�?計數??
$count_value = 0;

$sub_total = 0;

$query = "select * from `cart` where `username` = '$username'";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
	if ($discount_rate == 1) {
		$product_name[$count_value] = $row["product_name"];
		$product_price[$count_value] = $row["price"];
		$product_amount[$count_value] = $row["amount"];
		$sub_total += $row["price"] * $row["amount"];
		$count_value++;
	} else {
		$product_name[$count_value] = $row["product_name"];
		if (isset($row["original_price"])) {
			$product_price[$count_value] = $row["original_price"];
		} else {
			$product_price[$count_value] = $row["price"];
		}
		$product_amount[$count_value] = $row["amount"];
		$sub_total += $row["original_price"] * $row["amount"];
		$count_value++;
	}
}
//?�斷?�費?��?袋費
$original_sub_total = $sub_total;
$sub_total = round($sub_total * $discount_rate, 1);

if ($delivery_methods == "SF Express Refrigerated Delivery Service") {
	if ($sub_total <= 800) {
		$product_name[$count_value] = "Delivery Fee";
		// $product_price[$count_value] = 48;
		$product_price[$count_value] = 0;
		$product_amount[$count_value] = 1;
		// $extra_fee = 48;
		$extra_fee = 0;
		$count_value++;
	} else {
		$product_name[$count_value] = "Delivery Fee";
		$product_price[$count_value] = 0;
		$product_amount[$count_value] = 1;
		$extra_fee = 0;
		$count_value++;
	}
} else {
	$product_name[$count_value] = "Plastic Bag Charge";
	$product_price[$count_value] = 1;
	$product_amount[$count_value] = 1;
	$extra_fee = 1;
	$count_value++;
}
$order_amount = $count_value;
$order_total = $sub_total + $extra_fee;
//�?計數??
$count_value = 0;
//封�??��??��??��???
//Temp reaction for sql breach
$tempRegSql = "INSERT INTO `tempBreach` (`orderID`,`ip`) VALUES ('{$paypal}','{$registerIp}')";
$tempRes = mysqli_query($conn, $tempRegSql);

//保�??��??��?
$query = "
INSERT INTO `orders`(
  `paypal id`,
  `bought_items`,
  `amount`,
  `username`,
  `customer Fname`,
  `customer Lname`,
  `customer phone`,
  `customer email`,
  `customer address`,
  `company name`,
  `recipient Fname`,
  `recipient Lname`,
  `phone`,
  `email`,
  `address`,
  `delivery date`,
  `delivery time`,
  `remarks`,
  `time`,
  `status`$sql_coupon_query
) VALUES (
  '$paypal',
  '$bought_items',
  '$total',
  '$username',
  '$customer_first_name',
  '$customer_last_name',
  '$customer_phone',
  '$customer_email',
  '$customer_address',
  '$company_name',
  '$recipient_first_name',
  '$recipient_last_name',
  '$recipient_phone',
  '$recipient_email',
  '$recipient_address',
  '$delivery_date',
  '$delivery_time',
  '$remarks',
  '$time',
  '$status'$sql_coupon_value
)";
error_log(date("Y-m-d H:i:s") . ":" . print_r($query, true) . "\r\n", 3, "../../order_insert.log");
$result = mysqli_query($conn, $query);
//保�??��??��?結�?
//?��?coupon使用記�?
if ($_POST["discount_rate"] < 1) {
	$usage_count--;
	$query = "UPDATE `coupon` SET `usage_count` = '$usage_count' WHERE `coupon`.`code` = '$coupon_code';";
	$result = mysqli_query($conn, $query);

	$query = "INSERT INTO `used_coupon` (`date`, `username`, `receipt_no`, `code`) VALUES ('$time', '$username', '$paypal', '$coupon_code')";
	$result = mysqli_query($conn, $query);
}
//?��?coupon使用記�?結�?
//?��?購物記�?
$query = "INSERT INTO `bought_item` (`paypal_id`, `username`, `product_name`, `price`, `amount`) VALUES ";

//�?計數??
$count_value = 0;
$Torder_amount = $order_amount - 1;

$query .= "('$paypal','$username','" . mysqli_real_escape_string($conn, $product_name[$count_value]) . "', '" . round($product_price[$count_value] * $discount_rate, 1) . "', '$product_amount[$count_value]')";
$count_value++;
while ($count_value < $Torder_amount) {
	$query .= ",('$paypal','$username','" . mysqli_real_escape_string($conn, $product_name[$count_value]) . "', '" . round($product_price[$count_value] * $discount_rate, 1) . "', '$product_amount[$count_value]')";
	$count_value++;
}
$query .= ",('$paypal','$username','" . mysqli_real_escape_string($conn, $product_name[$count_value]) . "', '$product_price[$count_value]', '$product_amount[$count_value]')";

$result = mysqli_query($conn, $query);

//�?計數??
$count_value = 0;

//?��?購物記�?結�?
//?�郵?��??��??�函??
function letter_change($data) {

	//Letter chocolate currently containing '<br><div>' tags,bypass if this is not a letter chocolate product
	if (stripos($data, "<br><div") === false) {
		return $data;
	}

	$data = htmlentities($data, ENT_QUOTES, "UTF-8");

	$data = str_replace('&hearts;', "??", $data);
	$data = str_replace('&amp;', "&", $data);
	$data = str_replace('&lt;br&gt;', "<br>", $data);

	$pattern = '/^(.*?)(?:<br>)/';
	$replace = '<p>$1</p><table><tr>';
	$data = preg_replace($pattern, $replace, $data, 1);

	$data = str_replace('&lt;div class=&quot;Dark&quot;&gt;', "<td><img style='max-width:100%; max-height:100%;' src ='http://www.sayvour.com.hk/img/letter/d_", $data);
	$data = str_replace('&lt;div class=&quot;White&quot;&gt;', "<td><img style='max-width:100%; max-height:100%;' src ='http://www.sayvour.com.hk/img/letter/w_", $data);
	$data = str_replace('&lt;div class=&quot;Pink&quot;&gt;', "<td><img style='max-width:100%; max-height:100%;' src ='http://www.sayvour.com.hk/img/letter/p_", $data);
	$data = str_replace('&lt;div class=&quot;Brown&quot;&gt;', "<td><img style='max-width:100%; max-height:100%;' src ='http://www.sayvour.com.hk/img/letter/b_", $data);
	$data = str_replace('&lt;/div&gt;', ".png' align ='left'></td>", $data);
	$data = str_replace('_?.', "_s1.", $data);
	$data = str_replace('_/.', "_s2.", $data);
	$data = str_replace('_:.', "_s3.", $data);
	$data = str_replace("_&#10084;", '_?��?�?', $data);
	$data = str_replace("_&#127801;", '_?��', $data);
	$data = str_replace("&#9825;", "_??", $data);
	$data = str_replace('><br><', "></tr><tr><", $data);

	$data .= "</tr></table>";

	return $data;
}

//寄送�??�電??
$maillist = '';

//�?計數??
$count_value = 0;

//準�??�郵訂單詳細
$order_amount;
while ($count_value < $order_amount - 1) {
	$maillist .= "
<div style='Margin-left:20px;Margin-right:20px; width:100%;'>
<table style='WIDTH:100%;BORDER-COLLAPSE:collapse;BORDER-SPACING:0; margin:10px 0px' cellspacing='0' cellpadding='0' width='100%' border='0'>
<tbody>
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='50%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
" . letter_change($product_name[$count_value]) . "
<u></u><u></u></span></p></td>
<td style='WIDTH:15%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
HK$
" . $product_price[$count_value] . "
<u></u><u></u></span></p></td>
<td style='WIDTH:10%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
" . $product_amount[$count_value] . "
<u></u><u></u></span></p></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
HK$" . $product_price[$count_value] * $product_amount[$count_value] . "
</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td></tr>
</tbody>
</table>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<div style='display:block;font-size:2px;line-height:2px;Margin-left:auto;Margin-right:auto;width:100%;background-color:#7cc3c3'>&nbsp;</div>
</div>";
	$count_value++;
}
$maillist .= "
<div style='Margin-left:20px;Margin-right:20px; width:100%;'>
<table style='WIDTH:100%;BORDER-COLLAPSE:collapse;BORDER-SPACING:0; margin:10px 0px' cellspacing='0' cellpadding='0' width='100%' border='0'>
<tbody>
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='45%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Sub-Total<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='20%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:25%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='22%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
HK$" . $original_sub_total .
	"</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td>
</tr>
  ";
if ($discount_rate < 1) {
	$maillist .= "
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='45%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Discount(%)<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='20%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:25%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='22%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
" . (100 - $discount_rate * 100) . "%
</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td>
</tr>
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='45%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Sub-Total After Discount<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='20%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:25%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='22%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
HK$" . $sub_total . "
</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td>
</tr>
	";
}
$maillist .= "
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='45%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
" . $product_name[$count_value] . "
<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='20%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:25%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='22%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>
HK$" . $product_price[$count_value] * $product_amount[$count_value] . "
</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td>
</tr>
</tbody>
</table>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<div style='display:block;font-size:2px;line-height:2px;Margin-left:auto;Margin-right:auto;width:100%;background-color:#7cc3c3'>&nbsp;</div>
</div>
  ";
//?�份?�郵貨�??�表資�?
$query = "INSERT INTO `email` (`paypal id`, `username`, `maillist`) VALUES ('$paypal','$username','";
$query .= mysqli_real_escape_string($conn, $maillist);
$query .= "')";
$result = mysqli_query($conn, $query);

//?��?交�??��?
if ($status == 'bank') {
	//?�行�?賬�??��???
	//?�送電??
	require_once '../../phpmailer/class.phpmailer.php';
	$mail = new PHPMailer();
	$mail->CharSet = "utf8";
	//$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 = "mail.station191.com";
	//$mail->Port = 587;

	$mail->addReplyTo("info@sayvour.com.hk", "Sayvour");
	$mail->AddAddress($customer_email);

	//Won't send to follow person in sandbox env.
	if (in_retail()) {
		$mail->AddBCC("daniel@at-creative.com");
		// $mail->AddBCC("edmondcheng@at-creative.com");
		$mail->AddBCC("info@sayvour.com.hk");
		$mail->AddBCC("marketing@sayvour.com.hk");
		$mail->AddBCC("catherine@sayvour.com.hk");
		$mail->AddBCC("sayvourhongkong@gmail.com");
	}
	$mail->IsHTML(true);
	$mail->setFrom("info@sayvour.com.hk", "Sayvour");
	$mail->Subject = "Thank you for your order from Sayvour";
	$body = "
<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 your order from Sayvour</h1>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<p style='Margin-top:0;Margin-bottom:0;text-transform: capitalize'>Dear&nbsp;" . $_POST["customer_Fname"] . ",</p><p style='Margin-top:20px;Margin-bottom:20px'>Thank you for your recent order on " . date('Y-m-d') . ". We would like to confirm the details as follows:</p>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<div style='line-height:20px;font-size:1px'>&nbsp;</div>
</div>
<!-- End Dear -->
<!-- Order Summary -->
<div style='Margin-left:20px;Margin-right:20px'>
<p style='Margin-top:0;Margin-bottom:20px;font-size:16px;line-height:24px' lang='x-size-16'><span style='color:#575757'><strong>Order Summary</strong></span></p>
</div>
<div style='Margin-left:20px;Margin-right:20px; width:100%;'>
<table style='WIDTH:100%;BORDER-COLLAPSE:collapse;BORDER-SPACING:0; margin:10px 0px' cellspacing='0' cellpadding='0' width='100%' border='0'>
<tbody>
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='50%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Product Name<u></u><u></u></span></p></strong></td>
<td style='WIDTH:15%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Unit Price<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Quantity<u></u><u></u></span></p></strong></td>
<td style='WIDTH:10%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='25%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Amount</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td></tr>
</tbody>
</table>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<div style='display:block;font-size:2px;line-height:2px;Margin-left:auto;Margin-right:auto;width:100%;background-color:#7cc3c3'>&nbsp;</div>
</div>"
		. $maillist .
		"<div style='Margin-left:20px;Margin-right:20px; width:100%;'>
<table style='WIDTH:100%;BORDER-COLLAPSE:collapse;BORDER-SPACING:0; margin:10px 0px' cellspacing='0' cellpadding='0' width='100%' border='0'>
<tbody>
<tr>
<td style='WIDTH:45%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='45%'>
<strong><p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>Total<u></u><u></u></span></p></strong></td>
<td style='WIDTH:20%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='20%'>
<p class='MsoNormal' style='LINE-HEIGHT:12.75pt'><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:25%;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='22%'>
<p class='MsoNormal' style='TEXT-ALIGN:right;LINE-HEIGHT:12.75pt' align='right'><strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'>HK$" . $order_total . "</span></strong><span style='FONT-SIZE:9pt;FONT-FAMILY:&quot;Helvetica&quot;,sans-serif;COLOR:#333333'><u></u><u></u></span></p></td>
<td style='WIDTH:0.3pt;PADDING-BOTTOM:0in;PADDING-TOP:0in;PADDING-LEFT:0in;PADDING-RIGHT:0in' valign='top' width='1'></td></tr>
</tbody>
</table>
</div>
<!-- End Order Summary -->
<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'>
<div style='line-height:5px;font-size:1px'>&nbsp;</div>
</div>
<!-- Best regards -->
<div style='Margin-left:20px;Margin-right:20px'>
<strong>Order Details:</strong>
<table style='Margin-top:0;Margin-bottom:20px;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>
<tr><td>Name:</td><td> " . $customer_first_name . " " . $customer_last_name . "</td></tr>
<tr><td>Email:</td><td> " . $customer_email . "</td></tr>
<tr><td>Phone:</td><td> " . $customer_phone . "</td></tr>
<tr><td valign='top'>Company Name:</td><td> " . $company_name . "</td></tr>
</table>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<div style='line-height:10px;font-size:1px'>&nbsp;</div>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
<strong>Delivery Details:</strong>
<table style='Margin-top:0;Margin-bottom:20px;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>
<tr><td>Name:</td><td> " . $recipient_first_name . " " . $recipient_last_name . "</td></tr>
<tr><td>Email:</td><td> " . $recipient_email . "</td></tr>
<tr><td>Phone:</td><td> " . $recipient_phone . "</td></tr>";

	if ($delivery_methods == "SF Express Refrigerated Delivery Service") {
		$body .= "
    <tr><td valign='top'>Delivery Methods:</td><td> " . $delivery_methods . "</td></tr>
    <tr><td valign='top'>Address:</td><td> " . $recipient_address . "</td></tr>
    <tr><td valign='top'>Delivery Time:</td><td> " . $delivery_date . " " . $delivery_time . "</td></tr>
  ";
	} else {
		$body .= "
    <tr><td valign='top'>Delivery Methods:</td><td> " . $delivery_methods . "</td></tr>
    <tr><td valign='top'>Pick Up Time:</td><td> " . $delivery_date . "</td></tr>
  ";
	}

	$body .= "
<tr><td valign='top'>Remarks:</td><td> " . $remarks . "</td></tr>
</table>
</div>
<div style='Margin-left:20px;Margin-right:20px'><p style='Margin-top:0;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>Payment Method: Bank Transfer</p>
<p style='Margin-top:0;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>
Please note that the order will only be confirmed once the payment is settled. The date of delivery may be affected if the transfer is delayed. We will prepare the chocolates freshly by hand and deliver to your designated address accordingly.
Once you have deposited the payment, please send us an email with your payment slip to info@sayvour.com.hk and specify your order number as follows:
<br>
<p style='color:red;display:inline;'>" . $paypal . "  (Please put it on the subject for easy reference)</p>
<br>
</div>
<div style='Margin-left:20px;Margin-right:20px;color:#58ACFA'>
<p style='Margin-top:0;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>
<strong>Company Account Details:</strong><br>
Company Name:  Patisserie Sayvour Limited<br>
Beneficiary's Bank Name: HSBC       <br>
Beneficiary's Account no.  : 023-462187-838<br>
SWIFT address: HSBCHKHHHKH<br>
Bank address: 1 Queen's Road Central, Hong Kong<br>
<br>
</div>
<div style='Margin-left:20px;Margin-right:20px'>
";

	if ($delivery_methods == "SF Express Refrigerated Delivery Service") {
		$body .= "
<p style='Margin-top:0;Margin-bottom:20px;font-size:14px;line-height:21px;text-align:left' lang='x-size-14'>Refrigerated Delivery: All our chocolates are made to order and will be delivered to your designated address according to your schedule.</p>
";
	}

	$body .= "
<p>Should you have further enquiry, please feel free to contact us at +852 2951 0005.<br><br>
Thank you once again for supporting Sayvour. We hope that you and your loved ones will savour every mouthful of our delicacies and every moment of receiving the personalised gifts made by us.</p>
</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: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>
  ";
	$mail->Body = $body;
	$mail->Send();
	//寄送�??�郵件�???
	//?�除購物車�???
	$query = "DELETE FROM `cart` WHERE `cart`.`username` = '$username'";
	$result = mysqli_query($conn, $query);
	//?��?html結尾
	echo "
    <body>
    </body>
    </html>
  ";
} elseif ($status == 'perpare') {
	//paypal訂單?��?

	echo '
<body>
<form method="post" name="paypal_form" id="paypal_form" action="https://www'
		. (in_sandbox() ? '.sandbox' : '') . '.paypal.com/cgi-bin/webscr">
<input class="hidden" name="rm" value="2"/>
<input class="hidden" name="cmd" value="_cart"/>
<input class="hidden" name="custom" value="' . $paypal . '"/>
<input class="hidden" name="business" value="' . (in_sandbox() ? 'info-facilitator' : 'info') . '@sayvour.com.hk"/>
<!-- Where people will be sent after a successful order -->
<input class="hidden" name="return" value="http://' . $_SERVER['SERVER_NAME'] . '/en/Complete_purchase.php?url=' . $_SERVER['SERVER_NAME'] . '"/>
<!-- Where people will be sent after a cancelled order -->
<input class="hidden" name="cancel_return" value="http://' . $_SERVER['SERVER_NAME'] . '/en/e-shop.php?page=12"/>
<!-- The location of your IPN. PayPal needs to know this so it knows where to send the infomation about the order -->
<input class="hidden" name="notify_url" value="http://' . $_SERVER['SERVER_NAME'] . '/paypal.php"/>
<input class="hidden" name="quantity" value="2"/>
<input class="hidden" name="charset" value="utf-8"/> ';

	//�?計數??
	$count_value = 0;
	$Torder_amount = $order_amount - 1;
	while ($count_value < $Torder_amount) {
		$number = $count_value + 1;

		$item_name = str_replace('<div class="Dark">', 'D.', $product_name[$count_value]);
		$item_name = str_replace('<div class="White">', 'W.', $item_name);
		$item_name = str_replace('<div class="Pink">', 'P.', $item_name);
		$item_name = str_replace('<div class="Brown">', 'B.', $item_name);
		$item_name = str_replace('</div>', '_', $item_name);
		$item_name = htmlentities($item_name, ENT_QUOTES, "UTF-8");

		$item_amount = round($product_price[$count_value] * $discount_rate, 1);

		echo "<input class=\"hidden\" name=\"item_name_$number\" value=\"$item_name\" />";
		echo "<input class=\"hidden\" name=\"amount_$number\" value=\"$item_amount\" />";
		echo "<input class=\"hidden\" name=\"quantity_$number\" value=\"$product_amount[$count_value]\" />";
		$count_value++;
	}
	$number = $count_value + 1;

	echo "<input class=\"hidden\" name=\"item_name_$number\" value=\"$product_name[$count_value]\" />";
	echo "<input class=\"hidden\" name=\"amount_$number\" value=\"$product_price[$count_value]\" />";
	echo "<input class=\"hidden\" name=\"quantity_$number\" value=\"$product_amount[$count_value]\" />";
	//�?計數??
	$count_value = 0;

	echo '
<input class="hidden" name="upload" value="1"/>
<input class="hidden" name="txn_type" value="cart"/>
<input class="hidden" name="currency_code" value="HKD"/>
<input  class="hidden" type="submit" name="place-order" value="Place Order">
</form>
<script>document.getElementById("paypal_form").submit();</script>
</body>
</html>
  ';

	exit();
}
//交�??��?結�?
//跳�??�主�?
$_SESSION["page"] = 11;
echo "
<script>
window.location.href=\"../e-shop.php\";
</script>
";
//跳�??�主站�??
