<?php
	require_once "pageBase.php";
	require_once "bin/system/ECPay.Payment.Integration.php";
	require_once "dal/paypageDAL.php";
	require_once "function/function.php";
	class _paypage2 extends pageBase {
		public $dal;
	
		public function load() {
			$this->dal = new paypageDAL();

			switch ($this->registry->isPayPage) {
				case "1":
					$this->loadData();
					parent::loadTemplateFile("paypage2.html");
					break;
				case "2":
				case "3":
					$this->loadData();
					if ($this->alertMsg != "") {
						echo "<script>".PHP_EOL;
						echo "alert('".$this->alertMsg."');".PHP_EOL;
						if ($this->goBack == "Y") echo "history.back();".PHP_EOL;
						echo "</script>";
					}
					break;
				default:
					parent::alert2("此功能尚未開放!", "/");
			}
			parent::load();
		}

		public function loadData() {
			// 橫幅廣告
			$this->picturetype = "110";

			$checknum = parent::getPost("Checknum");
	
			if ($checknum == $_SESSION["dd_ckstr"] && isset($_SESSION["dd_ckstr"]) && $_SESSION["dd_ckstr"] != '') {
				$this->dal = new paypageDAL();
				$this->dal->PayerName = parent::getPost("Name", "", 4);
				$this->dal->TimeStamp = time();
				$this->dal->MerchantOrderNo = $this->dal->TimeStamp.rand(100,999);
				$this->dal->Amt = parent::getPost("Amt", "0", 4);
				$this->dal->ItemDesc = parent::getPost("Title", "", 4);
				$expireDate = date("Y-m-d", strtotime("+7 days"));    //最後繳款期限
				$expireTime = $expireDate." 23:59:59";
				$this->dal->ExpireTime = strtotime($expireTime);
				$this->dal->Email = parent::getPost("Email", "", 4);
				$this->dal->OrderComment = parent::getPost("Content", "", 4);
				$this->dal->CreatedIP = parent::getIP();

				if (empty($this->dal->PayerName)) {
					$this->alertMsg = "請輸入付款人姓名!!";
					$this->goBack = "Y";
					return;
				}
				if (!preg_match("/^[1-9]\d*$/", $this->dal->Amt)) {
					$this->alertMsg = "付款金額不正確!!";
					$this->goBack = "Y";
					return;
				}
				if (empty($this->dal->ItemDesc)) {
					$this->alertMsg = "請輸入付款原因!!";
					$this->goBack = "Y";
					return;
				}
				if (!filter_var($this->dal->Email, FILTER_VALIDATE_EMAIL)) {
					$this->alertMsg = "付款人信箱不正確!!";
					$this->goBack = "Y";
					return;
				}
	
				// 資料庫新增
				$this->dal->insertRecord();

				// API處理
				$this->processPayment();
			} else {
				$this->alertMsg = "驗證碼輸入錯誤喔";
				$this->goBack = "Y";
			}
			
			parent::loadData();
		}

		private function processPayment() {
			switch ($this->registry->isPayPage) {
				case "1":
					$this->newebpay();
					break;
				case "2":
					$this->ecpay();
					break;
				case "3":
					$this->pchomepay();
					break;
				default:
					$this->alertMsg = "不支援的付款方式";
					$this->goBack = "Y";
			}
		}

		private function newebpay() {
			if (empty($this->registry->merchantID) || empty($this->registry->hashKey) || empty($this->registry->hashIV)) {
				$this->alertMsg = "金流系統暫時停止服務，請和客服人員聯絡，或是稍後再試一次!";
				$this->location = "/";
				return;
			}
		
			$notifyURL = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/paypage3.html";
			$clientBackURL = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/paypage.html";
			
			//資訊陣列
			$trade_info_arr = [
				'MerchantID' => $this->registry->merchantID,
				'RespondType' => 'JSON',
				'TimeStamp' => $this->dal->TimeStamp,
				'Version' => '1.5',
				'MerchantOrderNo' => $this->dal->MerchantOrderNo,
				'Amt' => $this->dal->Amt,
				'ItemDesc' => $this->dal->ItemDesc,
				'ExpireDate' => date("Y-m-d", strtotime("+7 days")),
				'NotifyURL' => $notifyURL,
				'ClientBackURL' => $clientBackURL,
				'Email' => $this->dal->Email,
				'LoginType' => '0',
				'OrderComment' => $this->dal->OrderComment,
			];
			//交易資料經 AES 加密後取得 TradeInfo
			$tradeInfo = create_mpg_aes_encrypt($trade_info_arr, $this->registry->hashKey, $this->registry->hashIV);
			$tradeInfo2 = "HashKey={$this->registry->hashKey}&{$tradeInfo}&HashIV={$this->registry->hashIV}";
			$tradeSha = strtoupper(hash("sha256", $tradeInfo2));

			parent::addParameter("MerchantID", $this->registry->merchantID);
			parent::addParameter("TradeInfo", $tradeInfo);
			parent::addParameter("TradeSha", $tradeSha);
		}

		private function ecpay() {
			if (empty($this->registry->ecpay_merchantID) || empty($this->registry->ecpay_hashKey) || empty($this->registry->ecpay_hashIV)) {
				$this->alertMsg = "金流系統暫時停止服務，請和客服人員聯絡，或是稍後再試一次!";
				$this->goBack = "Y";
				return;
			}
			
			try {
				/* 綠界 SDK */
				$obj = new ECPay_AllInOne();
				// 服務參數
				$obj->ServiceURL = "https://payment.ecpay.com.tw/Cashier/AioCheckOut/V5";
				$obj->HashKey = $this->registry->ecpay_hashKey;
				$obj->HashIV = $this->registry->ecpay_hashIV;
				$obj->MerchantID = $this->registry->ecpay_merchantID;
				$obj->EncryptType = "1";

				// 基本參數
				$obj->Send['ReturnURL'] = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/paypage4.html";
				$obj->Send['MerchantTradeNo'] = $this->dal->MerchantOrderNo;
				$obj->Send['MerchantTradeDate'] = date('Y/m/d H:i:s');
				$obj->Send['TotalAmount'] = $this->dal->Amt;
				$obj->Send['TradeDesc'] = $this->dal->OrderComment ?: "線上快速付款";
				$obj->Send['ChoosePayment'] = ECPay_PaymentMethod::ALL;
				
				// 訂單的商品資訊
				$item = [
					'Name' => $this->dal->ItemDesc,
					'Price' => (int)$this->dal->Amt,
					'Currency' => '元',
					'Quantity' => 1,
					'URL' => '/',
				];
				$obj->Send['Items'][] = $item;
				
				// 產生訂單，自動發送到綠界
				$obj->CheckOut();
			} catch (Exception $e) {
				file_put_contents("ecpay.txt", "[".date("Y-m-d H:i:s")."]".PHP_EOL.$e->getMessage().PHP_EOL, FILE_APPEND);
				$this->alertMsg = "快速線上付款送出失敗!請重新整理再試一次!";
				$this->goBack = "Y";
			}
		}

		private function pchomepay() {
			if (empty($this->registry->pchomepay_appId) || empty($this->registry->pchomepay_secretCode)) {
				$this->alertMsg = "金流系統暫時停止服務，請和客服人員聯絡，或是稍後再試一次!";
				$this->goBack = "Y";
				return;
			}
			
			/* TOKEN參數 */
			$str_url = "https://api.pchomepay.com.tw/v1/token";
			$login = "{$this->registry->pchomepay_appId}:{$this->registry->pchomepay_secretCode}";
			
			/* 取得TOKEN */
			$headers = [
				'Content-Type:application/json',
				'Authorization: Basic '. base64_encode($login),
			];

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_URL, $str_url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, null);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			$result = curl_exec($ch);
			curl_close($ch);
			
			$token = json_decode($result);

			file_put_contents("pcpay.txt", "[".date("Y-m-d H:i:s")."]取得TOKEN".PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "RESULT:".$result.PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "TOKEN:".$token->token.PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "EXPIRED_IN:".$token->expired_in.PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "EXPIRED_TIMESTAMP:".$token->expired_timestamp.PHP_EOL, FILE_APPEND);
			
			/* 訂單參數 */
			$str2_url = "https://api.pchomepay.com.tw/v1/payment";
			$order_id = $this->dal->MerchantOrderNo;
			$pay_type = ["ATM", "CARD"];
			$amount = (int)$this->dal->Amt;
			$return_url = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/";
			$fail_return_url = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/";
			$notify_url = parent::getProtocol() . "://" . $_SERVER['HTTP_HOST'] . "/paypage5.html";
			$items = [(object)["name" => $this->dal->ItemDesc, "url" => "/"]];
			$atm_info = (object)["expire_days" => 3];
			$card_installment = "1,3,6";
			
			/* 訂單送出 */
			$headers = [
				'Content-Type:application/json',
				"pcpay-token:{$token->token}",
			];

			$aryRP = [
				"order_id" => $order_id,
				"pay_type" => $pay_type,
				"amount" => $amount,
				"return_url" => $return_url,
				"fail_return_url" => $fail_return_url,
				"notify_url" => $notify_url,
				"items" => $items,
				"atm_info" => $atm_info,
				"card_installment" => $card_installment,
			];

			$requestPayload = json_encode($aryRP);
		
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_URL, $str2_url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $requestPayload);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
			$result = curl_exec($ch);
			curl_close($ch);

			$obj = json_decode($result);
		
			file_put_contents("pcpay.txt", "[".date("Y-m-d H:i:s")."]訂單送出".PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "REQUESTPAYLOAD:".$requestPayload.PHP_EOL, FILE_APPEND);
			file_put_contents("pcpay.txt", "RESULT:".$result.PHP_EOL, FILE_APPEND);
			
			if (isset($obj->order_id)) file_put_contents("pcpay.txt", "ORDER_ID:".$obj->order_id.PHP_EOL, FILE_APPEND);
			if (isset($obj->payment_url)) file_put_contents("pcpay.txt", "PAYMENT_URL:".$obj->payment_url.PHP_EOL, FILE_APPEND);
			if (isset($obj->error_type)) file_put_contents("pcpay.txt", "ERROR_TYPE:".$obj->error_type.PHP_EOL, FILE_APPEND);
			if (isset($obj->code)) file_put_contents("pcpay.txt", "CODE:".$obj->code.PHP_EOL, FILE_APPEND);
			if (isset($obj->message)) file_put_contents("pcpay.txt", "MESSAGE:".$obj->message.PHP_EOL, FILE_APPEND);
		
			if (isset($obj->payment_url)) {
				header("Location: {$obj->payment_url}");
			} else {
				$this->alertMsg = "快速線上付款送出失敗!請重新整理再試一次!";
				$this->goBack = "Y";
			}
		}
	}

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