<?php
/**
 * HTTP Request
 *
 * auth: izumi.wang
 * date: 20200227
*/
namespace SunwareCore;
use Exception;

trait Curl_Request {
	
	private $headers = array();
	private $connect_timeout = 0;
	private $timeout = 10;
	
	public function setTimeout ($times) {
		if (isset($times["timeout"]) && (int)$times["timeout"]) {
			$this->timeout = (int)$times["timeout"];
		}
	}
	
	public function setHeaders ($headers) {
		if (is_array($headers) && $headers) {
			$this->headers = $this->_mergeHeaders($headers);
		}
	}
	
	public function getHeaders () {
		return $this->headers;
	}
	
	public function sendGet ($link, $input, $header=array()) {
		return $this->_sendRequest($link, $input, array("isPost" => false, "headers" => $header));
	}
	
	public function sendPost ($link, $input, $header=array()) {
		return $this->_sendRequest($link, $input, array("isPost" => true, "headers" => $header));
	}
	
	private function _mergeHeaders ($headers) {
		$tmpHeaders = $this->headers;
		foreach($headers as $key => $val) {
			$tmpHeaders[$key] = $val;
		}
		return $tmpHeaders;
	}
	
	private function _sendRequest ($link, $input, $setups=array()) {
		if (!isset($setups["isPost"])) {
			$setups["isPost"] = false;
		}
		if (!isset($setups["headers"])) {
			$setups["headers"] = array();
		}
		$uri = $link;
		$query_string = "";
		$output_headers = array(); 
		foreach($this->_mergeHeaders($setups["headers"]) as $hk => $hv) {
			$output_headers[] = sprintf("%s: %s", $hk, $hv);
		}
		// 設定參數
		if (is_array($input) && $input) {
			$query_string = http_build_query($input);
		}
		// 設定網址
		if ($setups["isPost"] === false && $query_string) {
			$uri = $link.(strpos($link, "?") === false ? "?" : "&").$query_string; 
		}
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uri);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout); 
		curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
		// 是否設置 headers
		if ($output_headers) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $output_headers);
		}
		// 是否使用 POST
		if ($setups["isPost"] === true) {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, ($query_string ?: $input));
		}
		// 是否使用SSL
		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 = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		if ($httpcode != "200") {
			// var_dump($response);
			throw new Exception("HTTP STATUS CODE ($httpcode)");
		}
		
		return $response;
	}
}
?>