<?php
	require_once "pageBase.php";
	require_once "../../dal/userDAL.php";
	require_once "../../dal/line_gearingDAL.php";
	class _line extends pageBase {
		private $dal, $dalL;
		private array $aryJ;

		public function __construct() {
			$this->dal = new userDAL();
			$this->dalL = new line_gearingDAL();
			$this->aryJ = ["Status" => "0", "Message" => ""];
		}

		public function load(): void {
			$this->aryJ["msg"] = "";

			$action = parent::getPost("do");
			$currentDate = new DateTime();
			$endDate = new DateTime('2025-03-20');
			
			switch ($action) {
				case "del":
					$this->delitem();
					break;
				case "upline":
					$this->upline();
					break;
				case "addline":
				case "smessage":
				case "delgear":
					if ($currentDate > $endDate) {
						$this->setStatusMessage("Line Notify 已經停止服務!", 1);
					} else {
						match ($action) {
							"addline" => $this->addline(),
							"smessage" => $this->smessage(),
							"delgear" => $this->delgear(),
						};
					}
					break;
				default:
					$this->setStatusMessage("系統異常!請重新整理再試一次!！", 1);
			}

			echo urldecode(json_encode($this->aryJ));
			parent::load();
		}
		
		private function setStatusMessage(string $errorMessage, int $errorStatus = 0): void {
			if ($errorStatus !== 0) $this->aryJ["Status"] = $errorStatus;
			$this->aryJ["Message"] = urlencode($errorMessage);
		}
		
		private function delitem() {
			$id = parent::getPost("id");
			$this->dal->UserID = $id;
			$this->dal->loadRecord();
			
			if ($this->dal->LineUID !== "") {
				$this->dal->LineUID = "";
				$this->dal->LineName = "";
				$this->dal->LinePicture = "";
		
				if ($this->dal->updateRecord()) {
					$this->setStatusMessage("刪除成功!!");
				} else {
					$this->setStatusMessage("資料更新失敗!!", "1");
				}
			} else {
				$this->setStatusMessage("請重新登入管理後台!!", "2");
			}
		}

		private function upline() {
			$lastMonthTimestamp = strtotime('first day of last month');
			$upLineTasonTime = strtotime($this->getRegistryValue("upLineTasonTime"));
			$upTime = date("Y年m月d日", $upLineTasonTime);
			if ($upLineTasonTime < $lastMonthTimestamp) {
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, "https://www.appleseo.com.tw/line/srever.json");
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$linesString = curl_exec($ch);
				curl_close($ch);
		
				if (file_put_contents("./../line/srever.json", $linesString)) {
					registryDAL::saveRegistry("upLineTasonTime", date("Y-m-d H:i:s"));
					$this->setStatusMessage("檔案更新成功!!");
				} else {
					$this->setStatusMessage("檔案更新失敗!!", "1");
				}
			} else {
				$this->setStatusMessage("Line登入站在" . $upTime . "已經更新過了!!", "1");
			}
		}
		
		private function addline() {
			$token = parent::getPost("token");

			//檢查對話資訊 找到該權杖的資訊
			$url = 'https://notify-api.line.me/api/status';
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$messageString = curl_exec($ch);
			curl_close($ch);

			$message = json_decode($messageString, true);
			
			if ($message['status'] == "200") {
				$intoAry = [ parent::addArray(":accessToken", $token, "str", 50) ];
				if ($this->dalL->countRecordset($intoAry, "a.`AccessToken`=:accessToken") === 0) {
					$this->dalL->AccessToken = $token;

					if ($message['targetType'] === "USER") {
						$this->dalL->TargetType = "1";
						$username = $message['target'] . '您好:' . "\n";
					} else if ($message['targetType'] === "GROUP") {
						$this->dalL->TargetType = "2";
						$username = '';
					} else {
						$this->dalL->TargetType = "0";
						$username = '';
					}

					$this->dalL->Target = $message['target'];
					$this->dalL->CreatedUserID = parent::getCurrentUserID();
					$this->dalL->CreatedIP = parent::getIP();
					$this->dalL->ModifiedUserID = parent::getCurrentUserID();
					$this->dalL->ModifiedIP = parent::getIP();
		
					$webName = ($this->getRegistryValue("webName") != "") ? ' 【' . $this->getRegistryValue("webName") . '】 ' : '網站';
					
					if ($this->dalL->insertRecord()) {
						$notifyUrl = 'https://notify-api.line.me/api/notify';
						$data = [
							'message' => "\n" . $username . '感謝您使用' . $webName . '後台通知!',
							'stickerPackageId' => '2',
							'stickerId' => '144'
						];
						$dataMessage = http_build_query($data);
		
						$ch2 = curl_init();
						curl_setopt($ch2, CURLOPT_URL, $notifyUrl);
						curl_setopt($ch2, CURLOPT_POST, 1);
						curl_setopt($ch2, CURLOPT_POSTFIELDS, $dataMessage);
						curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token));
						curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
						$messageString2 = curl_exec($ch2);
						curl_close($ch2);
		
						$this->setStatusMessage("新增連動帳號成功!");
					} else {
						$this->setStatusMessage("資料儲存錯誤!", "1");
					}
				}else{
					$this->setStatusMessage("很抱歉，該帳號已經連動過了，不需要再連動了!", "1");
				}
			}else{
				$this->setStatusMessage("發行的權杖有誤!", "1");
			}
		}
		
		private function smessage() {
			$id = parent::getPost("id");
			$ids = parent::getPost("ids");
			$text = htmlentities(parent::getPost("text"));

			$url = 'https://notify-api.line.me/api/notify';
			$data = [ 'message' => $text ];
			$datamessage = http_build_query($data);

			if (isset($id) && $id != "" && $id != "0") {
				$this->dalL->LGID = $id;
				$this->dalL->loadRecord();
				$messageStatus = $this->sendMessageToLine($url, $datamessage, $this->dalL->AccessToken);
				$this->setStatusMessageFromLineStatus($messageStatus);
			} else if (isset($ids) && $ids != "" && $ids != "0") {
				$aryID = explode(",", $ids);
				$data = $this->dalL->executeRecordset(array(), "a.`LGID` IN (" . implode(",", array_fill(0, count($aryID), "?")) . ")", "", 0, -1, $aryID);
				$messageStatuses = array_map(fn($item) => $this->sendMessageToLine($url, $datamessage, $item['AccessToken']), $data);
		
				$num = count(array_filter($messageStatuses, fn($status) => $status === "200"));
				$num2 = count(array_filter($messageStatuses, fn($status) => $status === "401"));
				$num3 = count(array_filter($messageStatuses, fn($status) => $status === "400" || $status === "500"));
				$total = $num + $num2 + $num3;
		
				$msg = ($num == count($data)) ? "訊息已經全部發送完畢!" : "發送" . $num . "筆訊息。" . $num2 . "組帳號存取權杖已經失效!" . $num3 . "筆訊息發送失敗!";
				$this->setStatusMessage($msg);
			} else {
				$this->setStatusMessage("找不到要發訊息的帳號!", "1");
			}
		}
		
		private function delgear(){
			$id = parent::getPost("id");
			$ids = parent::getPost("ids");
		
			$url = 'https://notify-api.line.me/api/revoke';

			if (isset($id) && $id != "" && $id != "0") {
				$this->dalL->LGID = $id;
				$this->dalL->loadRecord();
				$messageStatus = $this->revokeAccessToken($url, $this->dalL->AccessToken);
				$this->deleteAndSetStatusMessage($messageStatus, $this->dalL->deleteRecord($id));
			} else if (isset($ids) && $ids != "" && $ids != "0") {
				$aryID = explode(",", $ids);
				$data = $this->dalL->executeRecordset(array(), "a.`LGID` IN (" . implode(",", array_fill(0, count($aryID), "?")) . ")", "", 0, -1, $aryID);
				$messageStatuses = array_map(fn($item) => $this->revokeAccessToken($url, $item['AccessToken']), $data);
		
				$num = count(array_filter($messageStatuses, fn($status) => $status === "200"));
				$num2 = count(array_filter($messageStatuses, fn($status) => $status === "401"));
		
				$total = $num + $num2;
				if ($total > 0) {
					$this->aryJ["Status"] = "0";
					$this->dalL->batDelete($ids);
					$msg = ($num == count($data)) ? "已經取消連動所選的帳號!" : "取消連動" . $num . "組帳號。" . $num2 . "組帳號存取權杖失效!";
					$this->setStatusMessage($msg);
				} else {
					$this->setStatusMessage("取消連動失敗!", "1");
				}
			} else {
				$this->setStatusMessage("找不到取消連動的帳號!", "1");
			}
		}

		private function sendMessageToLine($url, $data, $accessToken) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$messageString = curl_exec($ch);
			curl_close($ch);
			
			$message = json_decode($messageString, true);
			return $message['status'];
		}

		private function revokeAccessToken($url, $accessToken) {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$messageString = curl_exec($ch);
			curl_close($ch);
		
			$message = json_decode($messageString, true);
			return $message['status'];
		}

		private function setStatusMessageFromLineStatus($status) {
			switch ($status) {
				case "200":
					$this->setStatusMessage("訊息發送成功!");
					break;
				case "401":
					$this->setStatusMessage("無效的存取權杖!", "1");
					break;
				default:
					$this->setStatusMessage("訊息發送失敗!", "1");
					break;
			}
		}

		private function deleteAndSetStatusMessage($messageStatus, $deleteSuccess) {
			if ($messageStatus == "200" || $messageStatus == "401") {
				$txt = ($messageStatus == "401") ? "存取權杖已經失效!" : "";
				
				if ($deleteSuccess) {
					$this->setStatusMessage($txt . "取消連動成功!!");
				} else {
					$this->setStatusMessage($txt . "取消連動失敗!!", "1");
				}
			} else {
				$this->setStatusMessage("取消連動失敗!", "1");
			}
		}
	}

	$page = new _line();
	$page->load();
?>