<?php
namespace API\Punchout;

class Punchout
{

   
    protected string $urlApi;
    protected \GuzzleHttp\Client $client;
    protected mixed $data;
    protected string $token;
    protected int $code;
    protected string $header;
    protected string $response;

    /**
     *
     * @param string $urlApi
     * @param string $contentType
     * @param string $body
     * @param string $type ('GET'/'POST')
     * @param string $contentHeader (format de la bdd séparé par | pour les ligne, et ; pour les colonnes)
     * @return mixed
     */
    public function __construct($urlApi, $contentType, $body, $type = 'POST', $contentHeader = '')
    {
        //'https://gateway.hoffmann-group.com/punchout/cxml/setup'

        $this->setUrlApi($urlApi);

        $this->client = new \GuzzleHttp\Client(['verify' => false]);
        
        $header['Content-Type'] = $contentType;
//         $contentHeader = 'SOAPAction:""';
        if ($contentHeader) {
            $spliter = explode('|', $contentHeader);
    
            foreach ($spliter as $value) {
                $spliter2 = explode(':', $value);
                $header[$spliter2[0]] = $spliter2[1];
            }
        }

        if ($type=='POST') {
            //method POST
            $response = $this->client->post($this->urlApi, [
                            'headers' => $header
                            ,'body' => $body]);
        } else {
            //method GET
            $response = $this->client->get($this->urlApi, [
                            'headers' => [
                            'Content-Type' => $contentType,
                            ],'body' => $body]);
        }
        
        $this->code = $response->getStatusCode();
        $this->header = $response->getHeaderLine('content-type');
        
        $this->response = $response->getBody()->getContents();
    }

    public function callBack(string $url) :mixed
    {
        $response = $this->client->get($url, [
           
            'headers' => [
                'Authorization' => 'Bearer '. $this->token
            ],

        ]);

        $this->code = $response->getStatusCode();
        $this->header = $response->getHeaderLine('content-type');
        
        return json_decode($response->getBody()->getContents(), true);
    }

    public function setUrlApi(string $url) :void
    {
        $this->urlApi = $url;
    }

    /**
     * @param mixed $data
     */
    public function setData($data) :void
    {
        $this->data = $data;
    }

    public function setToken(string $token) :void
    {
        $this->token = $token;
    }

    public function getCode() :int
    {
        return $this->code;
    }

    public function getHeader() :string
    {
        return $this->header;
    }
    
    public function getResponse() :string
    {
        return $this->response;
    }
}
