<?php
	require_once "pageBase.php";
	require_once "bin/web/repeater.php";
	require_once "bin/web/tables/sends.php";
	require_once "dal/orderDAL.php";
	require_once "dal/productDAL.php";
	require_once "dal/pictureDAL.php";
	require_once "dal/line_gearingDAL.php";
	class _order extends pageBase {
		public $product;
		public $order;
		private $dal;
	
		public function load() {
			if ($this->registry->webType != "20") {
				$this->alertMsg = "線上訂單功能製作中!";
				$this->locationHref = "/";
				return;
			}

			$this->dal = new productDAL();
			$this->product = new product();
			$this->order = new order();
			parent::isPostBack() ? $this->saveData() : $this->loadData();
			parent::loadTemplateFile("templates/{$this->registry->webTemplates}/order.html");
			parent::load();
		}
		
		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "120";
			
			// 線上訂單標題
			parent::addParameter("OrderName", $this->registry->OrderName);

			//線上購物說明
			parent::addParameter("webOrder", $this->registry->webOrder);

			//網站資訊
			$isShow = false;
			$webInfoStyle = " style=\"display:none;\"";
			$fields = [
				"webEmail" => ["webEmailisShow", "webEmailStyle", ""],
				"webAddress" => ["webAddressisShow", "webAddressStyle", "webAddressLink"],
				"webPhone" => ["webPhoneisShow", "webPhoneStyle", ""],
				"webMobile" => ["webMobileShow", "webMobileStyle", ""],
				"webFax" => ["webFaxisShow", "webFaxStyle", ""],
			];
			foreach ($fields as $field => $properties) {
				[$isShowProperty, $styleProperty, $linkProperty] = $properties;
    
				$$styleProperty = " style=\"display:none;\"";
				$$linkProperty = "javascript:void(0);";
				
				if (!empty($this->registry->$field) && $this->registry->$isShowProperty == 1) {
					$isShow = true;
					$$field = $this->registry->$field;
					$$styleProperty = "";
				
					if ($field === "webAddress") {
						$$linkProperty = !empty($this->registry->$field) ? "https://maps.google.com/maps?ll=23.016519,120.21529&z=15&t=m&hl=zh-TW&gl=US&mapclient=embed&q=" . urlencode($this->registry->$field) : "javascript:void(0);";
					}
					parent::addParameter($linkProperty, $$linkProperty);
				}
				parent::addParameter($field, $$field ?? "");
				parent::addParameter($styleProperty, $$styleProperty);
			}
			if ($isShow) $webInfoStyle = "";
			parent::addParameter("webInfoStyle", $webInfoStyle);
			
			// Google MAP
			$googlemapAddress = (!empty($this->registry->googlemapAddress)) ? urlencode($this->registry->googlemapAddress) : "";
			$googlemapStyle = (!empty($this->registry->googlemapAddress)) ? "" : " style='display:none;'";
			parent::addParameter("googlemapAddress", $googlemapAddress);
			parent::addParameter("googlemapStyle", $googlemapStyle);
			
			// 網站資訊是否顯示
			$arySN = explode(",", $this->registry->sideNavShow);
			$sideNavStyle = in_array($this->picturetype, $arySN) ? "" : " style=\"display:none;\"";
			parent::addParameter("sideNavStyle", $sideNavStyle);

			// 購物車
			$total = 0;
			$aryCP = [];
			$flag = 0;
			if (isset($_COOKIE["cart"]) && !empty($_COOKIE["cart"])) {
				$cart = $_COOKIE["cart"];
				if (!preg_match("/^[\d,;]+$/", $cart)) {
					setcookie("cart", "", 0, "/");
					$this->alertMsg = "購物車記錄異常已被清空!請重新購買!";
					$this->goBack = "Y";
					return false;
				}

				$aryC = $this->order->cart_decode($cart);
				$aryNC = [];

				foreach ($aryC as $rows) {
					$this->dal->ProductID = $rows["id"];
					$this->dal->loadRecord();

					if ($this->isProductValid($this->dal)) {
						$aryNC[] = ["id" => $rows["id"], "q" => $rows["q"]];
						$productData = $this->getProductData($this->dal, $rows["q"]);
						$total += $productData["amount"];
						$aryCP[] = $productData;
					} else {
						$flag++;
					}
				}

				$newCart = $this->order->cart_encode($aryNC);
				setcookie("cart", $newCart, 0, "/");
			} else {
				$this->alertMsg = "購物車是空的!";
				$this->locationHref = "/";
				return false;
			}

			if ($flag > 0) $this->alertMsg = "購物車中有被下架的產品，已經自動移除，請重新整理頁面確認!";
			
			$listCP = new repeater();
			$listCP->id = "listCP";
			$listCP->dataSource = $aryCP;
			parent::addControl($listCP);

			$tprice = 0;
			$transPrice = (int)$this->registry->transPrice;
			$transFreePrice = (int)$this->registry->transFreePrice;

			if ($transFreePrice === 0 || !is_numeric($transFreePrice)) {
				$tprice = $transPrice;
			} elseif ($total < $transFreePrice) {
				$tprice = $transPrice;
			}

			$oprice = $total + $tprice;
			
			// 使用 sprintf 函數將數字轉換為字串格式，以避免使用過時的 `string()` 函數
			parent::addParameter("ProductPrice", sprintf("%d", $total));
			parent::addParameter("TransPrice", sprintf("%d", $tprice));
			parent::addParameter("OrderPrice", sprintf("%d", $oprice));
			
			// 結構化資料
			$GoogleSearch = $this->order->seoGoogleSearch();
			parent::addParameter("GoogleSearch", $GoogleSearch);

			//TKD
			if (!empty($this->registry->orderTitle)) parent::addParameter("webTitle", $this->registry->orderTitle);
			if (!empty($this->registry->orderKeyword)) parent::addParameter("webKeyword", $this->registry->orderKeyword);
			if (!empty($this->registry->orderDescription)) parent::addParameter("webDescription", $this->registry->orderDescription);
			
			parent::loadData();
		}

		private function saveData() {
			//宣告
			$dalO = new orderDAL();
			$dalP = new pictureDAL();
			
			// logo
			$logo = parent::getLogo();

			// 檢查驗證碼
			$checknum = parent::getPost("Checknum");
			if ($checknum !== $_SESSION["dd_ckstr"] || !isset($_SESSION["dd_ckstr"]) || empty($_SESSION["dd_ckstr"])) {
				$this->alertMsg = "驗證碼輸入錯誤喔";
				$this->goBack = "Y";
				return;
			}

			// 購物車
			$total = 0;
			$aryCP = [];
			$flag = 0;
			
			if (isset($_COOKIE["cart"]) && !empty($_COOKIE["cart"])) {
				$cart = $_COOKIE["cart"];
				if (!preg_match("/^[\d,;]+$/", $cart)) {
					setcookie("cart", "", 0, "/");
					$this->alertMsg = "購物車記錄異常已被清空!請重新購買!";
					$this->goBack = "Y";
					return false;
				}

				$aryC = $this->order->cart_decode($cart);
				$aryNC = [];
			
				foreach ($aryC as $rows) {
					$this->dal->ProductID = $rows["id"];
					$this->dal->loadRecord();

					if ($this->isProductValid($this->dal)) {
						$aryNC[] = ["id" => $rows["id"], "q" => $rows["q"]];
						$productData = $this->getProductData($this->dal, $rows["q"]);
						$total += $productData["amount"];
						$aryCP[] = $productData;
						$dalO->OrderProduct[] = ["ProductID" => $productData["id"], "Price" => $productData["price"], "Quantity" => $productData["q"]];
					} else {
						$flag++;
					}
				}

				$newCart = $this->order->cart_encode($aryNC);
				setcookie("cart", $newCart, 0, "/");
			} else {
				$this->alertMsg = "購物車是空的!";
				$this->locationHref = "/";
				return false;
			}
			if ($flag > 0) {
				$this->alertMsg = "購物車中有被下架的產品，已經自動移除，請重新整理頁面確認!";
				$this->goBack = "Y";
				return false;
			}

			$tprice = 0;
			$transPrice = (int)$this->registry->transPrice;
			$transFreePrice = (int)$this->registry->transFreePrice;

			if ($transFreePrice === 0 || !is_numeric($transFreePrice)) {
				$tprice = $transPrice;
			} elseif ($total < $transFreePrice) {
				$tprice = $transPrice;
			}

			$oprice = $total + $tprice;
			if ($total != parent::getPost("PPrice")) {
				$this->alertMsg = "產品金額異常!";
				$this->goBack = "Y";
				return false;
			}
			if ($tprice != parent::getPost("TPrice")) {
				$this->alertMsg = "運費異常!";
				$this->goBack = "Y";
				return false;
			}
			if ($oprice != parent::getPost("OPrice")) { 
				$this->alertMsg = "總計金額異常!";
				$this->goBack = "Y";
				return false;
			}
			$dalO->ProductPrice = $total;
			$dalO->TransPrice = $tprice;
			$dalO->Name = parent::getPost("Name", "", 4);
			if($dalO->Name == ""){
				$this->alertMsg = "姓名不可空白!";
				$this->goBack = "Y";
				return false;
			}
			$dalO->Email = parent::getPost("Email", "", 4);
			if($dalO->Email == ""){
				$this->alertMsg = "信箱不可空白!";
				$this->goBack = "Y";
				return false;
			}else if(!preg_match("/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-]+(\.[A-Za-z0-9_\-]+)+$/", $dalO->Email)){
				$this->alertMsg = "信箱格式異常!";
				$this->goBack = "Y";
				return false;
			}
			$dalO->Phone = parent::getPost("Phone", "", 4);
			$dalO->Mobile = parent::getPost("Mobile", "", 4);
			if($dalO->Mobile == ""){
				$this->alertMsg = "手機不可空白!";
				$this->goBack = "Y";
				return false;
			}
			$dalO->Address = parent::getPost("Address", "", 4);
			if($dalO->Address == ""){
				$this->alertMsg = "地址不可空白!";
				$this->goBack = "Y";
				return false;
			}
			$dalO->Content = parent::getPost("Content", "", 4);
			$dalO->CreatedIP = parent::getIP();

			// 創建信件內容
			$txt = '<table border="1" align="center" cellpadding="0" cellspacing="0" style="width:660px; border:1px #000 solid;">';
			if (!empty($logo)) $txt .= '<tr><td colspan="4" style="border:0; border-bottom:1px #ccc solid; text-align:center;"><img src="' . $logo . '" style="margin:30px;" /></td></tr>';
			$txt .= '<tr style="background:#E7E7E7;border-left:0;">';
			$txt .= '<th style="border-left:0;">產品名稱&nbsp;&nbsp;</th>';
			$txt .= '<th style="border-left:0;">單價&nbsp;&nbsp;</th>';
			$txt .= '<th style="border-left:0;">數量&nbsp;&nbsp;</th>';
			$txt .= '<th style="border-left:0;">小計&nbsp;&nbsp;</th>';
			$txt .= '</tr>';
			foreach ($aryCP as $rows) {
				$image = ($rows["image"] != $this->NoPicImage) ? '<img src="' . $this->setImaageLink($rows["image"]) . '" width="50" height="50">' : '';
				$txt .= '<tr>';
				$txt .= '<td><a href="' . parent::getProtocol() . '://' . $_SERVER['HTTP_HOST'] . $rows["link"] . '" target="_blank">' . $image . $rows["name"] . '</a></td>';
				$txt .= '<td>' . $rows["price"] . '</td>';
				$txt .= '<td>' . $rows["q"] . '</td>';
				$txt .= '<td>' . $rows["amount"] . '</td>';
				$txt .= '</tr>';
			}
			$txt .= '<tr><td colspan="4" style="padding:10px;text-align:right;">產品金額：' . $total . '</td></tr>';
			$txt .= '<tr><td colspan="4" style="padding:10px;text-align:right;">運費：' . $tprice . '</td></tr>';
			$txt .= '<tr><td colspan="4" style="padding:10px;text-align:right;">總計：' . $oprice . '</td></tr>';
			$txt .= '</table><br />';
			$txt .= '<table border="1" align="center" cellpadding="0" cellspacing="0" style="width:660px; border:1px #000 solid;">';
			$arr_mail = [
				[ 'label' => '姓名', 'value' => $dalO->Name  . ' 先生/小姐' , 'ischk' => false ],
				[ 'label' => '手機', 'value' => $dalO->Phone , 'ischk' => false ],
				[ 'label' => '地址', 'value' => $dalO->Address , 'ischk' => false ],
				[ 'label' => '信箱', 'value' => $dalO->Email , 'ischk' => true ],
				[ 'label' => '備註', 'value' => str_replace("\r\n", "<br />", strip_tags($dalO->Content)) , 'ischk' => false ],
			];
			foreach ($arr_mail as $key => $item) {
				$style = (($key + 1) % 2 == 0) ? ' style="background:#E7E7E7;"' : '';
				if (!$item['ischk']) $chk .= str_replace([" ", "/"], "", $value);
			
				$txt .= '<tr' . $style . '>';
				$txt .= '<td style="padding:10px;width:200px;border:0;border-bottom:1px #ccc solid;">' . htmlspecialchars($item['label']) . '：</td>';
				$txt .= '<td style="padding:10px;border:0;border-bottom:1px #ccc solid;">' . htmlspecialchars($item['value']) . '</td>';
				$txt .= '</tr>';
			}
			$txt .= '</table><br />';
	
			// 系統信件內容（通知信）
			$mailtxt = $this->handleMailHTML($txt, 0);

			// 系統信件內容（確認信）
			$mailtxt2 = $this->handleMailHTML($txt, 1);

			// 寄送郵件
			$sends = new sends();
			$sendMail = $this->getValidEmails();

			if (!$dalO->insertRecord()) {
				$this->alertMsg = "很抱歉!線上訂單送出不成功!";
				$this->goBack = "Y";
				return;
			}

			$subject = "[" . $this->registry->webName . " " . $_SERVER['HTTP_HOST'] . "] [線上訂單系統通知]";
			$subject2 = "[" . $this->registry->webName . " " . $_SERVER['HTTP_HOST'] . "] [線上訂單系統確認信]";

			// 寄信檢查
			$mailflag = 0;
			if (count($sendMail) > 0) {
				if (empty($this->registry->sendMailType)) {
					if (!$sends->sendemail($dalO->Name, $dalO->Email, $subject, $mailtxt, implode(",", $sendMail))) $mailflag = 1;
				} else {
					if (!$sends->sendsmtpmail($subject, $mailtxt, $sendMail)) $mailflag = 1;
				}
			}

			if ($mailflag == 0) {
				if (empty($this->registry->sendMailType)) {
					$sends->sendemail($this->registry->webName, $dalO->Email, $subject2, $mailtxt2, $dalO->Email);
				} else {
					$to2Ary = [$dalO->Email];
					$sends->sendsmtpmail($subject2, $mailtxt2, $to2Ary);
				}

				// LINE 通知
				$dalL = new line_gearingDAL();
				$data = $dalL->executeRecordset([], "a.`LGID`!=0");
				$webName = ($this->registry->webName != "") ? ' 【' . $this->registry->webName . '】 ' : '';
				$text = '您的客戶在' . $webName . '線上購物中有訂購商品，訂單金額是' . $oprice . '元。' . "\n" . '請盡快去後台查看!' . "\n" . '網站後台:' . $_SERVER['HTTP_HOST'] . '/iweb';
				for ($i = 0; $i < count($data); $i++) {
					$data[$i]["name"] = ($data[$i]["TargetType"] == "1") ? $data[$i]["Target"] . '您好:' . "\n" : '';
					$sends->linemessage($data[$i]["name"] . $text, $data[$i]["AccessToken"]);
				}

				$this->alertMsg = "線上訂單已經送出!我們會盡快處理您的訂單!";
				$this->locationHref = "/";
			} else {
				$this->alertMsg = "很抱歉!線上訂單送出不成功!!";
				$this->goBack = "Y";
			}
		}
		
		// 函數：檢查產品是否有效
		private function isProductValid($productData) {
			return ($productData->Visible == "1" || $productData->Disable == "0") &&
				($productData->CategoryVisible == "1" || $productData->CategoryDisable == "0") &&
				($productData->ParentID == "0" || $productData->ParentVisible == "1" || $productData->ParentDisable == "0") &&
				($productData->ParentID == "0" || $productData->GrandID == "0" || $productData->GrandVisible == "1" || $productData->GrandDisable == "0");
		}
		
		// 函數：取得產品資訊
		private function getProductData($productData, $quantity) {
			$pid = $productData->ProductID;
			$pno = $productData->ProductNO;
			$pname = $productData->ProductName;
			$price = $productData->Price;
			$pimg = (!empty($productData->IconImage) && parent::image_exists($productData->IconImage)) ? $productData->IconImage : $this->NoPicImage;
			$amount = (int)$price * (int)$quantity;
			$link = $this->product->linkProductDetail($pid);
		
			return ["id" => $pid, "no" => $pno, "name" => $pname, "price" => $price, "image" => $pimg, "q" => $quantity, "amount" => $amount, "link" => $link];
		}

		private function setImaageLink($img) {
			if (preg_match("/^\/\//", $img)) $img = parent::getProtocol() . ":" . $img;
			if (!preg_match("/^https?:\/\//", $img)) $img = parent::getProtocol() . "://" . $_SERVER["HTTP_HOST"] . $img;
			return $img;
		}

		private function getValidEmails() {
			$sendMail = [];
			for ($i = 1; $i <= 5; $i++) {
				$emailParam = $this->registry->{"systemEmail$i"};
				if (!empty($emailParam)) $sendMail[] = $emailParam;
			}
			return $sendMail;
		}
		
		// 建立系統信件內容
		public function handleMailHTML($txt = "", $type = 0):string {
			$welcomeHtml = ($type == 1) ? '<p style="padding:10px; color:#f00; font-weight:bolder;">親愛的顧客您好，非常感謝您的訂購。<br />我們已收到您的訂單，我們客服人員會在第一時間，為您出貨，請你耐心等候。</p><br />' : '<p style="padding:10px; color:#f00; font-weight:bolder;">此信件為系統自動發送!請勿直接回覆!</p>';

			return <<<HTML
			<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			<html xmlns="https://www.w3.org/1999/xhtml">
			<head>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			</head>
			<body>
				{$welcomeHtml}
				{$txt}
				<p style="padding:10px; color:#f00; font-weight:bolder;">此信件為系統自動發送!請勿直接回覆!</p>
			</body>
			</html>
			HTML;
		}
	}

	$page = new _order();
	$page->load();
	$page->render();
?>