<?php

namespace App\Support;

use Exception;
use SoapClient;

class MySoapClient extends SoapClient
{
    private $__last_request_headers;

    /**
     * @param mixed $url WSDL url (eg: http://dominio.tld/webservice.aspx?wsdl)
     * @param array $data Array to be used to create an instance of SoapClient. Can take the same parameters as the native class
     * @throws Exception
     */

    public function __construct($url, $data)
    {
        $this->options = $data;

        if (empty($data['username']) && empty($data['password'])) {
            parent::__construct($url, $data);
        } else {
            $this->use_ntlm = true;
            NTLMStream::$user = $data['username'];
            NTLMStream::$password = $data['password'];
            NTLMStream::$domain = $data['domain'];

            // Remove HTTP stream registry
            stream_wrapper_unregister('http');

            // Register our defined NTLM stream
            if (!stream_wrapper_register('http', '\\App\\Support\\NTLMStream')) {
                throw new Exception("Unable to register HTTP Handler");
            }

            // Create an instance of SoapClient
            parent::__construct($url, $data);

            // Since our instance is using the defined NTLM stream,
            // you now need to reset the stream wrapper to use the default HTTP.
            // This way you're not messing with the rest of your application or dependencies.
            stream_wrapper_restore('http');
        }
    }


    /**
    * Create a cURL request and return the method's response
    * @param string $request
    * @param string $location
    * @param string $action
    * @param int $version
    * @param int $one_way
    * @see SoapClient::__doRequest()
    * @return mixed
    */
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $headers = array(
            'Method: POST',
            'Connection: Keep-Alive',
            'User-Agent: PHP-SOAP-CURL',
            'Content-Type: text/xml; charset=utf-8',
            'SOAPAction: "'.$action.'"',
        );
        $this->__last_request_headers = $headers;
        $ch = curl_init($location);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NTLM);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_USERPWD, NTLMStream::$user . ':' . NTLMStream::$password);

        $response = curl_exec($ch);
        return $response;
    }
    function __getLastRequestHeaders() {
        return implode("\n", $this->__last_request_headers)."\n";
    }
}
