<?php
namespace Modules\EtatStatistiques\Controller;

use Entity\Model\EtatThem;
use Entity\Model\Hastutil;
use GuzzleHttp\Psr7\Response;
use Helpers\Form\FormBuilder;
use Helpers\Pagination\PaginatorGestion;
use Modules\EtatStatistiques\Repository\EtatStatVisiRepo;
use Skeleton\Controller\Controller;

class GestionEtatVisiUtilController extends Controller
{
    private function getRepo() :EtatStatVisiRepo
    {
        return new EtatStatVisiRepo($this->pdo);
    }

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

        $list = $this->getRepo()->listUtil($post);
        $pagination = (PaginatorGestion::getInfoPagination() ?? []);
        
        return $this->renderer->render('@EtatStatistiques/Visi/gestion', [
            'post' => $post,
            'listRow' => $list,
            'pagination' =>
                $pagination
                + ['path' => $this->router->generateUri(
                    $this->router->getNameRoute(),
                    $this->request->getAttributes()
                )]
        ]);
    }

    public function formUpdateAction() :string
    {
        $id = $this->request->getAttribute('id');
        return $this->renderer->render('@EtatStatistiques/Visi/formUpdate', [
            'post' => $this->request->getParsedBody(),
            'form' => $this->getFormUpdate(),
            'subject' => $this->getRepo()->getDetail($id),
        ]);
    }
    
    public function updateAction() :Response
    {
        $id = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();

        $util = (new Hastutil($this->pdo))->find($id);
        if (empty($util)) {
            return $this->create404Response();
        }
        
        $validator = $this->createFormValidator();
        $post = $validator->validateForm(
            $this->getFormUpdate(),
            $post
        );
        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //___________________________

        $this->getRepo()->persist(['CODUSR' => $id] + $post);

        return new Response(200);
    }

//______________________________________________________________________________
// Sub-routine

    
    /**
     * @return \stdClass[]
     */
    private function getFormUpdate()
    {
        $trad = $this->getTranslationService();
        return (new FormBuilder())
            ->addMultipick('listGroupe', 'Ajax.liste.etatGroupe')
            ->addMultipick('listEtatstat', 'Ajax.liste.etatStat')
            ->build();
    }
}
