<?php
namespace Skeleton\Controller\Traits;

use GuzzleHttp\Psr7\Response as ResponseGuzzle;
use Skeleton\Renderer\RendererInterface;

trait Response
{

    protected RendererInterface $renderer;
    /**
     * redirect
     *
     * @param string $path
     * @param array<mixed> $params
     * @param array<mixed> $post
     * @return ResponseGuzzle
     */
    public function redirect(string $path, array $params = [], array $post = []) : ResponseGuzzle
    {
        if (\substr($path, 0, 4) == 'http' || \substr($path, 0, 1) == '/') {
            $redirectUri = $path;
        } else {
            $redirectUri = $this->router->generateUri($path, $params);
        }

        if ($post) {
            $tokenCSRF = \Helpers\Securite\CSRF::generateCSRFTokenPair();
            $post[array_key_first($tokenCSRF)] = $tokenCSRF[array_key_first($tokenCSRF)];
            $_SESSION['redirect_post'] = $post;
        }
       
        return (new ResponseGuzzle())->withStatus(301)->withHeader('Location', $redirectUri);
        // return (new HttpFactory())->createResponse(301)->withHeader('Location', $redirectUri);
    }

    /**
     * @param array<mixed> $params
     */
    public function redirect302(string $route, array $params = []) :ResponseGuzzle
    {
        return new ResponseGuzzle(302, [
            'Location' => $this->router->generateUri($route, $params),
        ]);
    }
    
    /**
     *
     * redirectLocation
     *
     * @param string $redirectUri
     * @return ResponseGuzzle
     */
    public function redirectLocation(string $redirectUri) : ResponseGuzzle
    {
        
        return (new ResponseGuzzle())->withStatus(301)->withHeader('Location', $redirectUri);
    }
        
    /**
     * create404Response
     *
     * @return ResponseGuzzle
     */
    protected function create404Response(?string $message = null) :ResponseGuzzle
    {
        $trad = $this->getTranslationService();
        return new ResponseGuzzle(
            404,
            [],
            $this->renderer->render('@index-error/error', [
                'message' => $message ?? $trad->t("404 Cette page n'existe pas"),
            ])
        );
    }
    protected function createErrorResponse(string $message, int $code) :ResponseGuzzle
    {
        $trad = $this->getTranslationService();
        return new ResponseGuzzle($code, [], $this->renderer->render('@index-error/error', ['message' => $trad->t($message)]));
    }
    
    /**
     * createJsonResponse
     *
     * @param  array<mixed> $data
     * @param  int $status
     * @return ResponseGuzzle
     */
    protected function createJsonResponse(array $data, int $status = 200) :ResponseGuzzle
    {
        return new ResponseGuzzle(
            $status,
            ['Content-Type' => 'application/json'],
            (string) json_encode($data)
        );
    }
}
