<?php

require './vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;

class MailchimpAPI
{
    private static function handleResponse($response)
    {
        $res = json_decode($response->getBody());

        if (!isset($res)) {
            return null;
        }

        return array_merge((array) $res);
    }

    public static function get($url, $params)
    {
        require_once('../../core/backend.php');
        global $savvyext;
        $token = $savvyext->cfgReadChar('mailchimp.api_key');
        $baseUri = $savvyext->cfgReadChar('mailchimp.domain');

        $client = new Client(['base_uri' => $baseUri]);
        $header = ['Authorization' => "apikey $token"];

        try {
            $response = $client->request('GET', $url, [
                'headers' => $header,
                'query' => $params,
            ]);
        } catch (ServerException $e) {
            $response = $e->getResponse();
        } catch (ClientException $e) {
            $response = $e->getResponse();
        }

        return self::handleResponse($response);
    }
}
