<?php
namespace Modules\Utilisateur\Controller;

use Entity\Model\Hastutil;
use Entity\Model\OxaUserPanier;
use Entity\Model\OxaUsers;
use Entity\Model\UsrBack;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Pagination\Paginator;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Index\Outil\OutilConnexion;
use Modules\Panier\Service\OutilPanierService;
use Modules\Utilisateur\Repository\UserBackupRepo;
use Modules\Utilisateur\Service\BackUpService;
use Skeleton\Application;
use Skeleton\Controller\Controller;

class MesBackupController extends Controller
{
    
    public function mesBackupAction() : string
    {
        Ariane::init();
        

        $mesBackup = new UserBackupRepo($this->pdo);
        $listeBackup = $mesBackup->getBackup();

        return $this->renderer->render('@Utilisateur/Mesbackup/mesBackup', [
            'hasBackup' => Roles::droitsUtilisateur($this->pdo, 'OX_AF_BACK'),
            'listeBackup' => $listeBackup,
        ]);
    }

    public function deleteBackupAction() : string
    {
        $id = $this->request->getAttribute('idBackup');

        $usrBackup = new UsrBack($this->pdo);
        $usrBackup->delete(['COD_USR' => $_SESSION["Session_Login"], 'COD_BAC' => $id]);

        return '';
    }

    public function listeBackupAction() : string
    {
        $post = $this->request->getParsedBody();

        $mesBackup = new UserBackupRepo($this->pdo);
        $listeUser = $mesBackup->listeBackupDispo($post);

        $paginator = new Paginator();
        $infoPagination = $paginator->generate($listeUser, 8, $post, $this->renderer);

        return $this->renderer->render('@Utilisateur/Mesbackup/listeUser', [
            'listeUser' => $listeUser,
            'infoPagination' => $infoPagination,
            'post' => $post
        ]);
    }

    /**
     * @return mixed
     */
    public function addBackupAction()
    {
        $post   = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        if ($post) {
            $validator = $this->createValidator();

            $mesBackup = new UserBackupRepo($this->pdo);
            $listeUser = $mesBackup->listeBackupDispo(['filter_egal_CODE' => $post['CODE_BAC']]);
    
            $validator->isObligatoire($post['CODE_BAC'], $trad->t('Login du nouveau backup'));
            $validator->isFalse($listeUser, trad::strBuild($trad->t('L\'utilisateur @1@ ne fait pas partie de la liste des backups disponibles.'), $post['CODE_BAC']));
            $validator->isCheck($post['ACHAT']);
            $validator->isCheck($post['SUPHIER']);

            if (!$post['ACHAT'] && !$post['SUPHIER']) {
                $validator->setError($trad->t('Le backup doit avoir au moins une fonction cochée.'));
            }
            
            if ($validator->isValid()) {
                $usrBackup = new UsrBack($this->pdo);
                $usrBackup->insert([
                    'COD_USR' => $_SESSION["Session_Login"],
                    'COD_BAC' => $post['CODE_BAC'],
                    'numerique_ACHAT' => Sql::setBoolSql($post['ACHAT']),
                    'numerique_SUPHIER' => Sql::setBoolSql($post['SUPHIER']),
                ]);

                return new Response(443, [
                    
                ], (string) \json_encode([
                    'statut' => 'O',
                    'path' => $this->router->generateUri('Utilisateur.MesBackup.mesBackup'),
                ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                    'desactiveRow' => true,
                ]);
            }
        }

        return $this->renderer->render('@Utilisateur/Mesbackup/addBackup', [
            'hasBackup' => roles::droitsUtilisateur($this->pdo, 'OX_AF_BACK'),
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxValidBackupAction()
    {
        $post = $this->request->getParsedBody();
        
        $validator = $this->createValidator();

        $mesBackup = new UserBackupRepo($this->pdo);
        $listeUser = $mesBackup->listeBackupDispo(['filter_egal_CODE' => $post['value']]);
        $trad = $this->getTranslationService();
        $validator->isFalse($listeUser, Trad::strBuild($trad->t('L\'utilisateur @1@ ne fait pas partie de la liste des backups disponibles.'), $post['value']));

        if ($validator->isValid()) {
            return new Response(200, [
                
            ], $validator->getError());
        } else {
            return new Response(200, [
                
            ], $validator->getError());
        }
    }

    /**
     * @return Response
     */
    public function activeBackupAction()
    {
        $post = $this->request->getParsedBody(true);
        $idUser = $post['idBackup'];

        $isValid = (new UserBackupRepo($this->pdo))->userValid($idUser);
        if (!$isValid) {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $this->getTranslationService()->t("Le délégateur sélectionné n'est pas valide : compte utilisateur non valide ou application non paramétrée sur le profil utilisateur"),
                'desactiveRow' => true,
            ]));
        }
        
        $backUpService = new BackUpService($this->pdo, $this->pdoOxaFT, $_SESSION['Session_Login']);
        $backUpService->initSession();
        $backUpService->changeBackup($this->contenaire, $idUser);

        return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Index.Index.index')]));
    }

    /**
     * @return Response
     */
    public function desactiveBackUpAction()
    {
        $backUpService = new BackUpService($this->pdo, $this->pdoOxaFT, $_SESSION['user_origine']);

        $backUpService->initSession();
        $backUpService->deconnexioBackUp($this->contenaire);

        return new Response(443, [], (string) json_encode(['path' => $this->router->generateUri('Index.Index.index')]));
    }
}
