<?php

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

    function __construct($key)
    {
        parent::__construct(
            'https://api.getresponse.com/v3',
            ['X-Auth-Token' => 'api-key ' . $key]
        );
    }

    public function ping()
    {
        $res = $this->send_request('/accounts', 'GET');
        return $res->success;
    }

    public function add_contact($campaign_id, $name, $email)
    {
        $params = [
            'campaign' => [
                'campaignId' => $campaign_id
            ],
            'email' => $email,
            'name' => $name,
            'dayOfCycle' => 0,
            'ipAddress' => self::get_client_ip()
        ];

        //$json_body = json_encode($params);
        $res = $this->send_request('/contacts', 'POST', $params);

        return $res->success;
    }

    public function createOrUpdateSubscriber($data)
    {
        $campaignId = '';
        if (isset($data['campaign']) && isset($data['campaign']['campaignId'])) {
            $campaignId = $data['campaign']['campaignId'];
        }
        $existingSubscriber = $this->getExistingSubscriberByEmailAndcampaignId($data['email'], $campaignId);
        $data['ipAddress'] = self::get_client_ip();
        if (!empty($existingSubscriber) && count($existingSubscriber) > 0) {
            //echo"<pre>"; print_r($existingSubscriber); exit;
            $id = $existingSubscriber[0]['contactId'];
            $res = $this->send_request('/contacts/' . $id, 'POST', $data);
            return $res->success;
        } else {
            $res = $this->send_request('/contacts', 'POST', $data);
            return $res->success;
        }
    }

    private function getExistingSubscriberByEmailAndcampaignId($email, $campaignId)
    {
        $url = '/contacts?query[email]=' . $email;
        if(!empty($campaignId)) {
            $url = $url.'&query[campaignId]='.$campaignId;
        }
        $res = $this->send_request($url, 'GET');
        if (isset($res->success) && $res->success && isset($res->data) && $res->data != 'OK') {
            return $res->data;
        }
        return null;
    }

    public function list_campaigns()
    {
        $res = $this->send_request('/campaigns', 'GET');
        if (!$res->success) {
            return [];
        }

        return array_map(function ($val) {
            return (object) $val;
        }, $res->data);
    }

    public function list_tags()
    {
        $res = $this->send_request('/tags', 'GET');
        if (!$res->success) {
            return [];
        }

        return array_map(function ($val) {
            return (object) $val;
        }, $res->data);
    }
}
