<?php
namespace API\Punchout;

class Punchout
{

   
    protected $urlApi;
    protected $client;
    protected $data;
    protected $token;
    protected $code;
    protected $header;
    protected $response;

    /**
     *
     * @param string $urlApi
     * @param string $contentType
     * @param string $body
     * @param string $type ('GET'/'POST')
     * @param string $format
     * @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($url)
    {
        $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($url)
    {
        $this->urlApi = $url;
    }

    public function setData($data)
    {
        $this->data = $data;
    }

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

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

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