<?php
namespace Modules\EtatStatistiques\Controller;

use Entity\Model\FentFiltEnt;
use Entity\Model\FlisFiltListe;
use Entity\Model\ReqFiltres;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Sql;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\Trad;
use Modules\EtatStatistiques\Repository\EtatStatTypeRepo;
use Modules\EtatStatistiques\Service\FiltreUtilForm;
use Skeleton\Controller\Controller;

class GestionFiltreUtilController extends Controller
{
    public function indexAction() :string
    {
        $post = $this->request->getParsedBody();
        
        (new PaginatorGestion())->generate(10, 'FENT_CODE_FILTRE', 'ASC');

        $list = (new FentFiltEnt($this->pdo))->findAll(null, [], $post);
        $pagination = (PaginatorGestion::getInfoPagination() ?? []);
        
        return $this->renderer->render('@EtatStatistiques/FiltreUtil/gestion', [
            'post' => $post,
            'listRow' => array_map(function ($item) {
                return $item + [
                    'menu' => $this->createMenuCont($item),
                ];
            }, $list),
            'pagination' =>
                $pagination
                + ['path' => $this->router->generateUri(
                    $this->router->getNameRoute(),
                    $this->request->getAttributes()
                )]
        ]);
    }

    public function formCreateAction() :string
    {
        return $this->renderer->render('@EtatStatistiques/FiltreUtil/formCreate', [
            'post' => $this->request->getParsedBody(),
            'form' => $this->getFormCreate(),
        ]);
    }
    
    public function createAction() :Response
    {
        $id = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();
        $qbFiltre = new FentFiltEnt($this->pdo);
        $trad = $this->getTranslationService();

        $validator = $this->createFormValidator();
        
        $duplicate = $qbFiltre->find($post['FENT_CODE_FILTRE']);
        if (! empty($duplicate)) {
            $validator->setError(
                $trad->t('Ce code existe déjà.')
            );
        }
        
        $post = $validator->validateForm($this->getFormCreate(), $post);
        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //___________________________

        (new EtatStatTypeRepo($this->pdo))->persistFiltreUtil($post);

        return new Response(200);
    }

    public function formUpdateAction() :string
    {
        $id = $this->request->getAttribute('id');
        return $this->renderer->render('@EtatStatistiques/FiltreUtil/formUpdate', [
            'post' => $this->request->getParsedBody(),
            'form' => $this->getFormUpdate(),
            'subject' =>
                ($fent = (new FentFiltEnt($this->pdo))->find($id))
                + [
                    'ReqLibre' => Sql::getMemo($this->pdo, $fent['FENT_NM_REQ_LIB']),
                    // 'Where' => Sql::getMemo($this->pdo, $fent['FENT_NM_WHERE']),
                    'ListChoix' => (new FlisFiltListe($this->pdo))->findAll([
                        'FLIS_CODE_FILTRE' =>  $fent['FENT_CODE_FILTRE'],
                    ], [], ['tri_FLIS_NO_ORDRE' => 'ASC']),
                ],
        ]);
    }
    
    public function updateAction() :Response
    {
        $id = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();
        $qbFiltre = new FentFiltEnt($this->pdo);

        $filtre = $qbFiltre->find($id);
        if (empty($filtre)) {
            return $this->create404Response();
        }

        //___________________________
        
        $validator = $this->createFormValidator();
        $post = $validator->validateForm(
            $this->getFormUpdate(),
            $post
        );
        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //___________________________

        $post['FENT_CODE_FILTRE'] = $filtre['FENT_CODE_FILTRE'];
        (new EtatStatTypeRepo($this->pdo))->persistFiltreUtil($post);

        return new Response(200);
    }

    public function deleteAction() :Response
    {
        // TODO : force post
        $id = $this->request->getAttribute('id');



        if ($list = (new ReqFiltres($this->pdo))->findAll([
            'CODE_FILTRE' => $id,
            'TYPE_FILTRE' => 'USER',
        ])) {
            $trad = $this->getTranslationService();
            return new Response(400, [], Trad::strBuild(
                $trad->t('Ce filtre ne peut être supprimé car il est utilisé par le(s) état(s) suivant : @1@'),
                implode(', ', array_column($list, 'REQ_ETAT'))
            ));
        }

        $this->pdo->beginTransaction();

        (new FentFiltEnt($this->pdo))->delete($id);
        (new FlisFiltListe($this->pdo))->delete([
            'FLIS_CODE_FILTRE' => $id,
        ]);
        // TODO : delete children

        $this->pdo->commit();

        return new Response(200);
    }

//______________________________________________________________________________
// Sub-routine
    

    /**
     * @param array<mixed> $filtre
     * @return array<mixed>
     */
    private function createMenuCont(array $filtre)
    {
        $trad = $this->getTranslationService();
        $id = $filtre['FENT_CODE_FILTRE'];
        return [
            'listeSecondaire' => [
                [
                    'libelle' => $trad->t('Modifier'),
                    'route' => 'EtatStatistique.FiltreUtil.formUpdate',
                    'routeParam' => ['id' => $id],
                ],
                [
                    'libelle' => $trad->t('Supprimer'),
                    'lienJs' =>
                        'popupConfirmSimple('
                        . implode(',', [
                            json_encode($trad->t('Confirmation')),
                            json_encode(Trad::strBuild(
                                $trad->t('Êtes-vous sûr de vouloir supprimer le type de filtre @1@ (@2@)'),
                                $filtre['FENT_LIB_FILTRE'],
                                $filtre['FENT_CODE_FILTRE']
                            )),
                            json_encode($this->router->generateUri(
                                'EtatStatistique.FiltreUtil.delete',
                                ['id' => $id]
                            )),
                            '{}',
                            '() => {window.action.arianeReload()}'
                        ])
                        . ')',
                ],
            ],
        ];
    }

    /**
     * @return \stdClass[]
     */
    private function getFormCreate()
    {
        $trad = $this->getTranslationService();
        return (new FiltreUtilForm($trad))->buildWithView($trad);
    }

    /**
     * @return \stdClass[]
     */
    private function getFormUpdate()
    {
        $form = $this->getFormCreate();
        unset($form['FENT_CODE_FILTRE']);
        return $form;
    }
}
