<?php

namespace Modules\Evaluation\Controller;

use Entity\Model\BibGrpNot;
use Entity\Model\BibQstQ;
use Entity\Model\CampGrpNot;
use Entity\Model\CampLstNotCamp;
use Entity\Model\CampLstNotFour;
use Entity\Model\CampLstNotGrp;
use Entity\Model\CampNotex;
use Entity\Model\CampSoc;
use Entity\Model\CampQstQ;
use Entity\Model\CampQstTh;
use Entity\Model\Fourniss;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\ExportTo\Outils;
use Helpers\Fichier\Fichier;
use Helpers\Filter\FiltreAvance\Generator;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Pagination\Paginator;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\Trad;
use Modules\Evaluation\Repository\Rater;
use Modules\Evaluation\Service\CampaignService;
use PDO;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Skeleton\Controller\Controller;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;

class RaterController extends Controller
{
    /**
     * @var array<mixed>
     */
    protected array $droits = [];

    /**
     * init
     * gestion des droits
     *
     * @return void
     */
    public function init()
    {
        $droits = [
            'HA_MQUESCM' => Roles::droitsUtilisateur($this->pdo, 'HA_MQUESCM', $_SESSION["Session_Login"]), // Droit de création et modification des modèles et les catégories de modèles
            'HA_CEVAVIS' => Roles::droitsUtilisateur($this->pdo, 'HA_CEVAVIS', $_SESSION["Session_Login"]), // Droit de visu des campagnes
            'HA_CEVALCM' => Roles::droitsUtilisateur($this->pdo, 'HA_CEVALCM', $_SESSION["Session_Login"]), // Droit de création et modification des campagnes
            'HA_CEVASUP' => Roles::droitsUtilisateur($this->pdo, 'HA_CEVASUP', $_SESSION["Session_Login"]), // Droit de suppression des campagnes d'évaluation
            'HA_BIBQTCM' => Roles::droitsUtilisateur($this->pdo, 'HA_BIBQTCM', $_SESSION["Session_Login"]), // Droit de création et modification de questionnaire
        ];

        $this->droits = $droits;
    }

    /**
     * indexAction
     *
     * @return string
     */
    public function indexAction(): string
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $deleteMessageRater = $trad->t('Êtes-vous sûr(e) de vouloir supprimer le groupe @1@ ?');
        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        if ($mode == 'campaign') {
            $campGrpNot = new CampGrpNot($this->pdo);
            $groupsOfRaters = $campGrpNot->findAll(
                ['ID_CAMP' => $id],
                ['GROUPE']
            );
            $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
                ->campaignDetail(
                    $id,
                    $this->router,
                    $this->droits
                );

            (new PaginatorGestion())->generate(15, 'C.NOTEUR', 'ASC');

            $raters = (new Rater($this->pdo, $this->pdoStorage))->getRatersByCampaign($id, $post);

            $tmpGroups = (new CampLstNotGrp($this->pdo))->findAll(['ID_CAMP' => (int) $id]);
            $groups = [];
            foreach ($tmpGroups as $value) {
                $groups[$value['NOTEUR']][] = $value['GROUPE'];
            }

            $tmpSuppliers = (new CampLstNotFour($this->pdo))->findAll(['ID_CAMP' => (int) $id]);
            $suppliers = [];
            foreach ($tmpSuppliers as $value) {
                $suppliers[$value['NOTEUR']][] = $value['CODE_FOU'];
            }

            foreach ($raters as &$rater) {
                $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous supprimer l\'évaluateur @1@ ?'), $rater['NOM']);
                $rater['groups'] = $groups[$rater['NOTEUR']];
                $rater['suppliers'] = $suppliers[$rater['NOTEUR']];
            }

            ArianeSub::generate(
                0,
                2,
                $trad->t('Évaluateurs'),
                $this->router->generateUri(
                    'Evaluation.Rater.informations',
                    ['id' => $id, 'mode' => 'campaign']
                ),
                1
            );

            $infopagination = PaginatorGestion::getInfoPagination();

            return $this->renderer->render(
                '@Evaluation/Campaign/detail',
                [
                    'id'                    => $id,
                    'title'                 => $trad->t('Campagnes d\'évaluation'),
                    'menuActive'            => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'              => 'campaign',
                    'tab'                   => 'Raters/index',
                    'mode'                  => $mode,
                    'groupsOfRaters'        => $groupsOfRaters,
                    'campaign'              => $campaign,
                    'raters'                => $raters,
                    'droits'                => $this->droits,
                    'infoPagination'        => $infopagination,
                    'deleteMessage'         => $deleteMessage,
                    'deleteMessageRater'    => $deleteMessageRater,
                ]
            );
        } elseif ($mode == 'question') {
            Ariane::generate(0, $trad->t('Groupes d\'évaluateurs'));

            $bibGrpNot = new BibGrpNot($this->pdo);
            $groupsOfRaters = $bibGrpNot->fetchAll(
                ['GROUPE'],
                [],
                PDO::FETCH_ASSOC
            );

            $paginator = new Paginator();
            $pagingInfo = $paginator->generate($groupsOfRaters, 15, $post);

            $advancedFilter = new Generator($post);
            $advancedFilter->setFiltre('GROUPE', 'text', $trad->t('Libellé'));

            return $this->renderer->render(
                '@Evaluation/BilbliothequeDeQuestions/Raters/raters',
                [
                    'title'             => $trad->t('Groupes d\'évaluateurs pour la bibliothèque'),
                    'id'                => $id,
                    'pagingInfo'        => $pagingInfo,
                    'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'          => 'campaign',
                    'tab'               => 'Raters/index',
                    'mode'              => $mode,
                    'filtreAvance'      => $advancedFilter->getFiltres(),
                    'initFiltreAvance'  => $advancedFilter->getInit(),
                    'groupsOfRaters'    => $groupsOfRaters,
                    'deleteMessage'     => $deleteMessage,
                    'droits'            => $this->droits, //['BIB_QST_CM' => true], //$droits,
                    'post'              => $post,
                ]
            );
        } else {
            return '';
        }
    }

    public function informationsAction(): string
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $deleteMessageRater = $trad->t('Êtes-vous sûr(e) de vouloir supprimer le groupe @1@ ?');
        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        if ($mode == 'campaign') {
            $campGrpNot = new CampGrpNot($this->pdo);
            $groupsOfRaters = $campGrpNot->findAll(
                ['ID_CAMP' => $id],
                ['GROUPE']
            );
            $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
                ->campaignDetail(
                    $id,
                    $this->router,
                    $this->droits
                );

            ArianeSub::generate(
                0,
                2,
                $trad->t('Évaluateurs'),
                $this->router->generateUri(
                    'Evaluation.Rater.informations',
                    ['id' => $id, 'mode' => 'campaign']
                ),
                1
            );

            $companiesList = array_column(
                (new CampSoc($this->pdo))
                    ->findAll(
                        ['ID_CAMP' => $id],
                        ['CODE_STE']
                    ),
                'CODE_STE'
            );

            return $this->renderer->render(
                '@Evaluation/Campaign/detail',
                [
                    'id'                    => $id,
                    'title'                 => $trad->t('Campagnes d\'évaluation'),
                    'menuActive'            => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'              => 'campaign',
                    'tab'                   => 'Raters/informations',
                    'mode'                  => $mode,
                    'groupsOfRaters'        => $groupsOfRaters,
                    'campaign'              => $campaign,
                    'companiesList'         => $companiesList,
                    'droits'                => $this->droits,
                    'deleteMessage'         => $deleteMessage,
                    'deleteMessageRater'    => $deleteMessageRater,
                ]
            );
        } elseif ($mode == 'question') {
            Ariane::generate(0, $trad->t('Groupes d\'évaluateurs'));

            $bibGrpNot = new BibGrpNot($this->pdo);
            $groupsOfRaters = $bibGrpNot->fetchAll(
                ['GROUPE'],
                [],
                PDO::FETCH_ASSOC
            );

            $paginator = new Paginator();
            $pagingInfo = $paginator->generate($groupsOfRaters, 15, $post);

            $advancedFilter = new Generator($post);
            $advancedFilter->setFiltre('GROUPE', 'text', $trad->t('Libellé'));

            return $this->renderer->render(
                '@Evaluation/BilbliothequeDeQuestions/Raters/raters',
                [
                    'title'             => $trad->t('Groupes d\'évaluateurs pour la bibliothèque'),
                    'id'                => $id,
                    'pagingInfo'        => $pagingInfo,
                    'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'          => 'campaign',
                    'tab'               => 'Raters/index',
                    'mode'              => $mode,
                    'filtreAvance'      => $advancedFilter->getFiltres(),
                    'initFiltreAvance'  => $advancedFilter->getInit(),
                    'groupsOfRaters'    => $groupsOfRaters,
                    'deleteMessage'     => $deleteMessage,
                    'droits'            => $this->droits, //['BIB_QST_CM' => true], //$droits,
                    'post'              => $post,
                ]
            );
        } else {
            return '';
        }
    }

    /**
     * ratersTableAction
     *
     * @return string
     */
    public function ratersTableAction(): string
    {
        $trad = $this->getTranslationService();

        $id = (int)$this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody(true);

        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
            ->campaignDetail(
                $id,
                $this->router,
                $this->droits
            );

        if (isset($post['group'])) {
            $raterRepo = new Rater($this->pdo, $this->pdoStorage);
            $raters = $raterRepo->getRatersByGroupByCampaign($id, $post['group']);
            foreach ($raters as &$rater) {
                $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous retirer l\'évaluateur @1@ du groupe ?'), $rater['NOM']);
            }
            return $this->renderer->render(
                '@Evaluation/Campaign/Tabs/GroupOfRaters/raters_table_for_group',
                [
                    'raters'    => $raters,
                    'id'        => $id,
                    'mode'      => $mode,
                    'group'     => $post['group'],
                    'droits'    => $this->droits,
                    'campaign'  => $campaign,
                ]
            );
        } elseif (isset($post['supplier'])) {
            $raterRepo = new Rater($this->pdo, $this->pdoStorage);
            $raters = $raterRepo->getRatersBySupplierByCampaign($id, $post['supplier'], $post);
            foreach ($raters as &$rater) {
                $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous dissocier l\'évaluateur @1@ du fournisseur ?'), $rater['NOM']);
            }

            $tableTitle = $post['supplier'];

            return $this->renderer->render(
                '@Evaluation/Campaign/Tabs/Raters/raters_table_for_suppliers',
                [
                    'raters'        => $raters,
                    'id'            => $id,
                    'mode'          => $mode,
                    'supplier'      => $post['supplier'],
                    'tableTitle'    => $tableTitle,
                    'tableSubTitle' => '',
                    'droits'        => $this->droits,
                    'campaign'      => $campaign,
                ]
            );
        } else {
            $raterRepo = new Rater($this->pdo, $this->pdoStorage);
            $raters = $raterRepo->getRatersByCampaign($id);

            foreach ($raters as &$rater) {
                if ($rater['IN_GROUP'] == 'T') {
                    $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous supprimer l\'évaluateur @1@ ?'), $rater['NOM']);
                } else {
                    $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous supprimer l\'évaluateur @1@ ? (ce noteur fait partie d\'un groupe d\'évaluateurs)'), $rater['NOM']);
                }
            }

            $tableTitle = $post['group'];

            return $this->renderer->render(
                '@Evaluation/Campaign/Tabs/Raters/raters_table',
                [
                    'raters'        => $raters,
                    'id'            => $id,
                    'mode'          => $mode,
                    'group'         => $post['group'],
                    'tableTitle'    => $tableTitle,
                    'tableSubTitle' => '',
                    'droits'        => $this->droits,
                    'campaign'      => $campaign,
                ]
            );
        }
    }

    /**
     * editGroupOfRatersAction
     *
     * @return Response|string
     */
    public function editGroupOfRatersAction()
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $group = $this->request->getAttribute('group');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        $validator = $this->createValidator();

        if (\is_array($post) && \count($post) > 0) {
            switch ($mode) {
                case 'campaign':
                    $post['numerique_ID_CAMP'] = $id;
                    $validator->isStringAvecEspace(
                        $trad->t('Libellé'),
                        $post['GROUPE'],
                        1,
                        30
                    );
                    $campGrpNot = new CampGrpNot($this->pdo);
                    $groupAlreadyExists = $campGrpNot->find(
                        ['ID_CAMP' => $id, 'GROUPE' => $post['GROUPE']],
                        ['GROUPE'],
                        $post
                    );
                    if (!$groupAlreadyExists && $validator->isValid()) {
                        $campGrpNot->insert($post);
                        return new Response(
                            200,
                            [],
                            (string) \json_encode([
                                'statut' => 'O',
                                'path' => $this->router->generateUri(
                                    'Evaluation.Rater.informations',
                                    ['id' => $id, 'mode' => 'campaign']
                                ),
                            ])
                        );
                    } else {
                        return new Response(
                            200,
                            [],
                            (string) \json_encode([
                                'statut' => 'E',
                                'erreur' => $validator->getError()
                                    ? $validator->getError()
                                    : $trad->t('Le groupe existe déjà.'),
                            ])
                        );
                    }

                case 'question':
                    $validator->isStringAvecEspace(
                        $trad->t('Libellé'),
                        $post['GROUPE'],
                        1,
                        30
                    );
                    $bibGrpNot = new BibGrpNot($this->pdo);
                    $groupAlreadyExists = $bibGrpNot->find(
                        ['GROUPE' => $post['GROUPE']],
                        ['GROUPE'],
                    );
                    if (!$groupAlreadyExists && $validator->isValid()) {
                        $bibGrpNot->insert($post);
                        return new Response(
                            200,
                            [],
                            (string) \json_encode([
                                'statut' => 'O',
                                'path' => $this->router->generateUri(
                                    'Evaluation.Rater.informations',
                                    ['id' => $id, 'mode' => $mode]
                                ),
                            ])
                        );
                    } else {
                        return new Response(
                            200,
                            [],
                            (string) \json_encode([
                                'statut' => 'E',
                                'erreur' => $validator->getError()
                                    ? $validator->getError()
                                    : $trad->t('Le groupe existe déjà.'),
                            ])
                        );
                    }

                default:
                    return '';
            }
        } else {
            switch ($mode) {
                case 'campaign':
                    ArianeSub::generate(
                        1,
                        0,
                        $trad->t('Nouveau groupe d\'évaluateurs'),
                        $this->router->generateUri(
                            'Evaluation.Rater.editGroupOfRaters',
                            ['mode' => $mode, 'id' => $id]
                        ),
                        1
                    );
                    $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

                    return $this->renderer->render(
                        '@Evaluation/Campaign/detail',
                        [
                            'menuActive'    => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                            'menuLeft'      => 'campagne',
                            'tab'           => 'Raters/new',
                            'mode'          => $mode,
                            'id'            => $id,
                            'droits'        => $this->droits,
                            'deleteMessage' => $deleteMessage,
                        ]
                    );

                case 'question':
                    Ariane::generate(2, $trad->t('Nouveau groupe d\'évaluateurs'));
                    return $this->renderer->render(
                        '@Evaluation/BilbliothequeDeQuestions/Raters/edit',
                        [
                            'menuActive'    => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                            'mode'          => $mode,
                            'group'         => $group,
                            'id'            => $id,
                            'droits'        => $this->droits, //['HA_MQUESCM' => true], //$droits,
                        ]
                    );

                default:
                    return '';
            }
        }
    }

    /**
     * deleteGroupOfRatersAction
     *
     * @return Response
     */
    public function deleteGroupOfRatersAction()
    {
        $mode = $this->request->getAttribute('mode');
        $group = $this->request->getAttribute('group');

        $bibGrpNot = new BibGrpNot($this->pdo);
        $bibQstQ = new BibQstQ($this->pdo);

        switch ($mode) {
            case 'campaign':
                return new Response();

            case 'question':
                $groupIsUsedByQuestion = $bibQstQ->find([
                    'PROFNOTEUR2' => $group,
                ]);
                if (count($groupIsUsedByQuestion) < 1) {
                    $bibGrpNot->delete([
                        'GROUPE' => $group,
                    ]);
                    return new Response();
                } else {
                    return new Response(
                        200,
                        [],
                        (string) \json_encode([
                            'statut'    => 'E',
                            'result'    => 'le groupe est déjà utilisé sur une question',
                        ])
                    );
                }

            default:
                return new Response();
        }
    }

    public function ratersListForGroupAction(): string
    {
        $id     = $this->request->getAttribute('id');
        $mode   = $this->request->getAttribute('mode');
        $group   = $this->request->getAttribute('group');
        $post   = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
                ->campaignDetail(
                    $id,
                    $this->router,
                    $this->droits
                );

        $paginatorManagement = new PaginatorGestion();
        $paginatorManagement->generate(15, 'CODE', 'ASC');

        $originsList = [
            ''      => $trad->t('Tous'),
            'I'     => $trad->t('Interne'),
            'E'     => $trad->t('Externe')
        ];

        $raterRepo = new Rater($this->pdo, $this->pdoStorage);
        $raters = $raterRepo->getCampaignRatersForGroup($id, $group, $post);
        
        ArianeSub::generate(
            1,
            0,
            Trad::strBuild($trad->t('Nouveau(x) évaluateur(s) pour le groupe @1@'), $group),
            $this->router->generateUri(
                'Evaluation.Rater.ratersListForGroup',
                ['mode' => $mode, 'id' => $id, 'group' => $group]
            ),
            1
        );

        $tabTitle = Trad::strBuild($trad->t('Nouveau(x) évaluateur(s) pour le groupe @1@'), $group);

        $infopagination = PaginatorGestion::getInfoPagination();
        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        return $this->renderer->render(
            '@Evaluation/Campaign/Tabs/Raters/list_of_raters_for_groups',
            [
                'infoPagination'    => $infopagination,
                'campaign'          => $campaign,
                'tabTitle'          => $tabTitle,
                'raters'            => $raters,
                'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                'menuLeft'          => 'campagne',
                'mode'              => $mode,
                'group'             => $group,
                'id'                => $id,
                'droits'            => $this->droits,
                'post'              => $post,
                'origin'            => 'groups',
                'originsList'       => $originsList,
                'deleteMessage'     => $deleteMessage,
            ]
        );
    }

    public function ratersListForCampaignAction(): string
    {
        $id     = $this->request->getAttribute('id');
        $mode   = $this->request->getAttribute('mode');
        $group   = $this->request->getAttribute('group');
        $origin   = $this->request->getAttribute('origin');
        $post   = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $raterRepo = new Rater($this->pdo, $this->pdoStorage);
        $paginatorManagement = new PaginatorGestion();
        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
            ->campaignDetail(
                $id,
                $this->router,
                $this->droits
            );

        if ($origin == 'internal') {
            $paginatorManagement->generate(15, 'H.CODE', 'ASC');

            $raters = $raterRepo->getRatersNotInCampaign($id, $post);
            $tabTitle = $trad->t('Ajout d\'évaluateurs internes');

            ArianeSub::generate(
                1,
                0,
                $trad->t('Nouvel évaluateur pour campagne'),
                $this->router->generateUri(
                    'Evaluation.Rater.ratersListForCampaign',
                    ['mode' => $mode, 'id' => $id, 'origin' => $origin]
                ),
                1
            );

            $infopagination = PaginatorGestion::getInfoPagination();
            $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

            return $this->renderer->render(
                '@Evaluation/Campaign/Tabs/Raters/list_of_raters',
                [
                    'infoPagination'    => $infopagination,
                    'campaign'          => $campaign,
                    'tabTitle'          => $tabTitle,
                    'raters'            => $raters,
                    'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'          => 'campagne',
                    'tab'               => 'Raters/list_of_raters',
                    'mode'              => $mode,
                    'group'             => $group,
                    'id'                => $id,
                    'droits'            => $this->droits, //['HA_MQUESCM' => true], //$droits,
                    'post'              => $post,
                    'origin'            => $origin,
                    'deleteMessage'     => $deleteMessage,
                ]
            );
        } else {
            $paginatorManagement->generate(15, 'E.ID_NOTEUR', 'DESC');

            $raters = $raterRepo->getExternalRatersNotInCampaign($id, $post);
            $tabTitle = $trad->t('Ajout d\'évaluateurs externes');


            ArianeSub::generate(
                1,
                0,
                $trad->t('Nouveau(x) évaluateur(s) externe(s) pour campagne'),
                $this->router->generateUri(
                    'Evaluation.Rater.ratersListForCampaign',
                    ['mode' => $mode, 'id' => $id]
                ),
                1
            );
            $infopagination = PaginatorGestion::getInfoPagination();
            $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

            return $this->renderer->render(
                '@Evaluation/Campaign/Tabs/Raters/list_of_external_raters',
                [
                    'infoPagination'    => $infopagination,
                    'campaign'          => $campaign,
                    'tabTitle'          => $tabTitle,
                    'raters'            => $raters,
                    'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                    'menuLeft'          => 'campagne',
                    'tab'               => 'Raters/list_of_external_raters',
                    'mode'              => $mode,
                    'group'             => $group,
                    'id'                => $id,
                    'droits'            => $this->droits, //['HA_MQUESCM' => true], //$droits,
                    'post'              => $post,
                    'origin'            => $origin,
                    'deleteMessage'     => $deleteMessage,
                ]
            );
        }
    }
    
    /**
     * ratersListForSupplierAction
     *
     * @return string
     */
    public function ratersListForSupplierAction()
    {
        $id         = $this->request->getAttribute('id');
        $mode       = $this->request->getAttribute('mode');
        $supplier   = $this->request->getAttribute('supplier');
        $post       = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
            ->campaignDetail(
                $id,
                $this->router,
                $this->droits
            );
        $fourniss = new Fourniss($this->pdo);
        $supplier = $fourniss->find(['CODE' => $supplier]);

        $paginatorManagement = new PaginatorGestion();
        $paginatorManagement->generate(15, 'CODE', 'ASC');

        $raterRepo = new Rater($this->pdo, $this->pdoStorage);
        $raters = $raterRepo->getCampaignRatersForSupplier($id, $supplier['CODE'], $post);

        ArianeSub::generate(
            1,
            0,
            Trad::strBuild($trad->t('Nouveau(x) évaluateur(s) pour le fournisseur @1@'), $supplier['RS']),
            $this->router->generateUri(
                'Evaluation.Rater.ratersListForSupplier',
                ['mode' => $mode, 'id' => $id, 'supplier' => $supplier]
            ),
            1
        );

        $tabTitle = Trad::strBuild($trad->t('Nouveau(x) évaluateur(s) pour le fournisseur @1@'), $supplier['RS']);

        $infopagination = PaginatorGestion::getInfoPagination();
        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        return $this->renderer->render(
            '@Evaluation/Campaign/Tabs/Raters/list_of_raters_for_suppliers',
            [
                'infoPagination'    => $infopagination,
                'campaign'          => $campaign,
                'tabTitle'          => $tabTitle,
                'raters'            => $raters,
                'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                'menuLeft'          => 'campagne',
                'mode'              => $mode,
                'supplier'          => $supplier,
                'id'                => $id,
                'droits'            => $this->droits, //['HA_MQUESCM' => true], //$droits,
                'post'              => $post,
                'origin'            => 'suppliers',
                'deleteMessage'     => $deleteMessage,
            ]
        );
    }

    /**
     * addRaterToGroupAction
     *
     * @return string|Response
     */
    public function addRaterToGroupAction()
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $group = $this->request->getAttribute('group');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $raterRepo = new Rater($this->pdo, $this->pdoStorage);
        $error = true;
        $raters = [];
        foreach ($post as $key => $value) {
            if (\strpos($key, 'save_selected_rater_') !== false) {
                $error = false;
                // TODO MCH ajouter interne ou externe dans le tableau pour l'insert
                $raters[\substr($key, 20)] = 0x54;
            }
        }

        if ($error == true) {
            return new Response(200, [], (string) \json_encode([
                'status' => 'E',
                'error'  => $trad->t('Veuillez sélectionner au moins un évaluateur.'),
            ]));
        } else {
            $raterRepo->addRaterToGroup($id, $mode, $group, $raters);
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        }
    }

    public function addRaterToCampaignAction(): string
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
            ->campaignDetail(
                $id,
                $this->router,
                $this->droits
            );

        ArianeSub::generate(
            1,
            0,
            $trad->t('Nouvel évaluateur pour campagne'),
            $this->router->generateUri(
                'Evaluation.Rater.addRaterToCampaign',
                ['mode' => $mode, 'id' => $id]
            ),
            1
        );

        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        return $this->renderer->render(
            '@Evaluation/Campaign/detail',
            [
                'campaign'        => $campaign,
                'menuActive'      => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                'menuLeft'        => 'campagne',
                'tab'             => 'Raters/list_of_raters',
                'mode'            => $mode,
                'group'           => $post['group'],
                'id'              => $id,
                'droits'          => $this->droits,
                'deleteMessage'   => $deleteMessage,
            ]
        );
    }

    /**
     * chooseOriginOfRaterAction
     *
     * @return string
     */
    public function chooseOriginOfRaterAction()
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $group = $this->request->getAttribute('group');

        return $this->renderer->render(
            '@Evaluation/Campaign/Tabs/Raters/popup_origin_of_raters',
            [
                'id' => $id,
                'mode' => $mode,
                'group' => $group,
                'menuActive' => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                'menuLeft' => 'campagne',
            ]
        );
    }

    /**
     * newExternalRaterAction
     *
     * @return string
     */
    public function newExternalRaterAction()
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $group = $this->request->getAttribute('group');

        $trad = $this->getTranslationService();

        $campaign = (new CampaignService($this->pdo, $this->getTranslationService()))
            ->campaignDetail(
                $id,
                $this->router,
                $this->droits
            );

        ArianeSub::generate(
            1,
            0,
            $trad->t('Nouvel évaluateur externe'),
            $this->router->generateUri(
                'Evaluation.Rater.newExternalRater',
                ['mode' => $mode, 'id' => $id]
            ),
            1
        );

        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        return $this->renderer->render(
            '@Evaluation/Campaign/Tabs/Raters/new_external_rater',
            [
                'id'            => $id,
                'mode'          => $mode,
                'group'         => $group,
                'menuActive'    => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
                'menuLeft'      => 'campagne',
                'campaign'      => $campaign,
                'tabTitle'      => $trad->t('Nouvel évaluateur externe'),
                'deleteMessage' => $deleteMessage,
            ]
        );
    }

    /**
     * validateNewRatersAction
     *
     * @return string|Response
     */
    public function validateNewRatersAction()
    {
        $id         = $this->request->getAttribute('id');
        $mode       = $this->request->getAttribute('mode');
        $origin     = $this->request->getAttribute('origin');
        $group      = $this->request->getAttribute('group');
        $post       = $this->request->getParsedBody();

        $raterRepo = new Rater($this->pdo, $this->pdoStorage);
        $campNotex = new CampNotex($this->pdo);
        $validator = $this->createValidator();
        $roles = new Roles;

        $trad = $this->getTranslationService();
        $raters = [];

        if ($origin != 'new_external') {
            if ($post['selectedCount'] == 0) {
                return new Response(200, [], (string) \json_encode([
                    'status' => 'E',
                    'error'  => $trad->t('la sélection ne peut pas être vide'),
                ]));
            }

            foreach (array_keys($post) as $key) {
                if (strpos($key, 'save_selected_rater_') === 0) {
                    $raters[] = str_replace('OxapointOxa', '.', $post[$key]);
                }
            }
        }
        
        if ($origin == 'internal') {
            $raterRepo->addRatersToCampaign($id, $raters, 'internal');
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        } elseif ($origin == 'external') {
            $raterRepo->addRatersToCampaign($id, $raters, 'external');
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        } elseif ($origin == 'groups') {
            $raterRepo->addRatersToGroup($id, $group, $raters);
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        } elseif ($origin == 'suppliers') {
            $supplier = $group;
            $raterRepo->addRatersToSupplier($id, $supplier, $raters);
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        } else {
            $validator->isStringAvecEspace($trad->t('Nom'), $post['NAME'], 1, 30);
            $validator->isStringAvecEspace($trad->t('Prénom'), $post['SURNAME'], 1, 30);
            $validator->adresseMail($trad->t('Email'), $post['EMAIL'], 1, 100);
            $validator->isStringAvecEspace($trad->t('Société'), $post['COMPANY'], 1, 30);
            $validator->isStringAvecEspace($trad->t('Fonction'), $post['OFFICE'], 0, 50);

            if ($validator->isValid()) {
                $raterId = Sql::guidGenerate();

                $nameSetting = $roles::droit($this->pdo, 'ORDRE_NOM_PRENOM', 'OXAPROC', true);
                if ($nameSetting == 1) {
                    $raterName = $post['SURNAME'] . ' ' . $post['NAME'];
                } else {
                    $raterName = $post['NAME'] . ' ' . $post['SURNAME'];
                }
                $insert = [
                    'ID_NOTEUR'     => $raterId,
                    'NOM_NOTEUR'    => $raterName,
                    'FCT_NOTEUR'    => $post['OFFICE'],
                    'EMAIL_NOTEUR'  => $post['EMAIL'],
                    'SOC_NOTEUR'    => $post['COMPANY'],
                    'CREATEUR'      => $_SESSION['Session_Login'],
                    'DTE_CREAT'     => \date('Ymd'),
                ];
                $campNotex->insert($insert);
                return new Response(443, [], (string) \json_encode([
                    'path' => $this->router->generateUri('Evaluation.Rater.ratersListForCampaign', ['mode' => $mode, 'id' => $id, 'origin' => $origin])
                ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        }
    }

    /**
     * removeRaterFromCampaignAction
     *
     * @return Response
     */
    public function removeRaterFromCampaignAction()
    {
        $id     = $this->request->getAttribute('id');
        $rater = $this->request->getAttribute('rater');
        $mode = $this->request->getAttribute('mode');

        $trad = $this->getTranslationService();

        $campLstNotCamp = new CampLstNotCamp($this->pdo);
        $campLstNotGrp = new CampLstNotGrp($this->pdo);
        $campLstNotFour = new CampLstNotFour($this->pdo);
        $fourniss = new Fourniss($this->pdo);
        $campQstQ = new CampQstQ($this->pdo);
        $campQstTh = new CampQstTh($this->pdo);

        $raterIsUsedByQuestion = $campQstQ->find([
            'PROFNOTEUR2'   => $rater,
            'ID_CAMP'       => $id,
        ]);

        $raterIsUsedByGroup = $campLstNotGrp->find([
            'ID_CAMP'   => $id,
            'NOTEUR'    => $rater,
        ], [
            'GROUPE'
        ]);

        $raterIsUsedBySupplier = $campLstNotFour->find([
            'ID_CAMP'   => $id,
            'NOTEUR'    => $rater,
        ], [
            'CODE_FOU',
        ]);

        $message = '';
        if ($raterIsUsedByQuestion) {
            $questionTheme = $campQstTh->find([
                'ID_THEME'  => $raterIsUsedByQuestion['ID_THEME'],
                'ID_CAMP'   => $id
            ], ['LIB_THEME'], [], PDO::FETCH_ASSOC);
            $message .= '</br></br><b>' . $trad->t('Cet évaluateur est lié à une question du questionnaire') . ' :</b></br></br>"' . $raterIsUsedByQuestion['LIB_QUEST'] . '" (' . $questionTheme['LIB_THEME'] . ')';
        }

        if ($raterIsUsedByGroup) {
            $message .= '</br></br><b>' . $trad->t('Cet évaluateur est lié à un groupe de la campagne') . ' :</b></br></br>"' . $raterIsUsedByGroup['GROUPE'] . '"';
        }

        if ($raterIsUsedBySupplier) {
            $supplier = $fourniss->find([
                'CODE'  => $raterIsUsedBySupplier['CODE_FOU']
            ], [
                'RS'
            ]);

            $message .= '</br></br><b>' . $trad->t('Cet évaluateur est lié à un fournisseur de la campagne') . ' :</b></br></br>"' . $supplier['RS'] . '"';
        }

        if ($message == '') {
            $campLstNotCamp->delete([
                'ID_CAMP'   => $id,
                'NOTEUR'    => $rater,
            ]);
            $campLstNotGrp->delete([
                'ID_CAMP'   => $id,
                'NOTEUR'    => $rater,
            ]);
            return new Response(200, [], (string) \json_encode([
                'path' => $this->router->generateUri('Evaluation.Rater.index', ['mode' => $mode, 'id' => $id])
            ]));
        } else {
            $message .= '</br></br>' . $trad->t('Voulez-vous supprimer l\'évaluateur malgré tout ?');
            return new Response(
                443,
                [],
                $this->renderer->render('@popup-erreur/confirmationSuppresion', [
                    'message'   => $message,
                    'div'       => 'redirect',
                    'pathURL'   => $this->router->generateUri('Evaluation.Rater.confirmedRaterRemoval', ['mode' => $mode, 'rater' => $rater, 'id' => $id]),
                ])
            );
        }
    }
    
    /**
     * confirmedRaterRemovalAction
     *
     * @return Response
     */
    public function confirmedRaterRemovalAction()
    {
        $id     = $this->request->getAttribute('id');
        $rater = $this->request->getAttribute('rater');
        $mode = $this->request->getAttribute('mode');

        $campLstNotCamp = new CampLstNotCamp($this->pdo);
        $campLstNotGrp = new CampLstNotGrp($this->pdo);

        $campLstNotCamp->delete([
            'ID_CAMP'   => $id,
            'NOTEUR'    => $rater,
        ]);
        $campLstNotGrp->delete([
            'ID_CAMP'   => $id,
            'NOTEUR'    => $rater,
        ]);
        return new Response(200, [], (string) \json_encode([
            'path' => $this->router->generateUri('Evaluation.Rater.index', ['mode' => $mode, 'id' => $id])
        ]));
    }

    /**
     * removeRaterFromGroupAction
     *
     * @return Response
     */
    public function removeRaterFromGroupAction()
    {
        $id     = $this->request->getAttribute('id');
        $group  = $this->request->getAttribute('group');
        $rater  = $this->request->getAttribute('rater');
        $mode  = $this->request->getAttribute('mode');

        $campLstNotgrp = new CampLstNotGrp($this->pdo);
        $campLstNotgrp->delete([
            'ID_CAMP'   => $id,
            'GROUPE'    => $group,
            'NOTEUR'    => $rater,
        ]);

        // return $this->redirect('Evaluation.GroupOfRaters.index', ['mode' => $mode, 'id' => $id], ['group' => $group]);
        return new Response(200, [], (string) \json_encode([
            'path' => $this->router->generateUri('Evaluation.GroupOfRaters.index', ['mode' => $mode, 'id' => $id]),
            'post' => ['group' => $group]
        ]));
    }
    /**
     * exportAction
     *
     * @return string
     */
    public function exportAction()
    {
        $bibGrpNot = new BibGrpNot($this->pdo);
        $groupsList = $bibGrpNot->fetchAll(['GROUPE'], [], PDO::FETCH_ASSOC);

        // Récupération des formats des champs
        $fieldList = $bibGrpNot->getArchitecture($this->getTranslationService());

        // On génère l'entête du fichier d'export
        $tab = [];
        foreach ($fieldList as $key => $field) {
            $tab[\substr($bibGrpNot->table, 0, 11) . '.' . $key] = $field['nomChamp'];
        }

        Outils::gestionEmailAsync2(
            "export_liste_groupes",
            $groupsList,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );
        return 'ok';
    }

    /**
     * importIndexAction
     *
     * @return string
     */
    public function importIndexAction()
    {
        $trad = $this->getTranslationService();

        Ariane::generate(2, $trad->t('Import groupes'));

        return $this->renderer->render('@Evaluation/BilbliothequeDeQuestions/Raters/import', [
            'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
            'menuLeft'          => 'category',
            'title'             => $trad->t('Gestion groupes d\'évaluateurs'),
            ]);
    }

    /**
     * importAction
     *
     * @return string|Response
     */
    public function importAction()
    {
        $trad = $this->getTranslationService();

        $file = $this->request->getUploadedFiles();

        if ($file) {
            $filename = $file['importFile']->getClientFilename();
            $fileSize = $file['importFile']->getSize();
        } else {
            $filename = null;
            $fileSize = 0;
        }

        $validator = $this->createValidator();
        $validator->fileCheck($trad->t('Fichier d\'import'), $filename ?? '', ['xsl', 'xlsx', 'csv'], '', $fileSize);

        if ($validator->isValid()) {
            // on enregistre le fichier d'import dans les fichiers temporaires
            $newPath = Fichier::UploadDocAtt($filename);
            $file['importFile']->moveTo($newPath["racine"] . $newPath["new_name"]);
            $newName = $newPath["racine"] . $newPath["new_name"];

            // on récupère les valeurs des colonnes qui nous intéressent
            $spreadsheet = IOFactory::load($newName);
            $sheet = $spreadsheet->getSheet(0);
            $totalRows = $sheet->getHighestRow();

            $arrayImport = [];
            $i = 1;
            foreach ($sheet->getRowIterator(2, $totalRows) as $row) {
                foreach ($row->getCellIterator('A', 'A') as $cell) {
                    $value = $cell->getCalculatedValue();
                    $arrayImport[$i] = $value;
                }
                $i++;
            }

            // on vérifie les groupes reçus et on retourne le compte de groupes OK et la liste des catégories qui étaient déjà enregistrées
            $raterRepo = new Rater($this->pdo, $this->pdoStorage);
            $import = $raterRepo->groupImport($arrayImport);
            $existingGroups = $import['existingGroups'] ?? [];
            $totalImportedGroups = $import['count'];

            // import par lot de 500 fournisseurs (append dans un fichier pour les logs)
            // faire un helper pour l'insert table temp
            // gérer l'entity dans le helper

            return new Response(200, [], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('Evaluation.Rater.importSummary'),
                'postGestion' => [
                    'existingGroups'         => $existingGroups,
                    'totalImportedGroups'    => $totalImportedGroups,
                ],
            ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }

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

        $trad = $this->getTranslationService();

        $existingGroups = $post['existingGroups'];
        $totalImportedGroups = $post['totalImportedGroups'];

        if ($totalImportedGroups > 0) {
            $message = Trad::strBuild($trad->t('Nombre de groupes importés depuis le fichier : @1@'), $totalImportedGroups);
        } else {
            $message = $trad->t('Aucun groupe n\'a été importé.');
        }

        Ariane::generate(1, $trad->t('Récapitulatif import'));

        return $this->renderer->render('@Evaluation/BilbliothequeDeQuestions/Raters/summary', [
            'menuActive'                    => Session::verifySessionTypeMenuTop(MenuTopEnum::S2C) ? 'Consultations' : 'Evaluations',
            'menuLeft'                      => 'categorie',
            'existingGroups'                => $existingGroups ?? [],
            'message'                       => $message,
            ]);
    }
}
