<?php

namespace Modules\Evaluation\Controller;

use Entity\Model\CampLstNotFour;
use Entity\Model\Fourniss;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\ArianeSub;
use Helpers\Outil\Roles;
use Helpers\Trad\Trad;
use Modules\Evaluation\Repository\Campaign;
use Modules\Evaluation\Repository\Rater;
use Modules\Evaluation\Service\CampaignService;
use Skeleton\Controller\Controller;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;

class RatersBySupplierController 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|Response
     */
    public function indexAction()
    {
        $id = $this->request->getAttribute('id');
        $mode = $this->request->getAttribute('mode');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $suppliers = (new Campaign($this->pdo))
            ->campaignSupplierList($id);

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

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

        $chosenName = '';

        // on récupère la raison sociale du fournisseur quand le post est alimenté (pour afficher le fournisseur sélectionné lors de la suppression d'un évaluateur)
        if ($post) {
            $supplierRepo = new Fourniss($this->pdo);
            $chosenName = $supplierRepo->find([
                'CODE'  => $post['supplier']
            ], ['RS'])['RS'];
        }

        $raters = (new Rater($this->pdo, $this->pdoStorage))->getRatersBySupplierByCampaign($id, '', $post);
        foreach ($raters as &$rater) {
            $rater['deleteMessage'] = Trad::strBuild($trad->t('Voulez-vous dissocier l\'évaluateur @1@ du fournisseur ?'), $rater['NOM']);
        }

        $ratersBySupplier = [];
        foreach ($raters as $supplierRater) {
            $ratersBySupplier[$supplierRater['CODE_FOU']][] = $supplierRater;
        }

        foreach ($suppliers as &$supplier) {
            $supplier['raters'] = $ratersBySupplier[$supplier['CODE_FOU']];
        }

        $tableTitle = $trad->t('Gérez vos évaluateurs par fournisseurs');
        $tableSubTitle = $trad->t('Sélectionnez un fournisseur puis utilisez le bouton "+" pour ajouter des évaluateurs aux fournisseurs de la campagne');
        $deleteMessage = $trad->t('Voulez-vous supprimer la campagne @1@ ?');

        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'               => 'RatersBySupplier/index',
                'mode'              => $mode,
                'suppliers'         => $suppliers,
                'campaign'          => $campaign,
                'tableTitle'        => $chosenName ?: $tableTitle,
                'tableSubTitle'     => $tableSubTitle,
                'droits'            => $this->droits, //['HA_MQUESCM' => true], //$droits,
                'chosenSupplier'    => $post['supplier'] ?? false,
                'chosenName'        => $chosenName,
                'deleteMessage'     => $deleteMessage,
            ]
        );
    }
    
    /**
     * addRaterToSupplierAction
     *
     * @return Response
     */
    public function addRaterToSupplierAction()
    {
        $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 noteur.'),
            ]));
        } else {
            $raterRepo->addRaterToGroup($id, $mode, $group, $raters);
            return new Response(200, [], (string) \json_encode([
                'status' => 'O',
            ]));
        }
    }
    
    /**
     * removeRaterFromSupplierAction
     *
     * @return Response
     */
    public function removeRaterFromSupplierAction()
    {
        $id         = $this->request->getAttribute('id');
        $supplier   = $this->request->getAttribute('supplier');
        $rater      = str_replace('OxapointOxa', '.', $this->request->getAttribute('rater'));
        $mode       = $this->request->getAttribute('mode');

        $campLstNotFour = new CampLstNotFour($this->pdo);
        $campLstNotFour->delete([
            'ID_CAMP'   => $id,
            'CODE_FOU'  => $supplier,
            'NOTEUR'    => $rater,
        ]);

        return new Response(200, [], (string) \json_encode([
            'path' => $this->router->generateUri('Evaluation.RatersBySupplier.index', ['mode' => $mode, 'id' => $id]),
            'post' => ['supplier' => $supplier]
        ]));
    }
}
