<?php

namespace Modules\Stock\Controller;

use Entity\Model\Srubcomp;
use Exception;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Modules\Stock\Enum\EmptyEnum;
use Modules\Stock\Helper\CodeHelper;
use Modules\Stock\Repository\RubriqueRepo;
use Modules\Stock\Trait\Controller\StockContollerTrait;
use Modules\Stock\Validator\RubriqueValidator;
use Skeleton\Controller\Controller;

class RubriqueController extends Controller
{
    use StockContollerTrait;

    /**
     * @throws Exception
     */
    public function gestionAction(): string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        Ariane::generate(0, $trad->t('Gestion'), [], null, $this->router->generateUri('Stock.Rubrique.gestion'));

        (new PaginatorGestion())->generate(20, 'CODE');
        $rubriques = (new RubriqueRepo($this->pdo))->listRubriques($post);
        $infoPagination = PaginatorGestion::getInfoPagination();

        return $this->renderer->render('@Stock/Rubrique/gestion', [
            'post'             => $post,
            'menuActive'       => 'Stock',
            'rubriques'        => $rubriques,
            'infoPagination'   => $infoPagination,
            'emptyParam'       => EmptyEnum::EMPTY_PARAM->value,
            'hasCreateEditAccessRights' => (bool) Roles::droitsUtilisateur($this->pdo, 'ST_RUB_CM')
        ]);
    }

    /**
     * @throws Exception
     */
    public function nouveauFormAction(): string
    {
        $trad = $this->getTranslationService();

        Ariane::generate(
            1,
            $trad->t('Création d\'une rubrique'),
            [],
            null,
            $this->router->generateUri('Stock.Rubrique.nouveauForm')
        );

        return $this->renderer->render('@Stock/Rubrique/nouveau_form');
    }

    /**
     * @throws Exception
     */
    public function nouveauAction(): Response
    {
        $post = $this->request->getParsedBody();

        $rubrique = $post['SRUBCOMP'];
        $validator = new RubriqueValidator($this->pdo, $this->getTranslationService());
        $validator->validateCode($rubrique)->validateLibelle($rubrique);

        if ($validator->isValid()) {
            $this->pdo->beginTransaction();
            (new Srubcomp($this->pdo))->merge($rubrique);
            $this->pdo->commit();

            return $this->createJsonResponse(['statut' => 'OK', 'redirectRoute' => $this->router->generateUri('Stock.Rubrique.gestion')]);
        } else {
            return $this->createBloquantJsonErrorResponse([], $validator->getError());
        }
    }

    /**
     * @throws Exception
     */
    public function modifierFormAction(): string|Response
    {
        $trad = $this->getTranslationService();

        $srubcomp = new Srubcomp($this->pdo);
        $code = CodeHelper::getCodeFromParam($this->request->getAttribute('code'));

        if (!$rubrique = $srubcomp->find(['CODE' => $code])) {
            return $this->createJsonResponse(['statut' => 'Not found', 'message' => 'Cette rubrique n\'existe pas'], 404);
        }

        Ariane::generate(
            1,
            $trad->t('Modification d\'une rubrique'),
            [],
            null,
            $this->router->generateUri('Stock.Rubrique.modifierForm')
        );

        return $this->renderer->render('@Stock/Rubrique/modifier_form', [
            'rubrique' => $rubrique
        ]);
    }

    /**
     * @throws Exception
     */
    public function modifierAction(): Response
    {
        $post = $this->request->getParsedBody();

        $srubcomp = new Srubcomp($this->pdo);
        $code = CodeHelper::getCodeFromParam($this->request->getAttribute('code'));

        if (!$rubrique = $srubcomp->find(['CODE' => $code])) {
            return $this->createJsonResponse(['statut' => 'Not found', 'message' => 'Cette rubrique n\'existe pas'], 404);
        }

        $rubrique = array_merge($rubrique, $post['SRUBCOMP']);
        $validator = new RubriqueValidator($this->pdo, $this->getTranslationService());
        $validator->validateCode($rubrique, false)->validateLibelle($rubrique);

        if ($validator->isValid()) {
            $this->pdo->beginTransaction();
            (new Srubcomp($this->pdo))->merge($rubrique);
            $this->pdo->commit();

            return $this->createJsonResponse(['statut' => 'OK', 'redirectRoute' => $this->router->generateUri('Stock.Rubrique.gestion')]);
        } else {
            return $this->createBloquantJsonErrorResponse([], $validator->getError());
        }
    }
}
