<?php
/**
 * SalesCreditNotesApi
 * PHP version 7.4
 *
 * @category Class
 * @package  SageOne
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * Sage Business Cloud Accounting - Accounts
 *
 * Documentation of the Sage Business Cloud Accounting API.
 *
 * The version of the OpenAPI document: 3.1
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 6.0.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 SageOne\Api;

use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\RequestOptions;
use SageOne\ApiException;
use SageOne\Configuration;
use SageOne\HeaderSelector;
use SageOne\ObjectSerializer;

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

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

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

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

    /**
     * @param ClientInterface $client
     * @param Configuration   $config
     * @param HeaderSelector  $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,
        $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($hostIndex): void
    {
        $this->hostIndex = $hostIndex;
    }

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

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

    /**
     * Operation deleteSalesCreditNotesKey
     *
     * Voids a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  string $void_reason The reason the Sales Credit Note is being voided (required unless status is DRAFT). (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\SalesCreditNote
     */
    public function deleteSalesCreditNotesKey($key, $void_reason = null)
    {
        list($response) = $this->deleteSalesCreditNotesKeyWithHttpInfo($key, $void_reason);
        return $response;
    }

    /**
     * Operation deleteSalesCreditNotesKeyWithHttpInfo
     *
     * Voids a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  string $void_reason The reason the Sales Credit Note is being voided (required unless status is DRAFT). (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\SalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function deleteSalesCreditNotesKeyWithHttpInfo($key, $void_reason = null)
    {
        $request = $this->deleteSalesCreditNotesKeyRequest($key, $void_reason);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\SalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\SalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\SalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation deleteSalesCreditNotesKeyAsync
     *
     * Voids a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  string $void_reason The reason the Sales Credit Note is being voided (required unless status is DRAFT). (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deleteSalesCreditNotesKeyAsync($key, $void_reason = null)
    {
        return $this->deleteSalesCreditNotesKeyAsyncWithHttpInfo($key, $void_reason)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation deleteSalesCreditNotesKeyAsyncWithHttpInfo
     *
     * Voids a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  string $void_reason The reason the Sales Credit Note is being voided (required unless status is DRAFT). (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function deleteSalesCreditNotesKeyAsyncWithHttpInfo($key, $void_reason = null)
    {
        $returnType = '\SageOne\Model\SalesCreditNote';
        $request = $this->deleteSalesCreditNotesKeyRequest($key, $void_reason);

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

                    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 'deleteSalesCreditNotesKey'
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  string $void_reason The reason the Sales Credit Note is being voided (required unless status is DRAFT). (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function deleteSalesCreditNotesKeyRequest($key, $void_reason = null)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling deleteSalesCreditNotesKey'
            );
        }

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

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $void_reason,
            'void_reason', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);


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


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

        // for model (json/xml)
        if (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

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

    /**
     * Operation getSalesCreditNotes
     *
     * Returns all Sales Credit Notes
     *
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $search Use this to filter by the credit note reference or contact name. (optional)
     * @param  string $contact_id Use this to filter by contact id (optional)
     * @param  string $status_id Use this to filter by status id (optional)
     * @param  \DateTime $from_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $to_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Sales Credit Notes changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Sales Credit Notes deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Notes. (optional)
     * @param  int $items_per_page Returns the given number of Sales Credit Notes per request. (optional, default to 20)
     * @param  int $page Go to specific page of Sales Credit Notes (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Notes (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\PagingSalesCreditNote
     */
    public function getSalesCreditNotes($show_payments_allocations = null, $search = null, $contact_id = null, $status_id = null, $from_date = null, $to_date = null, $updated_or_created_since = null, $deleted_since = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        list($response) = $this->getSalesCreditNotesWithHttpInfo($show_payments_allocations, $search, $contact_id, $status_id, $from_date, $to_date, $updated_or_created_since, $deleted_since, $show_legacy_id, $items_per_page, $page, $attributes);
        return $response;
    }

    /**
     * Operation getSalesCreditNotesWithHttpInfo
     *
     * Returns all Sales Credit Notes
     *
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $search Use this to filter by the credit note reference or contact name. (optional)
     * @param  string $contact_id Use this to filter by contact id (optional)
     * @param  string $status_id Use this to filter by status id (optional)
     * @param  \DateTime $from_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $to_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Sales Credit Notes changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Sales Credit Notes deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Notes. (optional)
     * @param  int $items_per_page Returns the given number of Sales Credit Notes per request. (optional, default to 20)
     * @param  int $page Go to specific page of Sales Credit Notes (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Notes (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\PagingSalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function getSalesCreditNotesWithHttpInfo($show_payments_allocations = null, $search = null, $contact_id = null, $status_id = null, $from_date = null, $to_date = null, $updated_or_created_since = null, $deleted_since = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        $request = $this->getSalesCreditNotesRequest($show_payments_allocations, $search, $contact_id, $status_id, $from_date, $to_date, $updated_or_created_since, $deleted_since, $show_legacy_id, $items_per_page, $page, $attributes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\PagingSalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\PagingSalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\PagingSalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation getSalesCreditNotesAsync
     *
     * Returns all Sales Credit Notes
     *
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $search Use this to filter by the credit note reference or contact name. (optional)
     * @param  string $contact_id Use this to filter by contact id (optional)
     * @param  string $status_id Use this to filter by status id (optional)
     * @param  \DateTime $from_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $to_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Sales Credit Notes changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Sales Credit Notes deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Notes. (optional)
     * @param  int $items_per_page Returns the given number of Sales Credit Notes per request. (optional, default to 20)
     * @param  int $page Go to specific page of Sales Credit Notes (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Notes (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesCreditNotesAsync($show_payments_allocations = null, $search = null, $contact_id = null, $status_id = null, $from_date = null, $to_date = null, $updated_or_created_since = null, $deleted_since = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        return $this->getSalesCreditNotesAsyncWithHttpInfo($show_payments_allocations, $search, $contact_id, $status_id, $from_date, $to_date, $updated_or_created_since, $deleted_since, $show_legacy_id, $items_per_page, $page, $attributes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getSalesCreditNotesAsyncWithHttpInfo
     *
     * Returns all Sales Credit Notes
     *
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $search Use this to filter by the credit note reference or contact name. (optional)
     * @param  string $contact_id Use this to filter by contact id (optional)
     * @param  string $status_id Use this to filter by status id (optional)
     * @param  \DateTime $from_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $to_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Sales Credit Notes changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Sales Credit Notes deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Notes. (optional)
     * @param  int $items_per_page Returns the given number of Sales Credit Notes per request. (optional, default to 20)
     * @param  int $page Go to specific page of Sales Credit Notes (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Notes (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesCreditNotesAsyncWithHttpInfo($show_payments_allocations = null, $search = null, $contact_id = null, $status_id = null, $from_date = null, $to_date = null, $updated_or_created_since = null, $deleted_since = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        $returnType = '\SageOne\Model\PagingSalesCreditNote';
        $request = $this->getSalesCreditNotesRequest($show_payments_allocations, $search, $contact_id, $status_id, $from_date, $to_date, $updated_or_created_since, $deleted_since, $show_legacy_id, $items_per_page, $page, $attributes);

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

                    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 'getSalesCreditNotes'
     *
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $search Use this to filter by the credit note reference or contact name. (optional)
     * @param  string $contact_id Use this to filter by contact id (optional)
     * @param  string $status_id Use this to filter by status id (optional)
     * @param  \DateTime $from_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $to_date Use this to filter by Sales Credit Notes dates (optional)
     * @param  \DateTime $updated_or_created_since Use this to limit the response to Sales Credit Notes changed since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Inclusive of the passed timestamp. (optional)
     * @param  \DateTime $deleted_since Use this to limit the response to Sales Credit Notes deleted since a given date (format: YYYY-MM-DDT(+|-)hh:mm) or date-time (format: YYYY-MM-DDThh:mm:ss(+|-)hh:mm). Not inclusive of the passed timestamp. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Notes. (optional)
     * @param  int $items_per_page Returns the given number of Sales Credit Notes per request. (optional, default to 20)
     * @param  int $page Go to specific page of Sales Credit Notes (optional, default to 1)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Notes (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getSalesCreditNotesRequest($show_payments_allocations = null, $search = null, $contact_id = null, $status_id = null, $from_date = null, $to_date = null, $updated_or_created_since = null, $deleted_since = null, $show_legacy_id = null, $items_per_page = 20, $page = 1, $attributes = null)
    {
        if ($items_per_page !== null && $items_per_page > 200) {
            throw new \InvalidArgumentException('invalid value for "$items_per_page" when calling SalesCreditNotesApi.getSalesCreditNotes, must be smaller than or equal to 200.');
        }
        if ($items_per_page !== null && $items_per_page < 1) {
            throw new \InvalidArgumentException('invalid value for "$items_per_page" when calling SalesCreditNotesApi.getSalesCreditNotes, must be bigger than or equal to 1.');
        }


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

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_payments_allocations,
            'show_payments_allocations', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $search,
            'search', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $contact_id,
            'contact_id', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $status_id,
            'status_id', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $from_date,
            'from_date', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $to_date,
            'to_date', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $updated_or_created_since,
            'updated_or_created_since', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $deleted_since,
            'deleted_since', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_legacy_id,
            'show_legacy_id', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $items_per_page,
            'items_per_page', // param base name
            'integer', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page,
            'page', // param base name
            'integer', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $attributes,
            'attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);




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

        // for model (json/xml)
        if (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

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

    /**
     * Operation getSalesCreditNotesKey
     *
     * Returns a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Sales Credit Note (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $mark_as_sent Use this to mark/not mark the artefact as sent. Defaulted to &#39;true&#39;. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Note. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Note (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\SalesCreditNote
     */
    public function getSalesCreditNotesKey($key, $show_payments_allocations = null, $nested_attributes = null, $mark_as_sent = null, $show_legacy_id = null, $attributes = null)
    {
        list($response) = $this->getSalesCreditNotesKeyWithHttpInfo($key, $show_payments_allocations, $nested_attributes, $mark_as_sent, $show_legacy_id, $attributes);
        return $response;
    }

    /**
     * Operation getSalesCreditNotesKeyWithHttpInfo
     *
     * Returns a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Sales Credit Note (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $mark_as_sent Use this to mark/not mark the artefact as sent. Defaulted to &#39;true&#39;. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Note. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Note (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\SalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function getSalesCreditNotesKeyWithHttpInfo($key, $show_payments_allocations = null, $nested_attributes = null, $mark_as_sent = null, $show_legacy_id = null, $attributes = null)
    {
        $request = $this->getSalesCreditNotesKeyRequest($key, $show_payments_allocations, $nested_attributes, $mark_as_sent, $show_legacy_id, $attributes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\SalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\SalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\SalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation getSalesCreditNotesKeyAsync
     *
     * Returns a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Sales Credit Note (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $mark_as_sent Use this to mark/not mark the artefact as sent. Defaulted to &#39;true&#39;. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Note. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Note (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesCreditNotesKeyAsync($key, $show_payments_allocations = null, $nested_attributes = null, $mark_as_sent = null, $show_legacy_id = null, $attributes = null)
    {
        return $this->getSalesCreditNotesKeyAsyncWithHttpInfo($key, $show_payments_allocations, $nested_attributes, $mark_as_sent, $show_legacy_id, $attributes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation getSalesCreditNotesKeyAsyncWithHttpInfo
     *
     * Returns a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Sales Credit Note (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $mark_as_sent Use this to mark/not mark the artefact as sent. Defaulted to &#39;true&#39;. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Note. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Note (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function getSalesCreditNotesKeyAsyncWithHttpInfo($key, $show_payments_allocations = null, $nested_attributes = null, $mark_as_sent = null, $show_legacy_id = null, $attributes = null)
    {
        $returnType = '\SageOne\Model\SalesCreditNote';
        $request = $this->getSalesCreditNotesKeyRequest($key, $show_payments_allocations, $nested_attributes, $mark_as_sent, $show_legacy_id, $attributes);

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

                    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 'getSalesCreditNotesKey'
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  bool $show_payments_allocations Use this to show the artefact&#39;s payments and allocations (optional)
     * @param  string $nested_attributes Specify the attributes that you want to expose for nested entities of the Sales Credit Note (expose all nested attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     * @param  bool $mark_as_sent Use this to mark/not mark the artefact as sent. Defaulted to &#39;true&#39;. (optional)
     * @param  bool $show_legacy_id Display the legacy_id for the Sales Credit Note. (optional)
     * @param  string $attributes Specify the attributes that you want to expose for the Sales Credit Note (expose all attributes with &#39;all&#39;). These are in addition to the base attributes (name, path) (optional)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function getSalesCreditNotesKeyRequest($key, $show_payments_allocations = null, $nested_attributes = null, $mark_as_sent = null, $show_legacy_id = null, $attributes = null)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling getSalesCreditNotesKey'
            );
        }

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

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_payments_allocations,
            'show_payments_allocations', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $nested_attributes,
            'nested_attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $mark_as_sent,
            'mark_as_sent', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $show_legacy_id,
            'show_legacy_id', // param base name
            'boolean', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $attributes,
            'attributes', // param base name
            'string', // openApiType
            '', // style
            false, // explode
            false // required
        ) ?? []);


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


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

        // for model (json/xml)
        if (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

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

    /**
     * Operation postSalesCreditNotes
     *
     * Creates a Sales Credit Note
     *
     * @param  \SageOne\Model\PostSalesCreditNotes $sales_credit_notes sales_credit_notes (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\SalesCreditNote
     */
    public function postSalesCreditNotes($sales_credit_notes)
    {
        list($response) = $this->postSalesCreditNotesWithHttpInfo($sales_credit_notes);
        return $response;
    }

    /**
     * Operation postSalesCreditNotesWithHttpInfo
     *
     * Creates a Sales Credit Note
     *
     * @param  \SageOne\Model\PostSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\SalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function postSalesCreditNotesWithHttpInfo($sales_credit_notes)
    {
        $request = $this->postSalesCreditNotesRequest($sales_credit_notes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 201:
                    if ('\SageOne\Model\SalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\SalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\SalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation postSalesCreditNotesAsync
     *
     * Creates a Sales Credit Note
     *
     * @param  \SageOne\Model\PostSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postSalesCreditNotesAsync($sales_credit_notes)
    {
        return $this->postSalesCreditNotesAsyncWithHttpInfo($sales_credit_notes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation postSalesCreditNotesAsyncWithHttpInfo
     *
     * Creates a Sales Credit Note
     *
     * @param  \SageOne\Model\PostSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postSalesCreditNotesAsyncWithHttpInfo($sales_credit_notes)
    {
        $returnType = '\SageOne\Model\SalesCreditNote';
        $request = $this->postSalesCreditNotesRequest($sales_credit_notes);

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

                    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 'postSalesCreditNotes'
     *
     * @param  \SageOne\Model\PostSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function postSalesCreditNotesRequest($sales_credit_notes)
    {
        // verify the required parameter 'sales_credit_notes' is set
        if ($sales_credit_notes === null || (is_array($sales_credit_notes) && count($sales_credit_notes) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $sales_credit_notes when calling postSalesCreditNotes'
            );
        }

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





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

        // for model (json/xml)
        if (isset($sales_credit_notes)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($sales_credit_notes));
            } else {
                $httpBody = $sales_credit_notes;
            }
        } elseif (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

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

    /**
     * Operation postSalesCreditNotesKeyRelease
     *
     * Releases a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\SalesCreditNote
     */
    public function postSalesCreditNotesKeyRelease($key)
    {
        list($response) = $this->postSalesCreditNotesKeyReleaseWithHttpInfo($key);
        return $response;
    }

    /**
     * Operation postSalesCreditNotesKeyReleaseWithHttpInfo
     *
     * Releases a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\SalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function postSalesCreditNotesKeyReleaseWithHttpInfo($key)
    {
        $request = $this->postSalesCreditNotesKeyReleaseRequest($key);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 201:
                    if ('\SageOne\Model\SalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\SalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\SalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation postSalesCreditNotesKeyReleaseAsync
     *
     * Releases a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postSalesCreditNotesKeyReleaseAsync($key)
    {
        return $this->postSalesCreditNotesKeyReleaseAsyncWithHttpInfo($key)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation postSalesCreditNotesKeyReleaseAsyncWithHttpInfo
     *
     * Releases a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function postSalesCreditNotesKeyReleaseAsyncWithHttpInfo($key)
    {
        $returnType = '\SageOne\Model\SalesCreditNote';
        $request = $this->postSalesCreditNotesKeyReleaseRequest($key);

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

                    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 'postSalesCreditNotesKeyRelease'
     *
     * @param  string $key The Sales Credit Note Key. (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function postSalesCreditNotesKeyReleaseRequest($key)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling postSalesCreditNotesKeyRelease'
            );
        }

        $resourcePath = '/sales_credit_notes/{key}/release';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;



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


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

        // for model (json/xml)
        if (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

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

    /**
     * Operation putSalesCreditNotesKey
     *
     * Updates a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  \SageOne\Model\PutSalesCreditNotes $sales_credit_notes sales_credit_notes (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return \SageOne\Model\SalesCreditNote
     */
    public function putSalesCreditNotesKey($key, $sales_credit_notes)
    {
        list($response) = $this->putSalesCreditNotesKeyWithHttpInfo($key, $sales_credit_notes);
        return $response;
    }

    /**
     * Operation putSalesCreditNotesKeyWithHttpInfo
     *
     * Updates a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  \SageOne\Model\PutSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \SageOne\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of \SageOne\Model\SalesCreditNote, HTTP status code, HTTP response headers (array of strings)
     */
    public function putSalesCreditNotesKeyWithHttpInfo($key, $sales_credit_notes)
    {
        $request = $this->putSalesCreditNotesKeyRequest($key, $sales_credit_notes);

        try {
            $options = $this->createHttpClientOption();
            try {
                $response = $this->client->send($request, $options);
            } catch (RequestException $e) {
                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();

            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()
                );
            }

            switch($statusCode) {
                case 200:
                    if ('\SageOne\Model\SalesCreditNote' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\SageOne\Model\SalesCreditNote' !== 'string') {
                            $content = json_decode($content);
                        }
                    }

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

            $returnType = '\SageOne\Model\SalesCreditNote';
            if ($returnType === '\SplFileObject') {
                $content = $response->getBody(); //stream goes to serializer
            } else {
                $content = (string) $response->getBody();
                if ($returnType !== 'string') {
                    $content = json_decode($content);
                }
            }

            return [
                ObjectSerializer::deserialize($content, $returnType, []),
                $response->getStatusCode(),
                $response->getHeaders()
            ];

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

    /**
     * Operation putSalesCreditNotesKeyAsync
     *
     * Updates a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  \SageOne\Model\PutSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function putSalesCreditNotesKeyAsync($key, $sales_credit_notes)
    {
        return $this->putSalesCreditNotesKeyAsyncWithHttpInfo($key, $sales_credit_notes)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation putSalesCreditNotesKeyAsyncWithHttpInfo
     *
     * Updates a Sales Credit Note
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  \SageOne\Model\PutSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Promise\PromiseInterface
     */
    public function putSalesCreditNotesKeyAsyncWithHttpInfo($key, $sales_credit_notes)
    {
        $returnType = '\SageOne\Model\SalesCreditNote';
        $request = $this->putSalesCreditNotesKeyRequest($key, $sales_credit_notes);

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

                    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 'putSalesCreditNotesKey'
     *
     * @param  string $key The Sales Credit Note Key. (required)
     * @param  \SageOne\Model\PutSalesCreditNotes $sales_credit_notes (required)
     *
     * @throws \InvalidArgumentException
     * @return \GuzzleHttp\Psr7\Request
     */
    public function putSalesCreditNotesKeyRequest($key, $sales_credit_notes)
    {
        // verify the required parameter 'key' is set
        if ($key === null || (is_array($key) && count($key) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $key when calling putSalesCreditNotesKey'
            );
        }
        // verify the required parameter 'sales_credit_notes' is set
        if ($sales_credit_notes === null || (is_array($sales_credit_notes) && count($sales_credit_notes) === 0)) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $sales_credit_notes when calling putSalesCreditNotesKey'
            );
        }

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



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


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

        // for model (json/xml)
        if (isset($sales_credit_notes)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($sales_credit_notes));
            } else {
                $httpBody = $sales_credit_notes;
            }
        } elseif (count($formParams) > 0) {
            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 = \GuzzleHttp\json_encode($formParams);

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


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

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

        $query = ObjectSerializer::buildQuery($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 of http client options
     */
    protected function createHttpClientOption()
    {
        $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;
    }
}
