<?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 _paypage5 extends pageBase {
		public function load() {
			/* 參數 */
			$dal = new paypageDAL();
			$nowTime = time();
			$ip = parent::getIP();

			/* 接收值 */
			$notify_type = $_POST["notify_type"];
			$notify_message = $_POST["notify_message"];
			$obj = json_decode($notify_message, true); // 使用關聯陣列
			
			/* 記錄 */
			$txt = "[".date("Y-m-d H:i:s")."]接收通知".PHP_EOL;
			$txt .= "NOTIFY_TYPE:$notify_type".PHP_EOL;
			$txt .= "NOTIFY_MESSAGE:$notify_message".PHP_EOL;
			
			/* 更新資料 */
			if ($notify_type == "order_confirm" || $notify_type == "order_expired") {
				if (isset($obj['order_id'])) $txt .= "ORDER_ID:".$obj['order_id'].PHP_EOL;
				if (isset($obj['amount'])) $txt .= "AMOUNT:".$obj['amount'].PHP_EOL;

				// 其他相關記錄項
				$dal->MerchantOrderNo = $obj['order_id'];
				$dal->loadRecord();
				if ($dal->ID == "" || $dal->ID == "0") {
					$txt .= "回傳訂單編號找不到符合的記錄!".PHP_EOL;
				} elseif ($dal->Amt != $obj['amount']) {
					$txt .= "回傳訂單金額和記錄資料不合!記錄金額為".$dal->Amt."!".PHP_EOL;
				} else {
					// 處理資料庫操作
					$dal->Status = ($obj['status'] == "S") ? '1' : '-1';
					if ($obj['status_code'] == "FE" || $obj['status_code'] == "FX") $dal->Status = "-2";
					$dal->ReStatus = $obj['status'];
					$dal->PaymentType = ($obj['pay_type'] == "ATM") ? "虛擬帳號(PCHome)" : (($obj['pay_type'] == "CARD") ? "信用卡(PCHome)" : "異常(PCHome)");

					if ($obj['status'] == "S" && preg_match("/^20\d{12}$/", $obj['pay_date'])) {
						$payDate = $obj['pay_date'];
						$payTime = substr($payDate, 0, 4) . "-" . substr($payDate, 4, 2) . "-" . substr($payDate, 6, 2) . " " . substr($payDate, 8, 2) . ":" . substr($payDate, 10, 2) . ":" . substr($payDate, 12, 2);
						$dal->PayTime = strtotime($payTime);
					}

					$dal->ReplyTime = $nowTime;
					$dal->ReplyIP = $ip;
					$dal->replyRecord();
					
					// 系統通知
					$sends = new sends();
					$sendMail = $this->getValidEmails();
		
					// 創建信件內容
					$reMessage = ($obj->status == "S") ? "成功" : "失敗";
					$mbody = "訂單編號:{$dal->MerchantOrderNo}<br />";
					$mbody .= "費用名稱:{$dal->ItemDesc}<br />";
					$mbody .= "費用金額:{$dal->Amt}<br />";
					$mbody .= "繳費方式:{$dal->PaymentType}<br />";
					$mbody .= "繳費時間:{$payTime}<br />";
					$mbody .= "繳費狀態:{$reMessage}<br />";
					$mbody .= "備註:{$dal->OrderComment}";
					
					$subject = "[" . $this->registry->webName . " " . $_SERVER['HTTP_HOST'] . "] [快速線上付款系統通知]" . $dal->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"]);
					}
					
				}
			}
			
			/* 記錄 */
			if($notify_type == "order_confirm" || $notify_type == "order_audit" || $notify_type == "order_expired"){
				if(isset($obj->order_id))						$txt .= "ORDER_ID:".$obj->order_id.PHP_EOL;
				if(isset($obj->amount))							$txt .= "AMOUNT:".$obj->amount.PHP_EOL;
				if(isset($obj->pay_type))						$txt .= "PAY_TYPE:".$obj->pay_type.PHP_EOL;
				if(isset($obj->trade_amount))					$txt .= "TRADE_AMOUNT:".$obj->trade_amount.PHP_EOL;
				if(isset($obj->platform_amount))				$txt .= "PLATFORM_AMOUNT:".$obj->platform_amount.PHP_EOL;
				if(isset($obj->pp_fee))							$txt .= "PP_FEE:".$obj->pp_fee.PHP_EOL;
				if(isset($obj->create_date))					$txt .= "CREATE_DATE:".$obj->create_date.PHP_EOL;
				if(isset($obj->pay_date))						$txt .= "PAY_DATE:".$obj->pay_date.PHP_EOL;
				if(isset($obj->actual_pay_date))				$txt .= "ACTUAL_PAY_DATE:".$obj->actual_pay_date.PHP_EOL;
				if(isset($obj->fail_date))						$txt .= "FAIL_DATE:".$obj->fail_date.PHP_EOL;
				if(isset($obj->status))							$txt .= "STATUS:".$obj->status.PHP_EOL;
				if(isset($obj->status_code))					$txt .= "STATUS_CODE:".$obj->status_code.PHP_EOL;
				if(isset($obj->items)){
					foreach($obj->items as $item){
						if(isset($item->name))					$txt .= "ITEM_NAME:".$item->name.PHP_EOL;
						if(isset($item->url))					$txt .= "ITEM_URL:".$item->url.PHP_EOL;
					}
				}
				if(isset($obj->payment_info->virtual_account))	$txt .= "VIRTUAL_ACCOUNT:".$obj->payment_info->virtual_account.PHP_EOL;
				if(isset($obj->payment_info->bank_code))		$txt .= "BANK_CODE:".$obj->payment_info->bank_code.PHP_EOL;
				if(isset($obj->payment_info->expire_date))		$txt .= "EXPIRE_DATE:".$obj->payment_info->expire_date.PHP_EOL;
				if(isset($obj->payment_info->installment))		$txt .= "INSTALLMENT:".$obj->payment_info->installment.PHP_EOL;
				if(isset($obj->payment_info->rate))				$txt .= "RATE:".$obj->payment_info->rate.PHP_EOL;
				if(isset($obj->payment_info->pp_fee))			$txt .= "PP_FEE:".$obj->payment_info->pp_fee.PHP_EOL;
				if(isset($obj->payment_info->card_last_number))	$txt .= "CARD_LAST_NUMBER:".$obj->payment_info->card_last_number.PHP_EOL;
				if(isset($obj->available_date))					$txt .= "AVAILABLE_DATE:".$obj->available_date.PHP_EOL;
			}else{
				if(isset($obj->refund_id))						$txt .= "REFUND_ID:".$obj->refund_id.PHP_EOL;
				if(isset($obj->status))							$txt .= "STATUS:".$obj->status.PHP_EOL;
				if(isset($obj->amount))							$txt .= "AMOUNT:".$obj->amount.PHP_EOL;
				if(isset($obj->fee))							$txt .= "FEE:".$obj->fee.PHP_EOL;
				if(isset($obj->transfer_fee))					$txt .= "TRANSFER_FEE:".$obj->transfer_fee.PHP_EOL;
				if(isset($obj->refund_date))					$txt .= "REFUND_DATE:".$obj->refund_date.PHP_EOL;
				if(isset($obj->actual_refund_date))				$txt .= "ACTUAL_REFUND_DATE:".$obj->actual_refund_date.PHP_EOL;
			}
			$txt .= PHP_EOL;
			file_put_contents("pcpay.txt", $txt, FILE_APPEND);
			echo "success";

			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 _paypage5();
	$page->load();
	$page->render();
?>