<?php 
// phpcs:ignoreFile WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
// phpcs:ignoreFile WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
// phpcs:ignoreFile WordPress.WP.AlternativeFunctions.file_system_operations_fclose
// phpcs:ignoreFile WordPress.WP.AlternativeFunctions.file_system_operations_fopen
// phpcs:ignoreFile WordPress.Security.EscapeOutput.ExceptionNotEscaped            

/**
 * OrderEventApi
 * PHP version 7.4
 *
 * @category Class
 * @package  PPLCZCPL
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */

/**
 * CPL
 *
 * **Changelog**    * 2024-08-22 - SPRJ-13791 - validace PRTE / PRBC externích čísel - nelze použít najednou    - /shipment/batch    * 2024-07-01 - SPRJ-13838 - přidání    - /customer/address    * 2023-11-23 - SPRJ-12703 - CPL - /shipment - timestamp    - /shipment - Rozšíření výstupu o LastUpdateDate.    * 2023-07-13 - SPRJ-11888 - přidání    - /codelist/status - číselník statusů    * 2023-07-13 - SPRJ-11953 - přidání    - /order/cancel - storno objednávky
 *
 * The version of the OpenAPI document: v1
 * Generated by: https://openapi-generator.tech
 * OpenAPI Generator version: 6.0.1
 */

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

namespace PPLCZCPL\Api;

use PPLCZVendor\GuzzleHttp\Client;
use PPLCZVendor\GuzzleHttp\ClientInterface;
use PPLCZVendor\GuzzleHttp\Exception\ConnectException;
use PPLCZVendor\GuzzleHttp\Exception\RequestException;
use PPLCZVendor\GuzzleHttp\Psr7\MultipartStream;
use PPLCZVendor\GuzzleHttp\Psr7\Request;
use PPLCZVendor\GuzzleHttp\RequestOptions;
use PPLCZCPL\ApiException;
use PPLCZCPL\Configuration;
use PPLCZCPL\HeaderSelector;
use PPLCZCPL\ObjectSerializerPpl;

/**
 * OrderEventApi Class Doc Comment
 *
 * @category Class
 * @package  PPLCZCPL
 * @author   OpenAPI Generator team
 * @link     https://openapi-generator.tech
 */
class OrderEventApi
{
    /**
     * @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 orderCancelPost
     *
     * Zrušení objednání svozu nebo balíku z libovolné adresy
     *
     * @param  string $customer_reference Reference odesílatele (optional)
     * @param  string $order_reference Reference objednávky (optional)
     * @param  string $accept_language Language specification, default language: cs-CZ (optional)
     * @param  string $x_correlation_id Correlation Id of request (optional)
     * @param  XLogLevelSchema $x_log_level The forced log level (optional)
     * @param  \PPLCZCPL\Model\EpsApiMyApi2WebModelsOrderEventCancelOrderEventModel $eps_api_my_api2_web_models_order_event_cancel_order_event_model Event detail (optional)
     *
     * @throws \PPLCZCPL\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return void
     */
    public function orderCancelPost($customer_reference = null, $order_reference = null, $accept_language = null, $x_correlation_id = null, $x_log_level = null, $eps_api_my_api2_web_models_order_event_cancel_order_event_model = null)
    {
        $this->orderCancelPostWithHttpInfo($customer_reference, $order_reference, $accept_language, $x_correlation_id, $x_log_level, $eps_api_my_api2_web_models_order_event_cancel_order_event_model);
    }

    /**
     * Operation orderCancelPostWithHttpInfo
     *
     * Zrušení objednání svozu nebo balíku z libovolné adresy
     *
     * @param  string $customer_reference Reference odesílatele (optional)
     * @param  string $order_reference Reference objednávky (optional)
     * @param  string $accept_language Language specification, default language: cs-CZ (optional)
     * @param  string $x_correlation_id Correlation Id of request (optional)
     * @param  XLogLevelSchema $x_log_level The forced log level (optional)
     * @param  \PPLCZCPL\Model\EpsApiMyApi2WebModelsOrderEventCancelOrderEventModel $eps_api_my_api2_web_models_order_event_cancel_order_event_model Event detail (optional)
     *
     * @throws \PPLCZCPL\ApiException on non-2xx response
     * @throws \InvalidArgumentException
     * @return array of null, HTTP status code, HTTP response headers (array of strings)
     */
    public function orderCancelPostWithHttpInfo($customer_reference = null, $order_reference = null, $accept_language = null, $x_correlation_id = null, $x_log_level = null, $eps_api_my_api2_web_models_order_event_cancel_order_event_model = null)
    {
        $request = $this->orderCancelPostRequest($customer_reference, $order_reference, $accept_language, $x_correlation_id, $x_log_level, $eps_api_my_api2_web_models_order_event_cancel_order_event_model);

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

            return [null, $statusCode, $response->getHeaders()];

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 400:
                    $data = ObjectSerializerPpl::deserialize(
                        $e->getResponseBody(),
                        '\PPLCZCPL\Model\EpsApiInfrastructureWebApiModelProblemJsonModel',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
                case 500:
                    $data = ObjectSerializerPpl::deserialize(
                        $e->getResponseBody(),
                        '\PPLCZCPL\Model\EpsApiInfrastructureWebApiModelProblemJsonModel',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
                case 503:
                    $data = ObjectSerializerPpl::deserialize(
                        $e->getResponseBody(),
                        '\PPLCZCPL\Model\EpsApiInfrastructureWebApiModelProblemJsonModel',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    break;
            }
            throw $e;
        }
    }

    /**
     * Operation orderCancelPostAsync
     *
     * Zrušení objednání svozu nebo balíku z libovolné adresy
     *
     * @param  string $customer_reference Reference odesílatele (optional)
     * @param  string $order_reference Reference objednávky (optional)
     * @param  string $accept_language Language specification, default language: cs-CZ (optional)
     * @param  string $x_correlation_id Correlation Id of request (optional)
     * @param  XLogLevelSchema $x_log_level The forced log level (optional)
     * @param  \PPLCZCPL\Model\EpsApiMyApi2WebModelsOrderEventCancelOrderEventModel $eps_api_my_api2_web_models_order_event_cancel_order_event_model Event detail (optional)
     *
     * @throws \InvalidArgumentException
     * @return \PPLCZVendor\GuzzleHttp\Promise\PromiseInterface
     */
    public function orderCancelPostAsync($customer_reference = null, $order_reference = null, $accept_language = null, $x_correlation_id = null, $x_log_level = null, $eps_api_my_api2_web_models_order_event_cancel_order_event_model = null)
    {
        return $this->orderCancelPostAsyncWithHttpInfo($customer_reference, $order_reference, $accept_language, $x_correlation_id, $x_log_level, $eps_api_my_api2_web_models_order_event_cancel_order_event_model)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

    /**
     * Operation orderCancelPostAsyncWithHttpInfo
     *
     * Zrušení objednání svozu nebo balíku z libovolné adresy
     *
     * @param  string $customer_reference Reference odesílatele (optional)
     * @param  string $order_reference Reference objednávky (optional)
     * @param  string $accept_language Language specification, default language: cs-CZ (optional)
     * @param  string $x_correlation_id Correlation Id of request (optional)
     * @param  XLogLevelSchema $x_log_level The forced log level (optional)
     * @param  \PPLCZCPL\Model\EpsApiMyApi2WebModelsOrderEventCancelOrderEventModel $eps_api_my_api2_web_models_order_event_cancel_order_event_model Event detail (optional)
     *
     * @throws \InvalidArgumentException
     * @return \PPLCZVendor\GuzzleHttp\Promise\PromiseInterface
     */
    public function orderCancelPostAsyncWithHttpInfo($customer_reference = null, $order_reference = null, $accept_language = null, $x_correlation_id = null, $x_log_level = null, $eps_api_my_api2_web_models_order_event_cancel_order_event_model = null)
    {
        $returnType = '';
        $request = $this->orderCancelPostRequest($customer_reference, $order_reference, $accept_language, $x_correlation_id, $x_log_level, $eps_api_my_api2_web_models_order_event_cancel_order_event_model);

        return $this->client
            ->sendAsync($request, $this->createHttpClientOption())
            ->then(
                function ($response) use ($returnType) {
                    return [null, $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 'orderCancelPost'
     *
     * @param  string $customer_reference Reference odesílatele (optional)
     * @param  string $order_reference Reference objednávky (optional)
     * @param  string $accept_language Language specification, default language: cs-CZ (optional)
     * @param  string $x_correlation_id Correlation Id of request (optional)
     * @param  XLogLevelSchema $x_log_level The forced log level (optional)
     * @param  \PPLCZCPL\Model\EpsApiMyApi2WebModelsOrderEventCancelOrderEventModel $eps_api_my_api2_web_models_order_event_cancel_order_event_model Event detail (optional)
     *
     * @throws \InvalidArgumentException
     * @return \PPLCZVendor\GuzzleHttp\Psr7\Request
     */
    public function orderCancelPostRequest($customer_reference = null, $order_reference = null, $accept_language = null, $x_correlation_id = null, $x_log_level = null, $eps_api_my_api2_web_models_order_event_cancel_order_event_model = null)
    {

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

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializerPpl::toQueryValue(
            $customer_reference,
            'customerReference', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializerPpl::toQueryValue(
            $order_reference,
            'orderReference', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);

        // header params
        if ($accept_language !== null) {
            $headerParams['Accept-Language'] = ObjectSerializerPpl::toHeaderValue($accept_language);
        }
        // header params
        if ($x_correlation_id !== null) {
            $headerParams['X-Correlation-ID'] = ObjectSerializerPpl::toHeaderValue($x_correlation_id);
        }
        // header params
        if ($x_log_level !== null) {
            $headerParams['X-LogLevel'] = ObjectSerializerPpl::toHeaderValue($x_log_level);
        }



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

        // for model (json/xml)
        if (isset($eps_api_my_api2_web_models_order_event_cancel_order_event_model)) {
            if ($headers['Content-Type'] === 'application/json') {
                $httpBody = wp_json_encode(ObjectSerializerPpl::sanitizeForSerialization($eps_api_my_api2_web_models_order_event_cancel_order_event_model));
            } else {
                $httpBody = $eps_api_my_api2_web_models_order_event_cancel_order_event_model;
            }
        } 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 = wp_json_encode($formParams);

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

        // this endpoint requires Bearer (JWT) authentication (access token)
        if (!empty($this->config->getAccessToken())) {
            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
        }

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

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

        $query = ObjectSerializerPpl::buildQuery($queryParams);
        return new Request(
            'POST',
            $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;
    }
}
