<?php namespace Intellex\MailChimp\Api;

use Intellex\Curly\Curl;
use Intellex\Curly\Method;
use Intellex\MailChimp\Client;

class ApiAbstract {

	/** @var Client The client which communicates with the Mail Chimp service. */
	protected $client;

	/**
	 * ApiAbstract constructor.
	 *
	 * @param Client $client The client which communicates with the Mail Chimp service.
	 */
	function __construct($client) {
		$this->client = $client;
	}

	/**
	 * @param string|string[] $path   The array of URL elements to be joined with '/' and added to the base URL.
	 * @param mixed|null      $data   The optional data for the POST.
	 * @param string          $method The HTTP method to use.
	 *
	 * @throws \Exception|ValidationException
	 * @return \Intellex\Curly\Response The response from the Mail Chimp.
	 */
	protected function curl($path, $data = null, $method = Method::POST) {

		// Handle the GET parameters
		$get = '';
		$path = (array) $path;
		foreach ($path as $i => $value) {
			if (is_array($value)) {

				// Handle count and offset
				if (sizeof($value) == 2 && key_exists(0, $value) && key_exists(1, $value)) {
					$value = [ 'offset' => $value[0], 'count' => $value[1] ];
				}

				$get = '?' . http_build_query($value);
				unset($path[$i]);
			}
		}

		// Initialize
		$url = implode('/', (array) $path) . $get;
		$curl = new Curl($this->client->config->getBaseURL() . $url);
		$curl->setAuthentication('user', $this->client->config->getApiKey());

		// Set POST, if any
		if ($data !== null) {
			$curl->setData($data, 'application/json', $method);
		}

		// Execute
		$response = $curl->execute();

		// Make sure the request is accepted
		if ($response->getCode() >= 400) {
			throw \Intellex\MailChimp\Exception\ExceptionFactory::fromResponse($response);
		}

		return $response;
	}

}