<?php
/**
 * 與AMR系統取得資料(By GET)
 * CBC-128
 * PKSC7
 *
 * auth: izumi.wang
 * date: 20191220
*/
class TPE_AMR { 
	
	// AMR API 網址
	protected $api = "https://twd.water.gov.taipei/www/amrapi/api/amr/";
	// 安全密鑰
	protected $security_key = "";
	// 偏移值
	protected $security_iv = "";
	// 公宅代碼
	protected $uid = "";
	// 密碼
	protected $pwd = "";
	
	// 建構子
	public function __construct ($cfg=array()) {
		if (is_array($cfg) && $cfg) {
			foreach (array("uid", "pwd", "security_key", "security_iv") as $_k) {
				if (isset($cfg[$_k])) 
					$this->SetCFG($_k, $cfg[$_k]);
			}
		}
	}
	
	// 設定參數
	public function SetCFG ($col, $val) {
		if (!isset($this->{$col})) {
			throw new Exception(sprintf("[%s] 設置參數不存在", $col));
		}
		$this->{$col} = $val;
	}
	
	// 取得參數
	public function GetCFG ($col) {
		return isset($this->{$col}) ? $this->{$col} : "";
	}
	
	// 加密
	public function Encrypt ($val, $isBase64=true) {
		if (!strlen($this->security_key) || !strlen($this->security_iv)) {
			throw new Exception("請先設置[安全密鑰]和[偏移值]");
		}
		$val = openssl_encrypt($val, "AES-128-CBC", $this->security_key, OPENSSL_RAW_DATA , $this->security_iv);
		return $isBase64 ? base64_encode($val) : $val;
		
	}
	
	// 解密
	public function Decrypt ($val, $isBase64=true) {
		if (!strlen($this->security_key) || !strlen($this->security_iv)) {
			throw new Exception("請先設置[安全密鑰]和[偏移值]");
		}
		$val = $isBase64 ? base64_decode($val) : $val;
		return openssl_decrypt($val, "AES-128-CBC", $this->security_key, OPENSSL_RAW_DATA , $this->security_iv);
	}
	
	// 查詢資料
	public function SelectRowDatasByDate ($date, $isJson=true) {
		if (!strtotime($date)) {
			throw new Exception("日期格式錯誤");
		}
		
		$date_tw = $this->yyyyToyyy($date);
		$res = $this->httpGet($this->queryUri($date_tw));
		return $isJson ? json_decode($res, true) : $res;
	}
	
	// 西元日期轉民國日期
	private function yyyyToyyy ($date) {
		$ds = explode("-", date("Y-m-d", strtotime($date)));
		$ds[0] = (int)$ds[0] - 1911;
		return implode("", $ds);
	}
	
	// 取得完整URI
	private function queryUri ($date_tw) {
		if (!strlen($this->uid) || !strlen($this->pwd)) {
			throw new Exception("請先設置[公宅代碼]和[登入密碼]");
		}
		$url = $this->api;
		if (substr($url, -1) == "/") {
			$url = substr($url, 0 , -1);
		}
		return sprintf("%s/%s/%s/%s", $url, $this->uid, $this->pwd, $date_tw);
	}
	
	// HTTP GET 呼叫
	private function httpGet ($uri="") {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch , CURLOPT_FOLLOWLOCATION, true);
		
		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;
	}
}
?>