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

use Modules\API\APIInterne\Magic\Outil\TranslateJwtError;
use Modules\API\Authenticate\Service\AuthService;
use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Modules\API\APIInterne\Magic\Service\Files;

abstract class AbstractController extends Controller
{
    /** @var AuthService $authService */
    protected AuthService $authService;
    
    /** @var Files $files */
    protected Files $files;
    
    /** @var array<mixed> $body */
    protected $body;

    /** @var array<mixed> $header */
    protected array $header;
    
    /**
     * init
     *
     * @return Response | void
     */
    public function init()
    {
        $this->authService = new AuthService($this->pdo, $this->JWTKEY);
       
        $payload = $this->authService->getPayloadWithTokenJWT(
            explode(' ', trim($_SERVER['HTTP_AUTHORIZATION']))[1] ?? ''
        );
        $this->header = $this->request->getServerParams();
        $this->files = new Files();
        if (!$payload['success']) {
            $outil = new TranslateJwtError($this->contenaire->get(\Helpers\Trad\ITrad::class));
            $translatedMessage = $outil->getTranslatedMessage($payload['message']);
            return new Response(
                $this->authService->getStatusCode(),
                [
                    'Content-Type' => 'application/json'
                ],
                (string)\json_encode(
                    [
                        'Error' => $this->authService->getMessageStatusCode(),
                        'Message' => $translatedMessage
                    ]
                )
            );
        }

        $bodyContent = $this->request->getBody()->getContents();
        $bodyContent = preg_replace('#:[ ]{0,100}(true)[,]{0,1}#sUim', ': "true"', $bodyContent);
        $bodyContent = preg_replace('#:[ ]{0,100}(false)[,]{0,1}#sUim', ': "false"', $bodyContent);

        if ($bodyContent != '') {
            $this->body = json_decode(
                $bodyContent,
                true
            );
            
            if (!is_array($this->body)) {
                return new Response(
                    415,
                    [
                        'Content-Type' => 'application/json'
                    ],
                    (string) json_encode([
                        'Error' => 'The JSON format is incorrect'
                    ])
                );
            }
        }
    }
    
    /**
     * errorRules
     *
     * @return Response
     */
    public function errorRules() : Response
    {
        return new Response(
            406,
            [
                'Content-Type' => 'application/json'
            ],
            (string)\json_encode(
                ['Error' => 'Unauthorized']
            )
        );
    }
}
