<?php

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

    protected function makeApiRequest($endpoint, $method = 'GET', $data = [])
    {
        try {
            $url = $this->url . $endpoint;
            $args = [
                'method'  => $method,
                'headers' => [
                    'Authorization' => 'Bearer ' . $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;
                return [];
            }

            $body = wp_remote_retrieve_body($response);
            $decodedBody = json_decode($body, true);
            //echo"<pre>"; print_r($decodedBody); exit;
            return $decodedBody;
        } catch (Exception $e) {
            return [];
        }
    }

    public function get_lists()
    {
        $res = [];
        try {
            $response = $this->makeApiRequest('contacts/v1/lists?count=250', 'GET');
            if (isset($response) && !empty($response) && isset($response['lists'])) {
                foreach ($response['lists'] as $item) {
                    $res[] = (object) [
                        'id' => strval($item['listId']),
                        'name' => $item['name']
                    ];
                }
            }
            //echo"<pre>"; print_r($res); exit;
            return $res;
        } catch (Exception $e) {
            return $res;
        }
    }

    public function getContactByEmail($email)
    {
        try {
            $response = $this->makeApiRequest('crm/v3/objects/contacts/search', 'POST', [
                'filterGroups' => [
                    [
                        'filters' => [
                            [
                                'propertyName' => 'email',
                                'operator' => 'EQ',
                                'value' => $email
                            ]
                        ]
                    ]
                ],
                'properties' => ['email'],
                'limit' => 1
            ]);
            return $response['results'][0] ?? null;
        } catch (Exception $e) {
            return [];
        }
    }

    public function createOrUpdateContact($data)
    {
        $existingContact = $this->getContactByEmail($data['properties']['email']);
        if (isset($existingContact) && isset($existingContact['id']) && $existingContact['id'] != '') {
            $contactId = $existingContact['id'];
            return $this->makeApiRequest("crm/v3/objects/contacts/{$contactId}", 'PATCH', $data);
        } else {
            return $this->makeApiRequest("crm/v3/objects/contacts/", 'POST', $data);
        }
    }

    public function batchAddContactsToLists($contactId, $listIds)
    {
        $batchData = [
            'vids' => [$contactId]
        ];
        foreach ($listIds as $listId) {
            $this->makeApiRequest("contacts/v1/lists/{$listId}/add", 'POST', $batchData);
        }
    }

    // Batch remove contacts from lists
    public function batchRemoveContactsFromLists($contactId, $listIds)
    {
        $batchData = [
            'vids' => [$contactId]
        ];
        foreach ($listIds as $listId) {
            $this->makeApiRequest("contacts/v1/lists/{$listId}/remove", 'POST', $batchData);
        }
    }

    public function manageContactLists($data)
    {
        $createOrUpdateResponse = $this->createOrUpdateContact($data);
        //echo "<pre>"; print_r($createOrUpdateResponse); exit;
        $contactId = $createOrUpdateResponse['id'];
        
        if (isset($data['removeListIds']) && !empty($data['removeListIds'])) {
            $this->batchRemoveContactsFromLists($contactId, $data['removeListIds']);
        }

        if (isset($data['addListIds']) && !empty($data['addListIds'])) {
            $this->batchAddContactsToLists($contactId, $data['addListIds']);
        }
    }
}
