<?php
/**
 * GoalsApi
 * PHP version 7.3
 *
 * @category Class
 * @package  Pipedrive
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Pipedrive API v1
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1.0.0
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 5.3.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace Pipedrive\Api;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Query;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Utils;
use InvalidArgumentException;
use Pipedrive\ApiException;
use Pipedrive\Configuration;
use Pipedrive\Exceptions\OAuthProviderException;
use Pipedrive\HeaderSelector;
use Pipedrive\ObjectSerializer;
use RuntimeException;

/**
 * GoalsApi Class Doc Comment
 *
 * @category Class
 * @package  Pipedrive
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class GoalsApi
{
    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var Configuration
     */
    protected $config;

    /**
     * @var HeaderSelector
     */
    protected $headerSelector;

    /**
     * @var int Host index
     */
    protected $hostIndex;

    /**
     * @param ClientInterface|null $client
     * @param Configuration|null   $config
     * @param HeaderSelector|null  $selector
     * @param int                  $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
     */
    public function __construct(
        ClientInterface $client = null,
        Configuration $config = null,
        HeaderSelector $selector = null,
        int $hostIndex = 0
    ) {
        $this->client = $client ?: new Client();
        $this->config = $config ?: new Configuration();
        $this->headerSelector = $selector ?: new HeaderSelector();
        $this->hostIndex = $hostIndex;
    }

    /**
     * Set the host index
     *
     * @param int $hostIndex Host index (required)
     */
    public function setHostIndex(int $hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

    /**
     * Get the host index
     *
     * @return int Host index
     */
    public function getHostIndex(): int
    {
        return $this->hostIndex;
    }

    /**
     * @return Configuration
     */
    public function getConfig(): Configuration
    {
        return $this->config;
    }

    /**
     * Operation addGoal
     *
     * Add a new goal
     *
     * @param  \Pipedrive\Model\NewGoal|null $new_goal new_goal (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return \Pipedrive\Model\UpsertGoalResponse
     */
    public function addGoal($new_goal = null)
    {
        list($response) = $this->addGoalWithHttpInfo($new_goal);
        return $response;
    }

    /**
     * Operation addGoalWithHttpInfo
     *
     * Add a new goal
     *
     * @param  \Pipedrive\Model\NewGoal|null $new_goal (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return array<mixed> of \Pipedrive\Model\UpsertGoalResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function addGoalWithHttpInfo($new_goal = null)
    {
        $request = $this->addGoalRequest($new_goal);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                if ($e->getCode() === 401 && $this->config->isRefreshPossible()) {
                    $this->config->refreshToken();
                    $request = $this->addGoalRequest($new_goal);
                    $response = $this->client->send($request, $options);
                } else {
                    throw new ApiException(
                        "[{$e->getCode()}] {$e->getMessage()}",
                        (int) $e->getCode(),
                        $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                        $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                    );
                }
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    /* @phpstan-ignore-next-line */
                    if ('\Pipedrive\Model\UpsertGoalResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\Pipedrive\Model\UpsertGoalResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            /* @phpstan-ignore-next-line */
            if ('\Pipedrive\Model\UpsertGoalResponse' === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, '\Pipedrive\Model\UpsertGoalResponse', []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Pipedrive\Model\UpsertGoalResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation addGoalAsync
     *
     * Add a new goal
     *
     * @param  \Pipedrive\Model\NewGoal|null $new_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function addGoalAsync($new_goal = null): PromiseInterface
    {
        return $this->addGoalAsyncWithHttpInfo($new_goal)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation addGoalAsyncWithHttpInfo
     *
     * Add a new goal
     *
     * @param  \Pipedrive\Model\NewGoal|null $new_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function addGoalAsyncWithHttpInfo($new_goal = null): PromiseInterface
    {
        $returnType = '\Pipedrive\Model\UpsertGoalResponse';
        $request = $this->addGoalRequest($new_goal);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    /* @phpstan-ignore-next-line */
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'addGoal'
     *
     * @param  \Pipedrive\Model\NewGoal|null $new_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return Request
     */
    public function addGoalRequest($new_goal = null): Request
    {

        $resourcePath = '/goals';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;





        /* @phpstan-ignore-next-line */
        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['application/json']
            );
        }

        // for model (json/xml)
        if (isset($new_goal)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($new_goal));
            } else {
                $httpBody = $new_goal;
            }
        } elseif (count($formParams) > 0) {
            /* @phpstan-ignore-next-line */
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = Query::build($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('api_token');
        if ($apiKey !== null) {
            $queryParams['api_token'] = $apiKey;
        }
        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            // If access token is expired
            if ($this->config->isRefreshPossible() && $this->config->getExpiresAt() <= time()) {
                $this->config->refreshToken();
            }
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = Query::build($queryParams);
        return new Request(
            'POST',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation deleteGoal
     *
     * Delete existing goal
     *
     * @param  string $id The ID of the goal (required)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return \Pipedrive\Model\DeleteGoalResponse
     */
    public function deleteGoal($id)
    {
        list($response) = $this->deleteGoalWithHttpInfo($id);
        return $response;
    }

    /**
     * Operation deleteGoalWithHttpInfo
     *
     * Delete existing goal
     *
     * @param  string $id The ID of the goal (required)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return array<mixed> of \Pipedrive\Model\DeleteGoalResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function deleteGoalWithHttpInfo($id)
    {
        $request = $this->deleteGoalRequest($id);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                if ($e->getCode() === 401 && $this->config->isRefreshPossible()) {
                    $this->config->refreshToken();
                    $request = $this->deleteGoalRequest($id);
                    $response = $this->client->send($request, $options);
                } else {
                    throw new ApiException(
                        "[{$e->getCode()}] {$e->getMessage()}",
                        (int) $e->getCode(),
                        $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                        $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                    );
                }
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    /* @phpstan-ignore-next-line */
                    if ('\Pipedrive\Model\DeleteGoalResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\Pipedrive\Model\DeleteGoalResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            /* @phpstan-ignore-next-line */
            if ('\Pipedrive\Model\DeleteGoalResponse' === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, '\Pipedrive\Model\DeleteGoalResponse', []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Pipedrive\Model\DeleteGoalResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation deleteGoalAsync
     *
     * Delete existing goal
     *
     * @param  string $id The ID of the goal (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function deleteGoalAsync($id): PromiseInterface
    {
        return $this->deleteGoalAsyncWithHttpInfo($id)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation deleteGoalAsyncWithHttpInfo
     *
     * Delete existing goal
     *
     * @param  string $id The ID of the goal (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function deleteGoalAsyncWithHttpInfo($id): PromiseInterface
    {
        $returnType = '\Pipedrive\Model\DeleteGoalResponse';
        $request = $this->deleteGoalRequest($id);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    /* @phpstan-ignore-next-line */
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'deleteGoal'
     *
     * @param  string $id The ID of the goal (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return Request
     */
    public function deleteGoalRequest($id): Request
    {
        // verify the required parameter 'id' is set
        /* @phpstan-ignore-next-line */
        if ($id === null || (is_array($id) && count($id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $id when calling deleteGoal'
            );
        }

        $resourcePath = '/goals/{id}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($id !== null) {
            $resourcePath = str_replace(
                '{' . 'id' . '}',
                ObjectSerializer::toPathValue($id),
                $resourcePath
            );
        }


        /* @phpstan-ignore-next-line */
        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            /* @phpstan-ignore-next-line */
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = Query::build($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('api_token');
        if ($apiKey !== null) {
            $queryParams['api_token'] = $apiKey;
        }
        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            // If access token is expired
            if ($this->config->isRefreshPossible() && $this->config->getExpiresAt() <= time()) {
                $this->config->refreshToken();
            }
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = Query::build($queryParams);
        return new Request(
            'DELETE',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getGoalResult
     *
     * Get result of a goal
     *
     * @param  string $id The ID of the goal that the results are looked for (required)
     * @param  \DateTime $period_start The start date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or after the goal duration start date. (required)
     * @param  \DateTime $period_end The end date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or before the goal duration end date. (required)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return \Pipedrive\Model\GetGoalResultResponse
     */
    public function getGoalResult($id, $period_start, $period_end)
    {
        list($response) = $this->getGoalResultWithHttpInfo($id, $period_start, $period_end);
        return $response;
    }

    /**
     * Operation getGoalResultWithHttpInfo
     *
     * Get result of a goal
     *
     * @param  string $id The ID of the goal that the results are looked for (required)
     * @param  \DateTime $period_start The start date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or after the goal duration start date. (required)
     * @param  \DateTime $period_end The end date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or before the goal duration end date. (required)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return array<mixed> of \Pipedrive\Model\GetGoalResultResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function getGoalResultWithHttpInfo($id, $period_start, $period_end)
    {
        $request = $this->getGoalResultRequest($id, $period_start, $period_end);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                if ($e->getCode() === 401 && $this->config->isRefreshPossible()) {
                    $this->config->refreshToken();
                    $request = $this->getGoalResultRequest($id, $period_start, $period_end);
                    $response = $this->client->send($request, $options);
                } else {
                    throw new ApiException(
                        "[{$e->getCode()}] {$e->getMessage()}",
                        (int) $e->getCode(),
                        $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                        $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                    );
                }
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    /* @phpstan-ignore-next-line */
                    if ('\Pipedrive\Model\GetGoalResultResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\Pipedrive\Model\GetGoalResultResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            /* @phpstan-ignore-next-line */
            if ('\Pipedrive\Model\GetGoalResultResponse' === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, '\Pipedrive\Model\GetGoalResultResponse', []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Pipedrive\Model\GetGoalResultResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getGoalResultAsync
     *
     * Get result of a goal
     *
     * @param  string $id The ID of the goal that the results are looked for (required)
     * @param  \DateTime $period_start The start date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or after the goal duration start date. (required)
     * @param  \DateTime $period_end The end date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or before the goal duration end date. (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function getGoalResultAsync($id, $period_start, $period_end): PromiseInterface
    {
        return $this->getGoalResultAsyncWithHttpInfo($id, $period_start, $period_end)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getGoalResultAsyncWithHttpInfo
     *
     * Get result of a goal
     *
     * @param  string $id The ID of the goal that the results are looked for (required)
     * @param  \DateTime $period_start The start date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or after the goal duration start date. (required)
     * @param  \DateTime $period_end The end date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or before the goal duration end date. (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function getGoalResultAsyncWithHttpInfo($id, $period_start, $period_end): PromiseInterface
    {
        $returnType = '\Pipedrive\Model\GetGoalResultResponse';
        $request = $this->getGoalResultRequest($id, $period_start, $period_end);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    /* @phpstan-ignore-next-line */
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getGoalResult'
     *
     * @param  string $id The ID of the goal that the results are looked for (required)
     * @param  \DateTime $period_start The start date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or after the goal duration start date. (required)
     * @param  \DateTime $period_end The end date of the period for which to find the goal&#39;s progress. Format: YYYY-MM-DD. This date must be the same or before the goal duration end date. (required)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return Request
     */
    public function getGoalResultRequest($id, $period_start, $period_end): Request
    {
        // verify the required parameter 'id' is set
        /* @phpstan-ignore-next-line */
        if ($id === null || (is_array($id) && count($id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $id when calling getGoalResult'
            );
        }
        // verify the required parameter 'period_start' is set
        /* @phpstan-ignore-next-line */
        if ($period_start === null || (is_array($period_start) && count($period_start) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $period_start when calling getGoalResult'
            );
        }
        // verify the required parameter 'period_end' is set
        /* @phpstan-ignore-next-line */
        if ($period_end === null || (is_array($period_end) && count($period_end) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $period_end when calling getGoalResult'
            );
        }

        $resourcePath = '/goals/{id}/results';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($period_start)) {
            $period_start = ObjectSerializer::serializeCollection($period_start, '', true);
        }
        if ($period_start !== null) {
            $queryParams['period.start'] = $period_start;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($period_end)) {
            $period_end = ObjectSerializer::serializeCollection($period_end, '', true);
        }
        if ($period_end !== null) {
            $queryParams['period.end'] = $period_end;
        }


        // path params
        if ($id !== null) {
            $resourcePath = str_replace(
                '{' . 'id' . '}',
                ObjectSerializer::toPathValue($id),
                $resourcePath
            );
        }


        /* @phpstan-ignore-next-line */
        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            /* @phpstan-ignore-next-line */
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = Query::build($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('api_token');
        if ($apiKey !== null) {
            $queryParams['api_token'] = $apiKey;
        }
        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            // If access token is expired
            if ($this->config->isRefreshPossible() && $this->config->getExpiresAt() <= time()) {
                $this->config->refreshToken();
            }
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = Query::build($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation getGoals
     *
     * Find goals
     *
     * @param  string|null $type_name The type of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $title The title of the goal (optional)
     * @param  bool|true $is_active Whether the goal is active or not (optional, default to true)
     * @param  int|null $assignee_id The ID of the user who&#39;s goal to fetch. When omitted, only your goals will be returned. (optional)
     * @param  string|null $assignee_type The type of the goal&#39;s assignee. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  float|null $expected_outcome_target The numeric value of the outcome. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $expected_outcome_tracking_metric The tracking metric of the expected outcome of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $expected_outcome_currency_id The numeric ID of the goal&#39;s currency. Only applicable to goals with &#x60;expected_outcome.tracking_metric&#x60; with value &#x60;sum&#x60;. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_pipeline_id An array of pipeline IDs or &#x60;null&#x60; for all pipelines. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $type_params_stage_id The ID of the stage. Applicable to only &#x60;deals_progressed&#x60; type of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_activity_type_id An array of IDs or &#x60;null&#x60; for all activity types. Only applicable for &#x60;activities_completed&#x60; and/or &#x60;activities_added&#x60; types of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  \DateTime|null $period_start The start date of the period for which to find goals. Date in format of YYYY-MM-DD. When &#x60;period.start&#x60; is provided, &#x60;period.end&#x60; must be provided too. (optional)
     * @param  \DateTime|null $period_end The end date of the period for which to find goals. Date in format of YYYY-MM-DD. (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return \Pipedrive\Model\GetGoalsResponse
     */
    public function getGoals($type_name = null, $title = null, $is_active = true, $assignee_id = null, $assignee_type = null, $expected_outcome_target = null, $expected_outcome_tracking_metric = null, $expected_outcome_currency_id = null, $type_params_pipeline_id = null, $type_params_stage_id = null, $type_params_activity_type_id = null, $period_start = null, $period_end = null)
    {
        list($response) = $this->getGoalsWithHttpInfo($type_name, $title, $is_active, $assignee_id, $assignee_type, $expected_outcome_target, $expected_outcome_tracking_metric, $expected_outcome_currency_id, $type_params_pipeline_id, $type_params_stage_id, $type_params_activity_type_id, $period_start, $period_end);
        return $response;
    }

    /**
     * Operation getGoalsWithHttpInfo
     *
     * Find goals
     *
     * @param  string|null $type_name The type of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $title The title of the goal (optional)
     * @param  bool|true $is_active Whether the goal is active or not (optional, default to true)
     * @param  int|null $assignee_id The ID of the user who&#39;s goal to fetch. When omitted, only your goals will be returned. (optional)
     * @param  string|null $assignee_type The type of the goal&#39;s assignee. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  float|null $expected_outcome_target The numeric value of the outcome. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $expected_outcome_tracking_metric The tracking metric of the expected outcome of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $expected_outcome_currency_id The numeric ID of the goal&#39;s currency. Only applicable to goals with &#x60;expected_outcome.tracking_metric&#x60; with value &#x60;sum&#x60;. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_pipeline_id An array of pipeline IDs or &#x60;null&#x60; for all pipelines. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $type_params_stage_id The ID of the stage. Applicable to only &#x60;deals_progressed&#x60; type of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_activity_type_id An array of IDs or &#x60;null&#x60; for all activity types. Only applicable for &#x60;activities_completed&#x60; and/or &#x60;activities_added&#x60; types of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  \DateTime|null $period_start The start date of the period for which to find goals. Date in format of YYYY-MM-DD. When &#x60;period.start&#x60; is provided, &#x60;period.end&#x60; must be provided too. (optional)
     * @param  \DateTime|null $period_end The end date of the period for which to find goals. Date in format of YYYY-MM-DD. (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return array<mixed> of \Pipedrive\Model\GetGoalsResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function getGoalsWithHttpInfo($type_name = null, $title = null, $is_active = true, $assignee_id = null, $assignee_type = null, $expected_outcome_target = null, $expected_outcome_tracking_metric = null, $expected_outcome_currency_id = null, $type_params_pipeline_id = null, $type_params_stage_id = null, $type_params_activity_type_id = null, $period_start = null, $period_end = null)
    {
        $request = $this->getGoalsRequest($type_name, $title, $is_active, $assignee_id, $assignee_type, $expected_outcome_target, $expected_outcome_tracking_metric, $expected_outcome_currency_id, $type_params_pipeline_id, $type_params_stage_id, $type_params_activity_type_id, $period_start, $period_end);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                if ($e->getCode() === 401 && $this->config->isRefreshPossible()) {
                    $this->config->refreshToken();
                    $request = $this->getGoalsRequest($type_name, $title, $is_active, $assignee_id, $assignee_type, $expected_outcome_target, $expected_outcome_tracking_metric, $expected_outcome_currency_id, $type_params_pipeline_id, $type_params_stage_id, $type_params_activity_type_id, $period_start, $period_end);
                    $response = $this->client->send($request, $options);
                } else {
                    throw new ApiException(
                        "[{$e->getCode()}] {$e->getMessage()}",
                        (int) $e->getCode(),
                        $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                        $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                    );
                }
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    /* @phpstan-ignore-next-line */
                    if ('\Pipedrive\Model\GetGoalsResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\Pipedrive\Model\GetGoalsResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            /* @phpstan-ignore-next-line */
            if ('\Pipedrive\Model\GetGoalsResponse' === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, '\Pipedrive\Model\GetGoalsResponse', []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Pipedrive\Model\GetGoalsResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation getGoalsAsync
     *
     * Find goals
     *
     * @param  string|null $type_name The type of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $title The title of the goal (optional)
     * @param  bool|true $is_active Whether the goal is active or not (optional, default to true)
     * @param  int|null $assignee_id The ID of the user who&#39;s goal to fetch. When omitted, only your goals will be returned. (optional)
     * @param  string|null $assignee_type The type of the goal&#39;s assignee. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  float|null $expected_outcome_target The numeric value of the outcome. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $expected_outcome_tracking_metric The tracking metric of the expected outcome of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $expected_outcome_currency_id The numeric ID of the goal&#39;s currency. Only applicable to goals with &#x60;expected_outcome.tracking_metric&#x60; with value &#x60;sum&#x60;. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_pipeline_id An array of pipeline IDs or &#x60;null&#x60; for all pipelines. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $type_params_stage_id The ID of the stage. Applicable to only &#x60;deals_progressed&#x60; type of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_activity_type_id An array of IDs or &#x60;null&#x60; for all activity types. Only applicable for &#x60;activities_completed&#x60; and/or &#x60;activities_added&#x60; types of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  \DateTime|null $period_start The start date of the period for which to find goals. Date in format of YYYY-MM-DD. When &#x60;period.start&#x60; is provided, &#x60;period.end&#x60; must be provided too. (optional)
     * @param  \DateTime|null $period_end The end date of the period for which to find goals. Date in format of YYYY-MM-DD. (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function getGoalsAsync($type_name = null, $title = null, $is_active = true, $assignee_id = null, $assignee_type = null, $expected_outcome_target = null, $expected_outcome_tracking_metric = null, $expected_outcome_currency_id = null, $type_params_pipeline_id = null, $type_params_stage_id = null, $type_params_activity_type_id = null, $period_start = null, $period_end = null): PromiseInterface
    {
        return $this->getGoalsAsyncWithHttpInfo($type_name, $title, $is_active, $assignee_id, $assignee_type, $expected_outcome_target, $expected_outcome_tracking_metric, $expected_outcome_currency_id, $type_params_pipeline_id, $type_params_stage_id, $type_params_activity_type_id, $period_start, $period_end)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getGoalsAsyncWithHttpInfo
     *
     * Find goals
     *
     * @param  string|null $type_name The type of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $title The title of the goal (optional)
     * @param  bool|true $is_active Whether the goal is active or not (optional, default to true)
     * @param  int|null $assignee_id The ID of the user who&#39;s goal to fetch. When omitted, only your goals will be returned. (optional)
     * @param  string|null $assignee_type The type of the goal&#39;s assignee. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  float|null $expected_outcome_target The numeric value of the outcome. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $expected_outcome_tracking_metric The tracking metric of the expected outcome of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $expected_outcome_currency_id The numeric ID of the goal&#39;s currency. Only applicable to goals with &#x60;expected_outcome.tracking_metric&#x60; with value &#x60;sum&#x60;. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_pipeline_id An array of pipeline IDs or &#x60;null&#x60; for all pipelines. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $type_params_stage_id The ID of the stage. Applicable to only &#x60;deals_progressed&#x60; type of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_activity_type_id An array of IDs or &#x60;null&#x60; for all activity types. Only applicable for &#x60;activities_completed&#x60; and/or &#x60;activities_added&#x60; types of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  \DateTime|null $period_start The start date of the period for which to find goals. Date in format of YYYY-MM-DD. When &#x60;period.start&#x60; is provided, &#x60;period.end&#x60; must be provided too. (optional)
     * @param  \DateTime|null $period_end The end date of the period for which to find goals. Date in format of YYYY-MM-DD. (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function getGoalsAsyncWithHttpInfo($type_name = null, $title = null, $is_active = true, $assignee_id = null, $assignee_type = null, $expected_outcome_target = null, $expected_outcome_tracking_metric = null, $expected_outcome_currency_id = null, $type_params_pipeline_id = null, $type_params_stage_id = null, $type_params_activity_type_id = null, $period_start = null, $period_end = null): PromiseInterface
    {
        $returnType = '\Pipedrive\Model\GetGoalsResponse';
        $request = $this->getGoalsRequest($type_name, $title, $is_active, $assignee_id, $assignee_type, $expected_outcome_target, $expected_outcome_tracking_metric, $expected_outcome_currency_id, $type_params_pipeline_id, $type_params_stage_id, $type_params_activity_type_id, $period_start, $period_end);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    /* @phpstan-ignore-next-line */
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'getGoals'
     *
     * @param  string|null $type_name The type of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $title The title of the goal (optional)
     * @param  bool|true $is_active Whether the goal is active or not (optional, default to true)
     * @param  int|null $assignee_id The ID of the user who&#39;s goal to fetch. When omitted, only your goals will be returned. (optional)
     * @param  string|null $assignee_type The type of the goal&#39;s assignee. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  float|null $expected_outcome_target The numeric value of the outcome. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  string|null $expected_outcome_tracking_metric The tracking metric of the expected outcome of the goal. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $expected_outcome_currency_id The numeric ID of the goal&#39;s currency. Only applicable to goals with &#x60;expected_outcome.tracking_metric&#x60; with value &#x60;sum&#x60;. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_pipeline_id An array of pipeline IDs or &#x60;null&#x60; for all pipelines. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int|null $type_params_stage_id The ID of the stage. Applicable to only &#x60;deals_progressed&#x60; type of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  int[]|null $type_params_activity_type_id An array of IDs or &#x60;null&#x60; for all activity types. Only applicable for &#x60;activities_completed&#x60; and/or &#x60;activities_added&#x60; types of goals. If provided, everyone&#39;s goals will be returned. (optional)
     * @param  \DateTime|null $period_start The start date of the period for which to find goals. Date in format of YYYY-MM-DD. When &#x60;period.start&#x60; is provided, &#x60;period.end&#x60; must be provided too. (optional)
     * @param  \DateTime|null $period_end The end date of the period for which to find goals. Date in format of YYYY-MM-DD. (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return Request
     */
    public function getGoalsRequest($type_name = null, $title = null, $is_active = true, $assignee_id = null, $assignee_type = null, $expected_outcome_target = null, $expected_outcome_tracking_metric = null, $expected_outcome_currency_id = null, $type_params_pipeline_id = null, $type_params_stage_id = null, $type_params_activity_type_id = null, $period_start = null, $period_end = null): Request
    {

        $resourcePath = '/goals/find';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($type_name)) {
            $type_name = ObjectSerializer::serializeCollection($type_name, '', true);
        }
        if ($type_name !== null) {
            $queryParams['type.name'] = $type_name;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($title)) {
            $title = ObjectSerializer::serializeCollection($title, '', true);
        }
        if ($title !== null) {
            $queryParams['title'] = $title;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($is_active)) {
            $is_active = ObjectSerializer::serializeCollection($is_active, '', true);
        }
        if ($is_active !== null) {
            $queryParams['is_active'] = $is_active;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($assignee_id)) {
            $assignee_id = ObjectSerializer::serializeCollection($assignee_id, '', true);
        }
        if ($assignee_id !== null) {
            $queryParams['assignee.id'] = $assignee_id;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($assignee_type)) {
            $assignee_type = ObjectSerializer::serializeCollection($assignee_type, '', true);
        }
        if ($assignee_type !== null) {
            $queryParams['assignee.type'] = $assignee_type;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($expected_outcome_target)) {
            $expected_outcome_target = ObjectSerializer::serializeCollection($expected_outcome_target, '', true);
        }
        if ($expected_outcome_target !== null) {
            $queryParams['expected_outcome.target'] = $expected_outcome_target;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($expected_outcome_tracking_metric)) {
            $expected_outcome_tracking_metric = ObjectSerializer::serializeCollection($expected_outcome_tracking_metric, '', true);
        }
        if ($expected_outcome_tracking_metric !== null) {
            $queryParams['expected_outcome.tracking_metric'] = $expected_outcome_tracking_metric;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($expected_outcome_currency_id)) {
            $expected_outcome_currency_id = ObjectSerializer::serializeCollection($expected_outcome_currency_id, '', true);
        }
        if ($expected_outcome_currency_id !== null) {
            $queryParams['expected_outcome.currency_id'] = $expected_outcome_currency_id;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($type_params_pipeline_id)) {
            $type_params_pipeline_id = ObjectSerializer::serializeCollection($type_params_pipeline_id, 'csv', true);
        }
        if ($type_params_pipeline_id !== null) {
            $queryParams['type.params.pipeline_id'] = $type_params_pipeline_id;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($type_params_stage_id)) {
            $type_params_stage_id = ObjectSerializer::serializeCollection($type_params_stage_id, '', true);
        }
        if ($type_params_stage_id !== null) {
            $queryParams['type.params.stage_id'] = $type_params_stage_id;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($type_params_activity_type_id)) {
            $type_params_activity_type_id = ObjectSerializer::serializeCollection($type_params_activity_type_id, 'csv', true);
        }
        if ($type_params_activity_type_id !== null) {
            $queryParams['type.params.activity_type_id'] = $type_params_activity_type_id;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($period_start)) {
            $period_start = ObjectSerializer::serializeCollection($period_start, '', true);
        }
        if ($period_start !== null) {
            $queryParams['period.start'] = $period_start;
        }
        // query params
        /* @phpstan-ignore-next-line */
        if (is_array($period_end)) {
            $period_end = ObjectSerializer::serializeCollection($period_end, '', true);
        }
        if ($period_end !== null) {
            $queryParams['period.end'] = $period_end;
        }




        /* @phpstan-ignore-next-line */
        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                []
            );
        }

        // for model (json/xml)
        if (count($formParams) > 0) {
            /* @phpstan-ignore-next-line */
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = Query::build($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('api_token');
        if ($apiKey !== null) {
            $queryParams['api_token'] = $apiKey;
        }
        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            // If access token is expired
            if ($this->config->isRefreshPossible() && $this->config->getExpiresAt() <= time()) {
                $this->config->refreshToken();
            }
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = Query::build($queryParams);
        return new Request(
            'GET',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation updateGoal
     *
     * Update existing goal
     *
     * @param  string $id The ID of the goal (required)
     * @param  \Pipedrive\Model\BasicGoal|null $basic_goal basic_goal (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return \Pipedrive\Model\UpsertGoalResponse
     */
    public function updateGoal($id, $basic_goal = null)
    {
        list($response) = $this->updateGoalWithHttpInfo($id, $basic_goal);
        return $response;
    }

    /**
     * Operation updateGoalWithHttpInfo
     *
     * Update existing goal
     *
     * @param  string $id The ID of the goal (required)
     * @param  \Pipedrive\Model\BasicGoal|null $basic_goal (optional)
     *
     * @throws ApiException on non-2xx response
     * @throws InvalidArgumentException|GuzzleException
     * @return array<mixed> of \Pipedrive\Model\UpsertGoalResponse, HTTP status code, HTTP response headers (array of strings)
     */
    public function updateGoalWithHttpInfo($id, $basic_goal = null)
    {
        $request = $this->updateGoalRequest($id, $basic_goal);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                if ($e->getCode() === 401 && $this->config->isRefreshPossible()) {
                    $this->config->refreshToken();
                    $request = $this->updateGoalRequest($id, $basic_goal);
                    $response = $this->client->send($request, $options);
                } else {
                    throw new ApiException(
                        "[{$e->getCode()}] {$e->getMessage()}",
                        (int) $e->getCode(),
                        $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                        $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                    );
                }
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    /* @phpstan-ignore-next-line */
                    if ('\Pipedrive\Model\UpsertGoalResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\Pipedrive\Model\UpsertGoalResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            /* @phpstan-ignore-next-line */
            if ('\Pipedrive\Model\UpsertGoalResponse' === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
            }

            return [
                ObjectSerializer::deserialize($content, '\Pipedrive\Model\UpsertGoalResponse', []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Pipedrive\Model\UpsertGoalResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation updateGoalAsync
     *
     * Update existing goal
     *
     * @param  string $id The ID of the goal (required)
     * @param  \Pipedrive\Model\BasicGoal|null $basic_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function updateGoalAsync($id, $basic_goal = null): PromiseInterface
    {
        return $this->updateGoalAsyncWithHttpInfo($id, $basic_goal)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation updateGoalAsyncWithHttpInfo
     *
     * Update existing goal
     *
     * @param  string $id The ID of the goal (required)
     * @param  \Pipedrive\Model\BasicGoal|null $basic_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return PromiseInterface
     */
    public function updateGoalAsyncWithHttpInfo($id, $basic_goal = null): PromiseInterface
    {
        $returnType = '\Pipedrive\Model\UpsertGoalResponse';
        $request = $this->updateGoalRequest($id, $basic_goal);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    /* @phpstan-ignore-next-line */
                    if ($returnType === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                    }

                    return [
                        ObjectSerializer::deserialize($content, $returnType, []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                },
                function ($exception) {
                    $response = $exception->getResponse();
                    $statusCode = $response->getStatusCode();
                    throw new ApiException(
                        sprintf(
                            '[%d] Error connecting to the API (%s)',
                            $statusCode,
                            $exception->getRequest()->getUri()
                        ),
                        $statusCode,
                        $response->getHeaders(),
                        (string) $response->getBody()
                    );
                }
            );
    }

    /**
     * Create request for operation 'updateGoal'
     *
     * @param  string $id The ID of the goal (required)
     * @param  \Pipedrive\Model\BasicGoal|null $basic_goal (optional)
     *
     * @throws InvalidArgumentException|OAuthProviderException
     * @return Request
     */
    public function updateGoalRequest($id, $basic_goal = null): Request
    {
        // verify the required parameter 'id' is set
        /* @phpstan-ignore-next-line */
        if ($id === null || (is_array($id) && count($id) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $id when calling updateGoal'
            );
        }

        $resourcePath = '/goals/{id}';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



        // path params
        if ($id !== null) {
            $resourcePath = str_replace(
                '{' . 'id' . '}',
                ObjectSerializer::toPathValue($id),
                $resourcePath
            );
        }


        /* @phpstan-ignore-next-line */
        if ($multipart) {
            $headers = $this->headerSelector->selectHeadersForMultipart(
                ['application/json']
            );
        } else {
            $headers = $this->headerSelector->selectHeaders(
                ['application/json'],
                ['application/json']
            );
        }

        // for model (json/xml)
        if (isset($basic_goal)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($basic_goal));
            } else {
                $httpBody = $basic_goal;
            }
        } elseif (count($formParams) > 0) {
            /* @phpstan-ignore-next-line */
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);

            } elseif ($headers['Content-Type'] === 'application/json') {
                $httpBody = Utils::jsonEncode($formParams);

            } else {
                // for HTTP post (form)
                $httpBody = Query::build($formParams);
            }
        }

        // this endpoint requires API key authentication
        $apiKey = $this->config->getApiKeyWithPrefix('api_token');
        if ($apiKey !== null) {
            $queryParams['api_token'] = $apiKey;
        }
        // this endpoint requires OAuth (access token)
        if ($this->config->getAccessToken() !== null) {
            // If access token is expired
            if ($this->config->isRefreshPossible() && $this->config->getExpiresAt() <= time()) {
                $this->config->refreshToken();
            }
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

        $defaultHeaders = [];
        if ($this->config->getUserAgent()) {
            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $query = Query::build($queryParams);
        return new Request(
            'PUT',
            $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Create http client option
     *
     * @throws RuntimeException on file opening failure
     * @return array<string, resource> of http client options
     */
    protected function createHttpClientOption(): array
    {
        $options = [];
        if ($this->config->getDebug()) {
            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
            if (!$options[RequestOptions::DEBUG]) {
                throw new RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
            }
        }

        return $options;
    }
}
