<?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);
		}
		// �]�w�Ѽ�
		if (is_array($input) && $input) {
			$query_string = http_build_query($input);
		}
		// �]�w���}
		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);
		// �O�_�]�m headers
		if ($output_headers) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $output_headers);
		}
		// �O�_�ϥ� POST
		if ($setups["isPost"] === true) {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, ($query_string ?: $input));
		}
		// �O�_�ϥ�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;
	}
}
