<?php

namespace YooMoney\Helpers\OauthHelpers;

use Exception;

/**
 * Класс методов для работы с запросами
 */
class HttpClient implements HttpClientInterface
{
    const BASE_PATH = 'https://yookassa.ru';

    /**
     * Отправка POST запроса и получение данных
     *
     * @param string $url
     * @param array $parameters
     * @return string
     * @throws Exception
     */
    public function sendRequest($url, array $parameters)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::BASE_PATH . $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type' => 'application/json; charset=utf-8'));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters, JSON_UNESCAPED_UNICODE));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $response = curl_exec($ch);
        $info = curl_getinfo($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_errno($ch);

        if ($response === false || $info['http_code'] != 200) {
            throw new Exception('Request failed: ' . $errno . ": " . $error . '. Code: ' . $info['http_code']);
        }

        return $response;
    }
}