<?php

namespace Modules\Stock\Controller;

use Entity\Model\Paravrac;
use Entity\Model\SSiteSto;
use Exception;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Filter\FiltreAvance\GeneratorCs;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Modules\Stock\Helper\GestionFiltreHelper;
use Modules\Stock\MenuContextuel\SiteStockContextuel;
use Modules\Stock\Repository\SiteStockRepo;
use Modules\Stock\Service\Form\SiteStockFormService;
use Modules\Stock\Service\ListManagerService;
use Modules\Stock\Trait\Controller\StockContollerTrait;
use Modules\Stock\Validator\SiteStockValidator;
use Skeleton\Controller\Controller;

class SiteStockController extends Controller
{
    use StockContollerTrait;

    /**
     * @throws Exception
     */
    public function gestionAction(): string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $listManagerService = new ListManagerService($trad);
        GestionFiltreHelper::initialiseCodeSocieteFiltre($post, 'filter_egal_STO#point#CODE_STE');

        if (!isset($post['ETAT'])) {
            $post['ETAT'] = 'V';
        }

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

        (new PaginatorGestion())->generate(20, 'SITE');
        $sitesStock = (new SiteStockRepo($this->pdo))->listSitesStock($post);
        $infoPagination = PaginatorGestion::getInfoPagination();

        (new SiteStockContextuel($this->pdo, $this->router, $trad))->addMenuContextuelToEntities($sitesStock);

        $filtreAvance = new GeneratorCs($post, 'SSITESTO', 'STO.SITE', $this->pdo, $trad);
        $filtreAvance->setFiltre('STO.SIST_DTE_FERM', 'date', $trad->t('Date fermeture'));
        $filtreAvance->setFiltre('STO.DTE_REAP', 'date', $trad->t('Date réapprovisionnement'));
        $filtreAvance->setFiltre('STO.NB_ART', 'numeric', $trad->t('Nombre d\'articles'));
        $filtreAvance->setFiltre('STO.COUT_ORD', 'numeric', $trad->t('Coût d\'ordre'));
        $filtreAvance->setFiltre('STO.DELAI_INT', 'numeric', $trad->t('Délai interne de déclenchement de commande'));
        $filtreAvance->setFiltre('STO.CUM_CONSO', 'numeric', $trad->t('Cumul conso'));

        return $this->renderer->render('@Stock/SiteStock/gestion', [
            'post'             => $post,
            'menuActive'       => 'Stock',
            'sitesStock'       => $sitesStock,
            'infoPagination'   => $infoPagination,
            'initFiltreAvance' => $filtreAvance->getInit(),
            'filtreAvance'     => $filtreAvance->getFiltres(),
            'listeFiltreEtat'  => $listManagerService->getValiditeList(),
            'configAxeImp'     => (new Paravrac($this->pdo))->getCommandeAxeImpConfig(),
            'sessionFilters'   =>  json_encode([
                'filter_egal_STO#point#CODE_STE'  => $_SESSION['Session_SocUsr']
            ]),
            'canCreateSite'    => Roles::droitsUtilisateur($this->pdo, 'ST_SIT_CM'),
        ]);
    }

    /**
     * @throws Exception
     */
    public function ligneAction(): string
    {
        $site = $this->request->getAttribute('site');
        $codeSte = $this->request->getAttribute('codeSte');

        return $this->renderer->render('@Stock/SiteStock/ligne', [
            'id' => $site,
            'idCs' => ChampSupp::encodeCodeEnr('SSITESTO', $site),
            'siteStock' => (new SSiteSto($this->pdo))->find(['SITE' => $site, 'CODE_STE' => $codeSte]),
        ]);
    }

    /**
     * @throws Exception
     */
    public function getSiteStockFromMagasinierAction() :Response
    {
        $post = $this->request->getParsedBody();
        if (!$siteStock = (new SiteStockRepo($this->pdo))->findFromMagasinier($post['code'])[0]) {
            return $this->create404Response($this->getTranslationService()->t('Cet utilisateur n\'a pas de site de stock'));
        }

        return $this->createJsonResponse($siteStock);
    }

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

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

        return $this->renderer->render('@Stock/SiteStock/nouveau_form', [
            'configAxeImp' => (new Paravrac($this->pdo))->getCommandeAxeImpConfig()
        ]);
    }

    /**
     * @throws Exception
     */
    public function nouveauAction(): Response
    {
        $post = $this->request->getParsedBody();
        $siteStock = $post['SSITESTO'];
        $validator = new SiteStockValidator($this->pdo, $this->getTranslationService());

        $validator
            ->validateSite($siteStock)
            ->validateDesign($siteStock)
            ->validateCodeSte($siteStock)
            ->validateCs('SSITESTO', $siteStock['SITE'], $post, null, true)
            ->validateSectimp($siteStock, null, $siteStock['CODE_STE'], 'SI')
            ->validateCodeComp($siteStock, null, $siteStock['CODE_STE'], 'CDC')
            ->validateSscpteana($siteStock, null, $siteStock['CODE_STE'], 'SCA')
        ;

        if ($validator->isValid()) {
            $ssitestoFormService = new SiteStockFormService($this->pdo);
            $bonSortie = $ssitestoFormService->initEntity($siteStock);
            $ssitestoFormService->flushData($bonSortie, $post);

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