<?php
namespace ProxyPay\Core;

class Retailcrm {

	const PATH = '/api/';
	const V = 'v5/';

	private $key;
	private $domain;

	public function __construct($domain, $key){
		$this->key = $key;
		$this->domain = $domain;
	}

	public function setPaymentMethod($code, $settings)
	{
		$data = ['integrationModule' => json_encode($settings)];
		$result = $this->request(self::V."integration-modules/$code/edit", 'POST', $data);
		return $result;
	}

	public function updateInvoice($invoice)
	{
		$data = ['updateInvoice' => json_encode($invoice)];
		$result = $this->request(self::V."payment/update-invoice", 'POST', $data);
		return $result;
	}

	public function getCredentials()
	{
		$result = $this->request("credentials");
		return $result;
	}

	public function request($path , $method = 'GET', $params = [])
	{
		$params['apiKey'] = $this->key;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//curl_setopt($ch, CURLOPT_HEADER, true);

		$url = 'https://'.$this->domain.self::PATH.$path;
		$query     = '';
		if (!empty($params) && $method == 'GET') {
			foreach ($params as $key => $value) {
				$query .= "&$key=" . urlencode($value);
			}
			if (!strpos($url, '?')) {
				$query = '?' . substr($query, 1);
			}
		}

		$data = http_build_query($params);


		curl_setopt($ch, CURLOPT_URL, $url . $query);

		if($method == 'POST') {
			curl_setopt($ch, CURLOPT_POST, true);
			if (!empty($params)) {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			}
		}

		$response = curl_exec($ch);
		curl_close($ch);
		$response = json_decode($response);
		return $response;
	}
}

