<?php

namespace Modules\Connexion\MiddlewareConnexion;

use GuzzleHttp\Psr7\Response;
use Helpers\Trad\ITrad;
use Modules\Connexion\Repository\ControleConnexionRepo;
use Modules\Index\Service\MagicSaml2Service;
use Skeleton\Renderer\RendererInterface;
use Psr\Container\ContainerInterface;

class SAML2 extends AbsConnexion implements InterfaceConnexion
{
    const NAMEMAGICSESSION = 'OXA_MAGIC_PASSERELLE_SAML2';
    private bool $logout = false;

    private ContainerInterface $contenaire;
    public function __construct(public \PDO $pdo, private ITrad $trad)
    {
        $this->typeConnexion = 'SAML2';
    }

    public function setLogout(bool $logout = false) : void
    {
        $this->logout = $logout;
    }

    public function setContainer(ContainerInterface $contenaire):void
    {
        $this->contenaire = $contenaire;
    }

    /**
     * @param array<mixed> $post
     */
    public function authentification(array $post = []):void
    {
        $ADFS = new \Helpers\SSO\ADFS($this->contenaire, $post, $this->pdo, false, $this->logout);
        $this->login = $ADFS->getLogin();
        \Helpers\Fichier\Fichier::createFichierTmp('PHP_SAML2_nameid.txt', $this->login);

        if ($this->login) {
            $loginTry = (new ControleConnexionRepo($this->pdo))->getInfoUser($this->login);
            if ($loginTry) {
                if ($loginTry['TYP_LOGIN'] == 'S') {
                } else {
                    $this->trad->t('Connexion SSO impossible. Vous devez utiliser le lien d\'accès à l\'application non SSO.');
                }
            } else {
                $this->error[] = $this->trad->t('Identifiant ou mot de passe incorrect');
            }
        }
    }

    /**
     * Summary of renderer
     * @return Response|null
     */
    public function renderer(RendererInterface $renderer)
    {
        /**
         * Connexion SSO SAML with Magic
         */
        if (isset($_SESSION[self::NAMEMAGICSESSION])) {
            /**
             * get token uuid in SESSION
             */
            $uuid = $_SESSION[self::NAMEMAGICSESSION];

            /**
             *  Delete session
             */
            unset($_SESSION[self::NAMEMAGICSESSION]);
            
            (new MagicSaml2Service($this->pdo))->getStringForMagic($uuid, $this->login);
            
            return new Response(200, [], $renderer->render('@magicSaml2/renderSaml2', []));
        }

        return null;
    }

    /**
     * @param array<mixed> $post
     * @return mixed
     */
    public function getMetada($post = []):mixed
    {
        return new \Helpers\SSO\ADFS($this->contenaire, $post, $this->pdo, true);
    }
}
