<?php

class BrevoSimpleClient extends SimpleWebClient\Client {
    protected $api_key = null;
    protected $url = null;
    public function __construct($key) {
        $this->api_key = $key;
        $this->url = "https://api.brevo.com/v3/";
    }

    protected function makeApiRequest($endpoint, $method = 'GET', $data = []) {
        $url = $this->url.$endpoint;
        $args = [
            'method'  => $method,
            'headers' => [
                //'Authorization' => 'Bearer ' . $this->api_key,
                'api-key' => $this->api_key,
                'Content-Type'  => 'application/json',
            ],
            'body'    => wp_json_encode($data),
            'sslverify' => false,
        ];

        // Only set the body if data is being sent
        if ($method === 'GET' || empty($data)) {
            unset($args['body']);
        }
        
        $response = wp_remote_request($url, $args);
        if (is_wp_error($response)) {
            return $response;
        }
        
        $body = wp_remote_retrieve_body($response);
        $decodedBody = json_decode($body, true);
        //echo"<pre>"; print_r($decodedBody); exit;
        return $decodedBody;
    }

    public function get_lists() {
        $response = $this->makeApiRequest('contacts/lists', 'GET');
        $res = [];
        if(isset($response['lists'])) {
            foreach ($response['lists'] as $item) {
                $res[] = (object) [
                    'id' => strval($item['id']),
                    'name' => $item['name']
                ];
            }
        }
        //echo"<pre>"; print_r($res); exit;
        return $res;
    }

    public function createOrUpdateSubscriber($data) {
        return $this->makeApiRequest('/contacts', 'POST', $data);
    }
}
