<?php
	require_once "pageBase.php";
	require_once "bin/web/tables/sends.php";
	require_once "dal/paypageDAL.php";
	require_once "dal/line_gearingDAL.php";
	require_once "function/function.php";
	class _paypage3 extends pageBase {
		public function load() {
			// 參數
			$dal = new paypageDAL();
			$hashKey = $this->registry->hashKey;
			$hashIV = $this->registry->hashIV;
			$mcID = $this->registry->merchantID;
			
			// 接收值
			$status = $_POST["Status"] ?? '';
			$merchantID = $_POST["MerchantID"] ?? '';
			$tradeInfo = $_POST["TradeInfo"] ?? '';
			$tradeSha = $_POST["TradeSha"] ?? '';
			$version = $_POST["Version"] ?? '';

			if (empty($status) || empty($merchantID) || empty($tradeInfo) || empty($tradeSha) || empty($version)) {
				$txtStatus = "缺少必要的 POST 參數!";
			} else {
				// 驗證
				$tradeText = "HashKey={$hashKey}&{$tradeInfo}&HashIV={$hashIV}";
				$reTradeSha = strtoupper(hash("sha256", $tradeText));

				// 回傳值解碼
				$txtJ = create_aes_decrypt($tradeInfo, $hashKey, $hashIV);
				$objJ = json_decode($txtJ);
				
				// 交易方式
				$paymentTypes = [
					"CREDIT" => "信用卡",
					"WEBATM" => "WebATM",
					"VACC" => "ATM轉帳",
					"CVS" => "超商代碼繳費",
					"BARCODE" => "超商條碼繳費",
					"CVSCOM" => "超商取貨付款",
				];
				$txtPT = $paymentTypes[$objJ->Result->PaymentType] ?? $objJ->Result->PaymentType;
				$txtPT .= "(藍新)";
			
				// 款項保管銀行
				$escrowBanks = [
					"Esun" => "玉山銀行",
					"Taishin" => "台新銀行",
					"HNCB" => "華南銀行",
				];
				$txtEB = $escrowBanks[$objJ->Result->EscrowBank] ?? $objJ->Result->EscrowBank;

				if ($merchantID != $mcID) {
					$txtStatus = "商店代號不吻合!";
				} else {
					if ($reTradeSha != $tradeSha) {
						$txtStatus = "檢核碼不吻合!";
					} else {
						if ($version == "1.5") {
							$sta = "-1";    //快速付款紀錄狀態，預設更新為失敗

							if ($status == "SUCCESS" && $objJ->Status == "SUCCESS") {
								$sta = "1";    //快速付款紀錄狀態，更新為成功
								$intoAry = [parent::addArray(":merchantOrderNo", $objJ->Result->MerchantOrderNo, "str", 30)];
								$filter = "a.`MerchantOrderNo`=:merchantOrderNo";
								$data = $dal->executeRecordset($intoAry, $filter);

								if (count($data) == 0) {
									$txtStatus = "找不到指定的付款紀錄!";
								} else if (count($data) > 1) {
									$txtStatus = "付款紀錄超過一筆!";
								} else {
									$txtStatus = ((int)$data[0]["Amt"] != (int)$objJ->Result->Amt) ? "金額和紀錄不吻合!" : "交易付款成功!";
		
									// 系統通知
									$sends = new sends();
									$sendMail = $this->getValidEmails();

									// 創建信件內容
									$mbody = "訂單編號:{$objJ->Result->MerchantOrderNo}<br />";
									$mbody .= "費用名稱:{$data[0]["ItemDesc"]}<br />";
									$mbody .= "費用金額:{$data[0]["Amt"]}<br />";
									$mbody .= "繳費方式:{$txtPT}<br />";
									$mbody .= "繳費時間:{$objJ->Result->PayTime}<br />";
									$mbody .= "繳費狀態:{$objJ->Message}<br />";
									$mbody .= "備註:{$data[0]["OrderComment"]}";
					
									$subject = "[" . $this->registry->webName . " " . $_SERVER['HTTP_HOST'] . "] [快速線上付款系統通知]" . $data[0]["ItemDesc"];
				
									//寄信
									if (count($sendMail) > 0) {
										if (empty($this->registry->sendMailType)) {
											$sends->sendemail($this->registry->webName, $this->registry->webEmail, $subject, $mbody, implode(",", $sendMail));
										} else {
											$sends->sendsmtpmail($subject, $mbody, $sendMail);
										}
									}
				
									// LINE 通知
									$dalL = new line_gearingDAL();
									$data = $dalL->executeRecordset([], "a.`LGID`!=0");
									$webName = ($this->registry->webName != "") ? ' 【' . $this->registry->webName . '】 ' : '';
									$text = '您的客戶在' . $webName . '使用快速線上付款，請盡快去後台查看!' . "\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"]);
									}
		
								}
							} else {
								$txtStatus = "交易付款失敗![{$aryEC[$status]}][{$aryEC[$objJ->Status]}]";
							}

							// 更新資料
							$replyIP = parent::getIP();
							$dal->ID = $data[0]["ID"];
							$dal->Status = $sta;
							$dal->ReStatus = $objJ->Status;
							$dal->ReMessage = $objJ->Message;
							$dal->TradeNo = $objJ->Result->TradeNo;
							$dal->PaymentType = $txtPT;
							$dal->PayTime = $objJ->Result->PayTime;
							$dal->PayIP = $objJ->Result->IP;
							$dal->ReplyIP = $replyIP;
							$dal->replyRecord();
						} else {
							$txtStatus = "回傳版本異常!";
						}
					}
				}
			}

			$txt = "[" . date("Y-m-d H:i:s") . "][{$txtStatus}]".PHP_EOL;
			$txt .= "交易結果(Status):{$status}".PHP_EOL;
			$txt .= "商店代號(MerchantID):{$merchantID}".PHP_EOL;
			$txt .= "版本(Version):{$version}".PHP_EOL;
			$txt .= "檢核碼(TradeSha):{$tradeSha}".PHP_EOL;
			$txt .= "驗證碼:{$reTradeSha}".PHP_EOL;
			$txt .= "回傳資料(TradeInfo):{$tradeInfo}".PHP_EOL;
			$txt .= "回傳JSON:{$txtJ}".PHP_EOL;
			$txt .= "回傳狀態(Status):{$objJ->Status}".PHP_EOL;
			$txt .= "回傳訊息(Message):{$objJ->Message}".PHP_EOL;
			$txt .= "回傳-商店代號(MerchantID):{$objJ->Result->MerchantID}".PHP_EOL;
			$txt .= "回傳-交易金額(Amt):{$objJ->Result->Amt}".PHP_EOL;
			$txt .= "回傳-智付通交易序號(TradeNo):{$objJ->Result->TradeNo}".PHP_EOL;
			$txt .= "回傳-商店訂單編號(MerchantOrderNo):{$objJ->Result->MerchantOrderNo}".PHP_EOL;
			$txt .= "回傳-支付方式(PaymentType):{$txtPT}({$objJ->Result->PaymentType})".PHP_EOL;
			$txt .= "回傳-回傳格式(RespondType):{$objJ->Result->RespondType}".PHP_EOL;
			$txt .= "回傳-支付完成時間(PayTime):{$objJ->Result->PayTime}".PHP_EOL;
			$txt .= "回傳-交易IP(IP):{$objJ->Result->IP}".PHP_EOL;
			$txt .= "回傳-款項保管銀行:{$txtEB}({$objJ->Result->EscrowBank})".PHP_EOL;
			
			file_put_contents("pay2go.txt", $txt, FILE_APPEND);
			parent::load();
		}

		private function getValidEmails() {
			$sendMail = [];
			for ($i = 1; $i <= 5; $i++) {
				$emailParam = $this->registry->{"systemEmail$i"};
				if (!empty($emailParam)) $sendMail[] = $emailParam;
			}
			return $sendMail;
		}
	}

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