<?php
	require_once "pageBase.php";
	require_once "bin/system/ECPay.Payment.Integration.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 _paypage4 extends pageBase {
		public function load() {
			try {
				/* 快速付款 */
				$dal = new paypageDAL();

				/* 綠界 SDK */
				$obj = new ECPay_AllInOne();
				
				// 服務參數
				$obj->HashKey = $this->registry->ecpay_hashKey;
				$obj->HashIV = $this->registry->ecpay_hashIV;
				$obj->MerchantID = $this->registry->ecpay_merchantID;
				$obj->EncryptType = ECPay_EncryptType::ENC_SHA256;

				// 接收
				$feedback = $obj->CheckOutFeedback();
				
				// 付款方式
				$paymentType = "異常";
				$aryPT = explode("_", $feedback["PaymentType"]);
				
				if (isset($aryPT[0])) {
					$paymentTypes = [
						"WebATM" => "WebATM",
						"ATM" => "ATM",
						"CVS" => "超商代碼",
						"BARCODE" => "超商條碼",
						"Credit" => "信用卡",
					];
					$paymentType = $paymentTypes[$aryPT[0]] ?? "異常";
				}
				$paymentType .= "(綠界)";
				
				$status = ($feedback['RtnCode'] == '1') ? '1' : '-1';
				$merchantOrderNo = $feedback['MerchantTradeNo'];
				$reStatus = $feedback['RtnCode'];
				$reMessage = $feedback['RtnMsg'];
				$tradeNo = $feedback['TradeNo'];
				$payTime = date("Y-m-d H:i:s", strtotime($feedback['PaymentDate']));
				$replyIP = parent::getIP();

				if ($this->registry->ecpay_merchantID != $feedback['MerchantID']) {
					$txtStatus = "商店代號不吻合!";
				} elseif($status == '-1') {
					$txtStatus = "交易付款失敗![".$reStatus."][".$reMessage."]";
				} else {
					$intoAry = [parent::addArray(":merchantOrderNo", $feedback['MerchantTradeNo'], "str", 30)];
					$filter = "a.`MerchantOrderNo`=:merchantOrderNo";
					$data = $dal->executeRecordset($intoAry, $filter);
					
					if (count($data) == 0) {
						$txtStatus = "找不到指定的付款紀錄!";
					} elseif(count($data) > 1) {
						$txtStatus = "付款紀錄超過一筆!";
					} else {
						$txtStatus = ((int)$data[0]["Amt"] != (int)$feedback['TradeAmt']) ? "金額和紀錄不吻合!" : "交易付款成功!";
						
						// 系統通知
						$sends = new sends();
						$sendMail = $this->getValidEmails();

						// 創建信件內容
						$mbody = "訂單編號:{$merchantOrderNo}<br />";
						$mbody .= "費用名稱:{$data[0]["ItemDesc"]}<br />";
						$mbody .= "費用金額:{$data[0]["Amt"]}<br />";
						$mbody .= "繳費方式:{$paymentType}<br />";
						$mbody .= "繳費時間:{$payTime}<br />";
						$mbody .= "繳費狀態:{$reMessage}<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"]);
						}
						
						// 更新資料
						$replyIP = parent::getIP();
						$dal->ID = $data[0]["ID"];
						$dal->Status = $status;
						$dal->ReStatus = $reStatus;
						$dal->ReMessage = $reMessage;
						$dal->TradeNo = $tradeNo;
						$dal->PaymentType = $paymentType;
						$dal->PayTime = $payTime;
						$dal->PayIP = "";
						$dal->ReplyIP = $replyIP;
						$dal->replyRecord();
					}
				}

				$txt = "[".date("Y-m-d H:i:s")."][".$txtStatus."]".PHP_EOL;
				$txt .= "交易結果(Status):".$status.PHP_EOL;
				$txt .= "檢查碼(CheckMacValue):".$_POST["CheckMacValue"].PHP_EOL;
				$txt .= "回傳狀態(RtnCode):".$reStatus.PHP_EOL;
				$txt .= "回傳訊息(RtnMsg):".$reMessage.PHP_EOL;
				$txt .= "回傳-商店代號(MerchantID):".$feedback["MerchantID"].PHP_EOL;
				$txt .= "回傳-商店訂單編號(MerchantTradeNo):".$feedback["MerchantTradeNo"].PHP_EOL;
				$txt .= "回傳-智付通交易序號(TradeNo):".$feedback["TradeNo"].PHP_EOL;
				$txt .= "回傳-交易金額(TradeAmt):".$feedback["TradeAmt"].PHP_EOL;
				$txt .= "回傳-支付完成時間(PaymentDate):".$feedback["PaymentDate"].PHP_EOL;
				$txt .= "回傳-支付方式(PaymentType):".$paymentType."(".$feedback["PaymentType"].")".PHP_EOL;
				$txt .= "回傳-通路費(PaymentTypeChargeFee):".$feedback["PaymentTypeChargeFee"].PHP_EOL;
				$txt .= "回傳-訂單成立時間(TradeDate):".$feedback["TradeDate"].PHP_EOL;
				file_put_contents("ecpay.txt", $txt, FILE_APPEND);
				echo '1|OK';
			} catch (Exception $e) {
				file_put_contents('ecpay.txt', '['.date("Y-m-d H:i:s").'][Error]'.$e->getMessage().PHP_EOL, FILE_APPEND);
				echo '0|' . $e->getMessage();
			}
			parent::load();
		}

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

	file_put_contents("ecpay.txt", "API回傳觸發" . PHP_EOL, FILE_APPEND);

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