<?php

class MailrelaySimpleClient extends SimpleWebClient\Client {
    protected $api_key = null;
    protected $endpoint = null;

    function __construct($key, $host) {
        $this->api_key = $key;
        // remove any trailing slash
        $this->endpoint = rtrim("https://{$host}/api/v1", '/');

        parent::__construct($this->endpoint, []);
    }

    public function get_lists($page = 1, $per_page = 1000) {
        $headers = array(
            'X-AUTH-TOKEN' => $this->api_key,
        );

        $params = [
        'page'     => max(1, (int)$page),
        'per_page' => max(50, (int)$per_page),
        ];

        $this->headers = $headers;

        $response = $this->send_request('/groups', 'GET', $params);

        if (!$response->success || !is_array($response->data)) {
            return null;
        }

        $lists = [];
        foreach ($response->data as $item) {
            $lists[] = (object)[
                'id'   => (string) $item['id'],
                'name' => $item['name'],
            ];
        }

        return $lists;
    }


    public function add_contact($list_id, $name, $email) {        
        $headers = array(
            'X-AUTH-TOKEN' => $this->api_key,
        );
        $this->headers = $headers;

        $body = [
            'email'  => $email,
            'name'   => $name,
            'group_ids' => [$list_id],
            'status' => 'active', // subscriber is active by default
        ];

        $response = $this->send_request('/subscribers', 'POST', $body);
        return $response->success;
    }
}
