<?php

namespace Vinteract\Payments\Providers\PinPayments;

use \Vinteract\Payments\Providers\PinPayments\RequestResponse as RequestResponse;

use Exception;

class Request {
	
	private $method;
	private $responseClass;
	
	public function __construct($method = "GET", $responseClass = RequestResponse::class) {
		$this->setMethod($method);
		$this->setResponseClass($responseClass);
	}
	
	private function setMethod($method) {
		$this->method = $method;
	}
	
	private function setResponseClass($responseClass) {
		$this->responseClass = $responseClass;
	}
	
	private function getMethod() {
		return $this->method;
	}
	
	private function getResponseClass() {
		return $this->responseClass;
	}
	
	public function process($url = "", $postData = []) {
		
		/*
			Request
		*/
		
		$curl = curl_init();
		
		curl_setopt($curl, CURLOPT_USERPWD, \Vinteract\Payments\Providers\PinPayments\PinPayments::getSecretKey());  
		
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ENVIRONMENT === "production");
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, ENVIRONMENT === "production" ? 2 : FALSE);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->getMethod());
		
		/*
			Post fields?
		*/
		
		if ($this->getMethod() === "POST") {
			curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData, "", "&"));
		}
		
		/*
			Exectue request
		*/
		
		$curl_response = json_decode(curl_exec($curl), true);
		
		/*
			Response
		*/
		
		if (isset($curl_response) && array_key_exists("error", $curl_response)) {
			return new $this->responseClass([
				"code" => curl_getinfo($curl, CURLINFO_HTTP_CODE),
				"message" => $curl_response["error_description"],
				"contents" => [
					"data" => $curl_response,
				],
			]);
		} else {
			return new $this->responseClass([
				"code" => curl_getinfo($curl, CURLINFO_HTTP_CODE),
				"contents" => [
					"data" => $curl_response["response"],
				]
			]);
		}
		
	}
	
}
