<?php
require_once dirname(dirname(dirname(dirname(__FILE__))))."/registry.php";
class lineBot {
    private $channelAccessToken;
    private $channelSecret;
	
	public $registry;
	
	//構造函數
	public function __construct($channelAccessToken, $channelSecret) {
        $this->channelAccessToken = $channelAccessToken;
        $this->channelSecret = $channelSecret;
		
		$this->registry = registry::createInstance();
	}

	// 取得 webhook 的內容
	public function parseEvents(): array {
		if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
			http_response_code(405);
			error_log('取得webhook方法不允許!');
			exit();
		}

		$httpRequestBody = file_get_contents('php://input');

		if ($httpRequestBody === '') {
			http_response_code(400);
			error_log('取得webhook時異常!缺少請求正文!');
			exit();
		}
		
		$userRequest = json_decode($httpRequestBody, true);
		if (!isset($userRequest['events'])) {
			http_response_code(400);
			error_log('取得webhook時異常!請求正文無效：缺少事件屬性!');
			exit();
		}

		return $userRequest['events'];
	}

	/* 回覆訊息-文字訊息
	 * @param $replyToken 回覆的token
	 * @param $message 文字訊息
	 */
	public function replyLineMessage($replyToken, $message) {
		$url = 'https://api.line.me/v2/bot/message/reply';
		$data = [
			'replyToken' => $replyToken,
			'messages' => [
				[
					'type' => 'text',
					'text' => $message
				]
			]
		];
		return $this->sendRequest($url, $data);
	}

	/* 回覆訊息-flex訊息
	 * @param $replyToken 回覆的token
	 * @param $flexMessage flex陣列
	 */
	public function replyLineFlexMessage($replyToken, $flexMessage) {
		$url = 'https://api.line.me/v2/bot/message/reply';
		$data = [
			'replyToken' => $replyToken,
			'messages' => [$flexMessage]
		];
		return $this->sendRequest($url, $data);
	}
	
	/* 發送推播訊息-文字訊息
	 * @param $pushId 要推送到的ID
	 * @param $message 文字訊息
	 */
	public function pushLineMessage($pushId, $message): bool {
		$url = 'https://api.line.me/v2/bot/message/push';
		$data = [
			'to' => $pushId,
			'messages' => [
				[
					'type' => 'text',
					'text' => $message
				]
			]
		];
		return $this->sendRequest($url, $data);
	}

	/* 發送聯絡我們推播訊息(Flex Message)
	 * @param $pushId 要推送到的ID
	 * @param $data 要傳的內容陣列 $data[] = [ 標題, 欄位 ];
	 */
	public function pushContactMessage($pushId, $data = []): bool {
		$webName = ($this->registry->webName != "") ? " 【" . $this->registry->webName . "】 " : "";

		$contents = [];
		foreach ($data as $item) {
			$contents[] = [
				"type" => "box",
				"layout" => "horizontal",
				"contents" => [
					[
						"type" => "box",
						"layout" => "vertical",
						"contents" => [
							[ "type" => "text", "text" => $item['label'] . ":", "size" => "sm", "color" => "#989898", "wrap" => true ]
						],
						"flex" => 2
					],
					[
						"type" => "box",
						"layout" => "vertical",
						"contents" => [
							[ "type" => "text", "text" => str_replace("<br />", "\n", $item['value']), "size" => "sm", "color" => "#111111", "wrap" => true ]
						],
						"flex" => 5
					]
				]
			];
		}
		
		$flexMessage = [
			"type" => "flex",
			"altText" => $_SERVER['HTTP_HOST'] . "網站通知",
			"contents" => [
				"type" => "bubble",
				"body" => [
					"type" => "box",
					"layout" => "vertical",
					"contents" => [
						[ "type" => "text", "text" => $_SERVER['HTTP_HOST'], "weight" => "bold", "color" => "#1DB446", "size" => "sm" ],
						[ "type" => "text", "text" => "網站通知", "weight" => "bold", "size" => "xxl", "margin" => "md" ],
						[ "type" => "text", "text" => "您的客戶在" . $webName . "聯絡我們中有留言，請盡快去後台查看!", "size" => "xs", "color" => "#6f6f6f", "wrap" => true ],
						[ "type" => "separator", "margin" => "xxl" ],
						[
							"type" => "box",
							"layout" => "vertical",
							"contents" => $contents,
							"paddingTop" => "xl",
							"paddingBottom" => "sm",
							"spacing" => "sm"
						]
					]
				],
				"footer" => [
					"type" => "box",
					"layout" => "vertical",
					"contents" => [
						[
							"type" => "button",
							"action" => [ "type" => "uri", "label" => "前往後台", "uri" => "https://" . $_SERVER['HTTP_HOST'] . "/iweb/" ],
							"style" => "primary",
							"height" => "sm"
						]
					]
				],
				"styles" => [
					"footer" => [
						"separator" => true
					]
				]
			]
		];
	
		$url = 'https://api.line.me/v2/bot/message/push';
		$data = [
			'to' => $pushId,
			'messages' => [$flexMessage]
		];
		return $this->sendRequest($url, $data);
	}

	/* 發送推播請求的通用函數
	 * @param $url 要執行的服務
	 * @param $data 要傳的內容陣列
	 */
	public function sendRequest(string $url,array $data): bool {
		if (!empty($this->channelAccessToken)) {
			$options = [
				CURLOPT_HTTPHEADER => [
					'Content-Type: application/json',
					'Authorization: Bearer ' . $this->channelAccessToken
				],
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POST => true,
				CURLOPT_POSTFIELDS => json_encode($data, JSON_THROW_ON_ERROR)
			];

			$ch = curl_init($url);
			curl_setopt_array($ch, $options);
			$response = curl_exec($ch);
			curl_close($ch);
		
			// Handle response
			return ($response === false) ? false : true;
		}
	}
}
?>