<?php

namespace Vinteract\Payments\Providers\MerchantWarrior;

use Exception;

class Request {
	
	public static function send($url, $postData) {
		
		// Execute cURL request.
		
		$curl = curl_init();
		
		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_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postData, "", "&"));
		
		$response = curl_exec($curl);
		$error = curl_error($curl);
		
		// Check for CURL errors.
		
		if (isset($error) && strlen($error)) {
			throw new Exception("CURL Error: {$error}");
		}
		
		// Parse the XML response.
		
		$xml = simplexml_load_string($response);
		
		// Close connection.
		
		curl_close($curl);
		
		// Cast the SimpleXMLObject object into an array.
		
		$xml = (array) $xml;
		
		// Success or error?
		
		$success = ((int) $xml["responseCode"] === 0) ? true : false;
		$error = !$success;
		
		// Response.
		
		return [
			"success" => $success,
			"error" => $error,
			"data" => $xml,
		];
		
	}
	
}
