<?php

namespace Modules\Stock\Controller;

use Entity\Model\Hastutil;
use Exception;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Filter\FiltreAvance\GeneratorCs;
use Helpers\Pagination\PaginatorGestion;
use Modules\Stock\Helper\GestionFiltreHelper;
use Modules\Stock\Repository\MagasinierRepo;
use Modules\Stock\Trait\Controller\StockContollerTrait;
use Skeleton\Controller\Controller;

class MagasinierController extends Controller
{
    use StockContollerTrait;

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

        GestionFiltreHelper::initialiseCodeSocieteFiltre($post, 'filter_egal_HA#point#CODE_STE');
        Ariane::generate(0, $trad->t('Gestion'), [], null, $this->router->generateUri('Stock.Magasinier.magasiniersGestion'));

        (new PaginatorGestion())->generate(20, 'CODE');
        $magasiniers = (new MagasinierRepo($this->pdo))->listMagasiniers($post);
        $infoPagination = PaginatorGestion::getInfoPagination();

        $filtreAvance = new GeneratorCs($post, 'HASTUTIL', 'CODE', $this->pdo, $trad);
        $filtreAvance->setFiltre('NOM', 'text', $trad->t('Nom'));
        $filtreAvance->setFiltre('CODE', 'text', $trad->t('Code'));

        return $this->renderer->render('@Stock/Magasinier/magasiniers_gestion', [
            'post'             => $post,
            'menuActive'       => 'Stock',
            'infoPagination'   => $infoPagination,
            'magasiniers'      => $magasiniers,
            'initFiltreAvance' => $filtreAvance->getInit(),
            'filtreAvance'     => $filtreAvance->getFiltres(),
            'sessionFilters'   =>  json_encode(['filter_egal_HA#point#CODE_STE'  => $_SESSION['Session_SocUsr']]),
        ]);
    }

    /**
     * @throws Exception
     */
    public function getSiteFromMagasinierAction() :Response
    {
        $post = $this->request->getParsedBody();
        if (!(new Hastutil($this->pdo))->find($post['code'])) {
            return $this->create404Response($this->getTranslationService()->t('L\'utilisateur n\'existe pas'));
        }

        return $this->createJsonResponse((new MagasinierRepo($this->pdo))->getSiteFromMagasinier($post['code']));
    }
}
