<?php
namespace Modules\API\APIInterne\OxaMobility\Controller;

use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Utils;
use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;
use Helpers\Outil\Outils;
use Helpers\Outil\XmlHelper;
use Helpers\Session\ParseBase1;
use Modules\API\APIInterne\OxaMobility\Outil\ApiRequest;
use SimpleXMLElement;
use Skeleton\Controller\Controller;
use Skeleton\Request;

class AbsApiController extends Controller
{
    /** @var ApiRequest */
    protected Request $request;

    public function init(): void
    {
        // Leave this comment here
        // TODO : WHY ?
    }

    protected function startPhpSessionJwt() :void
    {
        $contents = file_get_contents(session_save_path() . '\\sess_' . $this->request->getJwtPayload()['sessionId']);
        session_name('__OxaProc-PHPSESSID');
        @session_start();
        session_decode((string)$contents);
    }

    public function setRequest(ApiRequest $request) :void
    {
        $this->request = $request;
    }

    /**
     * @param array<mixed> $data
     */
    public function createApiResponse(array $data, mixed $arrayString = '', int $status = 200) :Response
    {
        if ($this->request->wantJson()) {
            return $this->createJsonResponse($data, $status);
        }
        return $this->createXmlResponse($data, $arrayString, $status);
    }


    public function createJsonResponse(array $data, int $status = 200) :Response
    {
        $retourJSON['MPROC_Out'] = $data;
        if ((new ParseBase1())->getDebug()) {
            Fichier::createFichierTmp(
                LogSysteme::getServerName().'.'.str_replace('|', '_', $this->request->getAction()) . '_Out.json',
                (string)json_encode($retourJSON)
            );
        }
        return parent::createJsonResponse($retourJSON, $status);
    }

    /**
     * @param array<mixed> $return
     * @param mixed $replace
     */
    public function createXmlResponse(array $return, mixed $replace = '', int $status = 200) :Response
    {
        $xml = new SimpleXMLElement('<MPROC_Out/>');
        \Helpers\Outil\Outils::array_to_xml($return, $xml);
        
        // TODO improve and remove XML replacement should not be made in the response
        if (!is_array($replace)) {
            $replace = ['replace1' => $replace];
        }
        $s = $xml->asXML();
        foreach ($replace as $k => $v) {
            $s = str_replace($k, $v, $s);
        }

        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML($s);

        if ((new ParseBase1())->getDebug()) {
            Fichier::createFichierTmp(
                LogSysteme::getServerName()
                .'.'.str_replace('|', '_', $this->request->getAction()).'_Out.xml',
                XmlHelper::saveXML($domxml)
            );
        }

        return new Response($status, [
            'Content-Type' => 'application/xml; charset=utf-8'
        ], XmlHelper::saveXML($domxml));
    }
}
