<?php
/**
 * CreateNewWebhooksApi
 * PHP version 5
 *
 * @category Class
 * @package  CyberSource
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * CyberSource Merged Spec
 *
 * All CyberSource API specs merged together. These are available at https://developer.cybersource.com/api/reference/api-reference.html
 *
 * OpenAPI spec version: 0.0.1
 * 
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 */
/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace CyberSource\Api;

use \CyberSource\ApiClient;
use \CyberSource\ApiException;
use \CyberSource\Configuration;
use \CyberSource\ObjectSerializer;
use \CyberSource\Logging\LogFactory as LogFactory;
use \CyberSource\Authentication\Util\MLEUtility;
use \CyberSource\Utilities\MultipartHelpers\MultipartHelper;
use \Exception;

/**
 * CreateNewWebhooksApi Class Doc Comment
 *
 * @category Class
 * @package  CyberSource
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */
class CreateNewWebhooksApi
{
    private static $logger = null;
    
    /**
     * API Client
     *
     * @var \CyberSource\ApiClient instance of the ApiClient
     */
    protected $apiClient;

    /**
     * Constructor
     *
     * @param \CyberSource\ApiClient|null $apiClient The api client to use
     */
    public function __construct(\CyberSource\ApiClient $apiClient = null)
    {
        if ($apiClient === null) {
            $apiClient = new ApiClient();
        }

        $this->apiClient = $apiClient;

        if (self::$logger === null) {
            self::$logger = (new LogFactory())->getLogger(\CyberSource\Utilities\Helpers\ClassHelper::getClassName(get_class($this)), $apiClient->merchantConfig->getLogConfiguration());
        }
    }

    /**
     * Get API client
     *
     * @return \CyberSource\ApiClient get the API client
     */
    public function getApiClient()
    {
        return $this->apiClient;
    }

    /**
     * Set the API client
     *
     * @param \CyberSource\ApiClient $apiClient set the API client
     *
     * @return CreateNewWebhooksApi
     */
    public function setApiClient(\CyberSource\ApiClient $apiClient)
    {
        $this->apiClient = $apiClient;
        return $this;
    }

    /**
     * Operation findProductsToSubscribe
     *
     * Find Products You Can Subscribe To
     *
     * @param string $organizationId The Organization Identifier. (required)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2003[], HTTP status code, HTTP response headers (array of strings)
     */
    public function findProductsToSubscribe($organizationId)
    {
        self::$logger->info('CALL TO METHOD findProductsToSubscribe STARTED');
        list($response, $statusCode, $httpHeader) = $this->findProductsToSubscribeWithHttpInfo($organizationId);
        self::$logger->info('CALL TO METHOD findProductsToSubscribe ENDED');
        self::$logger->close();
        return [$response, $statusCode, $httpHeader];
    }

    /**
     * Operation findProductsToSubscribeWithHttpInfo
     *
     * Find Products You Can Subscribe To
     *
     * @param string $organizationId The Organization Identifier. (required)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2003[], HTTP status code, HTTP response headers (array of strings)
     */
    public function findProductsToSubscribeWithHttpInfo($organizationId)
    {
        // verify the required parameter 'organizationId' is set
        if ($organizationId === null) {
            self::$logger->error("InvalidArgumentException : Missing the required parameter $organizationId when calling findProductsToSubscribe");
            throw new \InvalidArgumentException('Missing the required parameter $organizationId when calling findProductsToSubscribe');
        }
        // parse inputs
        $resourcePath = "/notification-subscriptions/v2/products/{organizationId}";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/hal+json;charset=utf-8']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json;charset=utf-8']);

        // path params
        if ($organizationId !== null) {
            $resourcePath = str_replace(
                "{" . "organizationId" . "}",
                $this->apiClient->getSerializer()->toPathValue($organizationId),
                $resourcePath
            );
        }
        if ('GET' == 'POST') {
            $_tempBody = '{}';
        }

        // for model (json/xml)
        if (isset($_tempBody) and count($formParams) <= 0) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = MultipartHelper::build_data_files($boundary, $formParams); // for HTTP post (form)
        }

        //MLE check and mle encryption for req body
        $isMLESupportedByCybsForApi = false;
        if (MLEUtility::checkIsMLEForAPI($this->apiClient->merchantConfig, $isMLESupportedByCybsForApi, "findProductsToSubscribe,findProductsToSubscribeWithHttpInfo")) {
            try {
                $httpBody = MLEUtility::encryptRequestPayload($this->apiClient->merchantConfig, $httpBody);
            } catch (Exception $e) {
                self::$logger->error("Failed to encrypt request body:  $e");
                throw new ApiException("Failed to encrypt request body : " . $e->getMessage());
            }
        }

        
        // Logging
        self::$logger->debug("Resource : GET $resourcePath");
        if (isset($httpBody) and count($formParams) <= 0) {
            if ($this->apiClient->merchantConfig->getLogConfiguration()->isMaskingEnabled()) {
                $printHttpBody = \CyberSource\Utilities\Helpers\DataMasker::maskData($httpBody);
            } else {
                $printHttpBody = $httpBody;
            }
            
            self::$logger->debug("Body Parameter :\n" . $printHttpBody); 
        }

        self::$logger->debug("Return Type : \CyberSource\Model\InlineResponse2003[]");
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'GET',
                $queryParams,
                $httpBody,
                $headerParams,
                '\CyberSource\Model\InlineResponse2003[]',
                '/notification-subscriptions/v2/products/{organizationId}'
            );
            
            self::$logger->debug("Response Headers :\n" . \CyberSource\Utilities\Helpers\ListHelper::toString($httpHeader));

            return [$this->apiClient->getSerializer()->deserialize($response, '\CyberSource\Model\InlineResponse2003[]', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\CyberSource\Model\InlineResponse2003[]', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            self::$logger->error("ApiException : $e");
            throw $e;
        }
    }

    /**
     * Operation notificationSubscriptionsV2WebhooksPost
     *
     * Create a New Webhook Subscription
     *
     * @param \CyberSource\Model\CreateWebhook $createWebhook The webhook payload (optional)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2014, HTTP status code, HTTP response headers (array of strings)
     */
    public function notificationSubscriptionsV2WebhooksPost($createWebhook = null)
    {
        self::$logger->info('CALL TO METHOD notificationSubscriptionsV2WebhooksPost STARTED');
        list($response, $statusCode, $httpHeader) = $this->notificationSubscriptionsV2WebhooksPostWithHttpInfo($createWebhook);
        self::$logger->info('CALL TO METHOD notificationSubscriptionsV2WebhooksPost ENDED');
        self::$logger->close();
        return [$response, $statusCode, $httpHeader];
    }

    /**
     * Operation notificationSubscriptionsV2WebhooksPostWithHttpInfo
     *
     * Create a New Webhook Subscription
     *
     * @param \CyberSource\Model\CreateWebhook $createWebhook The webhook payload (optional)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2014, HTTP status code, HTTP response headers (array of strings)
     */
    public function notificationSubscriptionsV2WebhooksPostWithHttpInfo($createWebhook = null)
    {
        // parse inputs
        $resourcePath = "/notification-subscriptions/v2/webhooks";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/hal+json;charset=utf-8']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json;charset=utf-8']);

        // body params
        $_tempBody = null;
        if (isset($createWebhook)) {
            $_tempBody = $createWebhook;
        }
        
        $sdkTracker = new \CyberSource\Utilities\Tracking\SdkTracker();
        $modelClassLocation = explode('\\', '\CyberSource\Model\CreateWebhook');

        $_tempBody = $sdkTracker->insertDeveloperIdTracker($_tempBody, end($modelClassLocation), $this->apiClient->merchantConfig->getRunEnvironment(), $this->apiClient->merchantConfig->getDefaultDeveloperId());

        // for model (json/xml)
        if (isset($_tempBody) and count($formParams) <= 0) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = MultipartHelper::build_data_files($boundary, $formParams); // for HTTP post (form)
        }

        //MLE check and mle encryption for req body
        $isMLESupportedByCybsForApi = false;
        if (MLEUtility::checkIsMLEForAPI($this->apiClient->merchantConfig, $isMLESupportedByCybsForApi, "notificationSubscriptionsV2WebhooksPost,notificationSubscriptionsV2WebhooksPostWithHttpInfo")) {
            try {
                $httpBody = MLEUtility::encryptRequestPayload($this->apiClient->merchantConfig, $httpBody);
            } catch (Exception $e) {
                self::$logger->error("Failed to encrypt request body:  $e");
                throw new ApiException("Failed to encrypt request body : " . $e->getMessage());
            }
        }

        
        // Logging
        self::$logger->debug("Resource : POST $resourcePath");
        if (isset($httpBody) and count($formParams) <= 0) {
            if ($this->apiClient->merchantConfig->getLogConfiguration()->isMaskingEnabled()) {
                $printHttpBody = \CyberSource\Utilities\Helpers\DataMasker::maskData($httpBody);
            } else {
                $printHttpBody = $httpBody;
            }
            
            self::$logger->debug("Body Parameter :\n" . $printHttpBody); 
        }

        self::$logger->debug("Return Type : \CyberSource\Model\InlineResponse2014");
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\CyberSource\Model\InlineResponse2014',
                '/notification-subscriptions/v2/webhooks'
            );
            
            self::$logger->debug("Response Headers :\n" . \CyberSource\Utilities\Helpers\ListHelper::toString($httpHeader));

            return [$this->apiClient->getSerializer()->deserialize($response, '\CyberSource\Model\InlineResponse2014', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\CyberSource\Model\InlineResponse2014', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            self::$logger->error("ApiException : $e");
            throw $e;
        }
    }

    /**
     * Operation saveSymEgressKey
     *
     * Create Webhook Security Keys
     *
     * @param string $vCSenderOrganizationId Sender organization id (required)
     * @param string $vCPermissions Encoded user permissions returned by the CGK, for the entity user who initiated the boarding (required)
     * @param string $vCCorrelationId A globally unique id associated with your request (optional)
     * @param \CyberSource\Model\SaveSymEgressKey $saveSymEgressKey Provide egress Symmetric key information to save (create or store or refresh) (optional)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2013, HTTP status code, HTTP response headers (array of strings)
     */
    public function saveSymEgressKey($vCSenderOrganizationId, $vCPermissions, $vCCorrelationId = null, $saveSymEgressKey = null)
    {
        self::$logger->info('CALL TO METHOD saveSymEgressKey STARTED');
        list($response, $statusCode, $httpHeader) = $this->saveSymEgressKeyWithHttpInfo($vCSenderOrganizationId, $vCPermissions, $vCCorrelationId, $saveSymEgressKey);
        self::$logger->info('CALL TO METHOD saveSymEgressKey ENDED');
        self::$logger->close();
        return [$response, $statusCode, $httpHeader];
    }

    /**
     * Operation saveSymEgressKeyWithHttpInfo
     *
     * Create Webhook Security Keys
     *
     * @param string $vCSenderOrganizationId Sender organization id (required)
     * @param string $vCPermissions Encoded user permissions returned by the CGK, for the entity user who initiated the boarding (required)
     * @param string $vCCorrelationId A globally unique id associated with your request (optional)
     * @param \CyberSource\Model\SaveSymEgressKey $saveSymEgressKey Provide egress Symmetric key information to save (create or store or refresh) (optional)
     * @throws \CyberSource\ApiException on non-2xx response
     * @return array of \CyberSource\Model\InlineResponse2013, HTTP status code, HTTP response headers (array of strings)
     */
    public function saveSymEgressKeyWithHttpInfo($vCSenderOrganizationId, $vCPermissions, $vCCorrelationId = null, $saveSymEgressKey = null)
    {
        // verify the required parameter 'vCSenderOrganizationId' is set
        if ($vCSenderOrganizationId === null) {
            self::$logger->error("InvalidArgumentException : Missing the required parameter $vCSenderOrganizationId when calling saveSymEgressKey");
            throw new \InvalidArgumentException('Missing the required parameter $vCSenderOrganizationId when calling saveSymEgressKey');
        }
        // verify the required parameter 'vCPermissions' is set
        if ($vCPermissions === null) {
            self::$logger->error("InvalidArgumentException : Missing the required parameter $vCPermissions when calling saveSymEgressKey");
            throw new \InvalidArgumentException('Missing the required parameter $vCPermissions when calling saveSymEgressKey');
        }
        // parse inputs
        $resourcePath = "/kms/egress/v2/keys-sym";
        $httpBody = '';
        $queryParams = [];
        $headerParams = [];
        $formParams = [];
        
        $_header_accept = $this->apiClient->selectHeaderAccept(['application/hal+json;charset=utf-8']);
        if (!is_null($_header_accept)) {
            $headerParams['Accept'] = $_header_accept;
        }
        
        $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json;charset=utf-8']);

        // header params
        if ($vCCorrelationId !== null) {
            $headerParams['v-c-correlation-id'] = $this->apiClient->getSerializer()->toHeaderValue($vCCorrelationId);
        }
        // header params
        if ($vCSenderOrganizationId !== null) {
            $headerParams['v-c-sender-organization-id'] = $this->apiClient->getSerializer()->toHeaderValue($vCSenderOrganizationId);
        }
        // header params
        if ($vCPermissions !== null) {
            $headerParams['v-c-permissions'] = $this->apiClient->getSerializer()->toHeaderValue($vCPermissions);
        }
        // body params
        $_tempBody = null;
        if (isset($saveSymEgressKey)) {
            $_tempBody = $saveSymEgressKey;
        }
        
        $sdkTracker = new \CyberSource\Utilities\Tracking\SdkTracker();
        $modelClassLocation = explode('\\', '\CyberSource\Model\SaveSymEgressKey');

        $_tempBody = $sdkTracker->insertDeveloperIdTracker($_tempBody, end($modelClassLocation), $this->apiClient->merchantConfig->getRunEnvironment(), $this->apiClient->merchantConfig->getDefaultDeveloperId());

        // for model (json/xml)
        if (isset($_tempBody) and count($formParams) <= 0) {
            $httpBody = $_tempBody; // $_tempBody is the method argument, if present
        } elseif (count($formParams) > 0) {
            $httpBody = MultipartHelper::build_data_files($boundary, $formParams); // for HTTP post (form)
        }

        //MLE check and mle encryption for req body
        $isMLESupportedByCybsForApi = false;
        if (MLEUtility::checkIsMLEForAPI($this->apiClient->merchantConfig, $isMLESupportedByCybsForApi, "saveSymEgressKey,saveSymEgressKeyWithHttpInfo")) {
            try {
                $httpBody = MLEUtility::encryptRequestPayload($this->apiClient->merchantConfig, $httpBody);
            } catch (Exception $e) {
                self::$logger->error("Failed to encrypt request body:  $e");
                throw new ApiException("Failed to encrypt request body : " . $e->getMessage());
            }
        }

        
        // Logging
        self::$logger->debug("Resource : POST $resourcePath");
        if (isset($httpBody) and count($formParams) <= 0) {
            if ($this->apiClient->merchantConfig->getLogConfiguration()->isMaskingEnabled()) {
                $printHttpBody = \CyberSource\Utilities\Helpers\DataMasker::maskData($httpBody);
            } else {
                $printHttpBody = $httpBody;
            }
            
            self::$logger->debug("Body Parameter :\n" . $printHttpBody); 
        }

        self::$logger->debug("Return Type : \CyberSource\Model\InlineResponse2013");
        // make the API Call
        try {
            list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
                $resourcePath,
                'POST',
                $queryParams,
                $httpBody,
                $headerParams,
                '\CyberSource\Model\InlineResponse2013',
                '/kms/egress/v2/keys-sym'
            );
            
            self::$logger->debug("Response Headers :\n" . \CyberSource\Utilities\Helpers\ListHelper::toString($httpHeader));

            return [$this->apiClient->getSerializer()->deserialize($response, '\CyberSource\Model\InlineResponse2013', $httpHeader), $statusCode, $httpHeader];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 201:
                    $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\CyberSource\Model\InlineResponse2013', $e->getResponseHeaders());
                    $e->setResponseObject($data);
                    break;
            }

            self::$logger->error("ApiException : $e");
            throw $e;
        }
    }
}
