<?php

namespace API\BVD;

use API\BVD\Traits\MatchBVD;
use API\BVD\Traits\getData;
use Helpers\Session\ParseBase1;

class BVD
{
    use MatchBVD;
    use getData;
    
    protected \GuzzleHttp\Client $client;
    protected string $token;
    protected \SimpleXMLElement $data;
    protected string $url;
    
    protected string $tokenFRS;
    protected int $countFRS;

    /**
     * @param array<mixed> $options
     */
    private function generateXML($options) :\SimpleXMLElement
    {
        $response = $this->client->post($this->url, $options);
        $dataTMP = $response->getBody()->getContents();
        //$this->code = $response->getStatusCode();
        
        $dom = new \DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
        $dom->loadXML($dataTMP);
        
        $dom = \Helpers\Outil\Document::removeAllNamespaces($dom);
        $xml = $dom->saveXML();
        if ($xml === false) {
            throw new \Exception('invalid response');
        }
        
        $xml = new \SimpleXMLElement($xml);
        
        return $xml;
    }
    
    public function __construct(\PDO $pdo)
    {
        $codeAPI = 'BVD';
        $this->client = new \GuzzleHttp\Client(['verify' => false]);
        
        $dilispec = new \Entity\Model\Dilispec($pdo);
        $dilispec = $dilispec->findAll(['TYPEDICO' => $codeAPI]);
        foreach ($dilispec as $param) {
            ${$param['CODEDICO']} = $param['LIB01DICO'];
        }

        $parametrage = file_get_contents((new ParseBase1())->getRep()->etc.'API/externe/'.$codeAPI.'/Parametres.json', true);
        if ($parametrage === false) {
            throw new \Exception('Invalid file');
        }
        $parametrage = json_decode($parametrage, true);

        /** @phpstan-ignore-next-line */
        $this->url = $parametrage[$TYPE_ENVIRONNEMENT]['BaseUrl'];

        $xmlRequest = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://bvdep.com/webservices/">
                        <soap:Header/>
                        <soap:Body>
                           <web:Open>
                              <!--Optional:-->
                              <web:username>';
                              /** @phpstan-ignore-next-line */
                              $xmlRequest .=$USER;
                              
                              $xmlRequest .='</web:username>
                              <!--Optional:-->
                              <web:password>';
                              
                              /** @phpstan-ignore-next-line */
                              $xmlRequest .=$MDP;
                              $xmlRequest .='</web:password>
                           </web:Open>
                        </soap:Body>
                     </soap:Envelope>';
        
        $options = [
            'body'    => $xmlRequest,
            'headers' => [
                "Content-Type" => "text/xml"
            ]
        ];
        
        /*$parametrage = file_get_contents((new ParseBase1())->getRep()->etc.'API/externe/'.$this->codeAPI.'/Parametres.json', true);
        $parametrage = json_decode($parametrage, true);*/
        try {
            $xml = $this->generateXML($options);
            
            $this->setToken($xml->Body->OpenResponse->OpenResult);
        } catch (\Exception $e) {
            echo 'Connection : '.$e;
            @exit;
        }
    }

    public function generateTokenById(string $idBVD) :void
    {

        $xmlRequest = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://bvdep.com/webservices/">
                            <soap:Header/>
                            <soap:Body>
                               <web:FindByBVDId>
                                  <web:sessionHandle>'.$this->token.'</web:sessionHandle>
                                  <web:id>'.$idBVD.'</web:id>
                               </web:FindByBVDId>
                            </soap:Body>
                        </soap:Envelope>';
        
        $options = [
            'body'    => $xmlRequest,
            'headers' => [
                "Content-Type" => "text/xml"
            ]
        ];
        
        try {
            $xml = $this->generateXML($options);

            $this->tokenFRS = $xml->Body->FindByBVDIdResponse->FindByBVDIdResult->Token;
            $this->countFRS = (int) $xml->Body->FindByBVDIdResponse->FindByBVDIdResult->SelectionCount;
        } catch (\Exception $e) {
            echo 'getTokenById : '.$e;
        }
    }
    
    public function disconnect() :void
    {
        $xmlRequest = '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://bvdep.com/webservices/">
                         <soap:Header/>
                         <soap:Body>
                            <web:Close>
                               <!--Optional:-->
                               <web:sessionHandle>'.$this->token.'</web:sessionHandle>
                            </web:Close>
                         </soap:Body>
                      </soap:Envelope>';
        
        $options = [
            'body'    => $xmlRequest,
            'headers' => [
                "Content-Type" => "text/xml"
            ]
        ];
        
        try {
            $response = $this->client->post('https://webservices.bvdinfo.com/orbis4/remoteaccess.asmx?WSDL', $options);
            $dataTMP = $response->getBody()->getContents();
            $metadataIDP = new \SimpleXMLElement($dataTMP);
        } catch (\Exception $e) {
            echo 'Deconnection : '.$e;
            @exit;
        }
    }
    
    public function setToken(string $token) :void
    {
        $this->token = $token;
    }
    
    public function setData(\SimpleXMLElement $data) :void
    {
        $this->data = $data;
    }
    
    public function getData() :\SimpleXMLElement
    {
        return $this->data;
    }
}
