<?php

/**
 * 透過Socket與Soft通訊
 *
 * auth: izumi.wang
 * date: 20181128
 */

namespace SunwareCore;

use Exception;

trait Line_Notify
{
	// 私有成員
	private $LineApi = 'https://notify-api.line.me/api/notify';
	private $tokens  = null;
	private $http    = null;
	private $errors  = array();
	// 建構子
	public function __construct($token = '')
	{
		if (strlen(trim($token)))
			$this->setTokens(array($token));

		$this->clearSendMessageError();
	}
	// 設置token
	public function setTokens($tokens)
	{
		$this->tokens = $tokens;
	}
	// 取得token  
	public function getToken()
	{
		return $this->tokens;
	}

	// 發送訊息
	public function sendMessage($text, $imagePath = null, $sticker = null)
	{
		// 內容不得為空
		if (!strlen(trim($text))) {
			return false;
		}

		$request_params = array();
		//Message always required
		$request_params['multipart'] = array(
			array(
				'name' => 'message',
				'contents' => $text
			)
		);

		if (!empty($imagePath) && preg_match("#^https?://#", $imagePath)) {
			// Remote HTTP / HTTPS image
			$request_params['multipart'][] = array(
				'name' => 'imageThumbnail',
				'contents' => $imagePath
			);

			$request_params['multipart'][] = array(
				'name' => 'imageFullsize',
				'contents' => $imagePath
			);
		} elseif (!empty($imagePath) && file_exists($imagePath)) {
			// Local image
			$request_params['multipart'][] = array(
				'name' => 'imageFile',
				'contents' => fopen($imagePath, 'r')
			);
		}

		//https://devdocs.line.me/files/sticker_list.pdf
		if (
			!empty($sticker)
			&& !empty($sticker['stickerPackageId'])
			&& !empty($sticker['stickerId'])
		) {

			$request_params['multipart'][] = array(
				'name' => 'stickerPackageId',
				'contents' => $sticker['stickerPackageId']
			);

			$request_params['multipart'][] = array(
				'name' => 'stickerId',
				'contents' => $sticker['stickerId']
			);
		}

		foreach ($this->tokens as $_token) {
			$request_params['headers'] = array(
				'Content-Type: application/x-www-form-urlencoded',
				'Authorization: Bearer ' . $_token
			);

			try {
				$this->httpPost($this->LineApi, $request_params);
			} catch (Exception $e) {
				$this->errors[] = sprintf("[%s] %s", $_token, $e->getMessage());
			}
		}

		return true;
	}

	public function getSendMessageError()
	{
		return $this->errors ? implode("\r\n", $this->errors) : "";
	}

	public function clearSendMessageError()
	{
		$this->errors = array();
	}

	// 發送授權

	// 接受授權

	private function httpPost($uri = '', $options = array())
	{
		$headers = isset($options['headers']) ? $options['headers'] : array();
		unset($options['headers']);

		$params = array();
		foreach ($options['multipart'] as $p) {
			$params[$p['name']] = $p['contents'];
		}

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

		if ($headers)
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		if (substr($uri, 0, 8) == 'https://') {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		}

		$response = curl_exec($ch);
		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		if ($httpcode != '200') {
			throw new Exception('http error (' . $httpcode . ')');
		}

		return $response;
	}
}
