<?php

namespace Modules\Additional\Specifique\Client71\Modules\Administration\Controller;

use Entity\Model\ParamDico;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Modules\Additional\Specifique\Client71\Modules\Administration\Repository\ChantierRepository;
use Skeleton\Controller\Controller;

class ParametrageChantierController extends Controller
{
    public function indexAction():string
    {
        $trad = $this->getTranslationService();

        Ariane::generate(0, $trad->t('Chantier complémentaire par direction '));

        return $this->renderer->render('@Specifique71Admin/index', [
            'menuActive'            => 'Administration',
            'menuLeft'              => 'specifique71',

            'post'                  => ['CODE_STE' => $_SESSION["Session_SocUsr"]],
        ]);
    }

    /**
     * @return Response|string
     */
    public function ajaxSaveChantierAction()
    {
        $post = $this->request->getParsedBody();

        if (!$post['CODE_STE'] || !$post['CODE_DIR']) {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $this->getTranslationService()->t('Il faut un code société et un code Agence.'),
                'desactiveRow' => true,
            ]));
        }

        (new ParamDico($this->pdo))->delete([
            'TYPEDICO'  => 'LEONG_DIRSI',
            'ID1'       => $post['CODE_STE'],
            'ID2'       => $post['CODE_DIR'],
        ]);

        $listeSI = explode('/', $post['CHANTIER']);

        foreach ($listeSI as $si) {
            (new ParamDico($this->pdo))->insert([
                'TYPEDICO'  => 'LEONG_DIRSI',
                'ID1'       => $post['CODE_STE'],
                'ID2'       => $post['CODE_DIR'],
                'ID3'       => uniqid(),
                'LIBELLE'   => $si
            ]);
        }

        return $this->renderer->render('@popup-erreur/information', [
            'message' => $this->getTranslationService()->t('Les modifications ont été enregistrées'),
        ]);
    }

    /**
     * @return Response
     */
    public function getChantierAction()
    {
        $post = $this->request->getParsedBody();

        if (!$post['CODE_STE'] || !$post['CODE_DIR']) {
            return new Response(200, [
            
            ], (string) \json_encode([
                'listeChantier' => ''
            ]));
        }

        $listeSITmp = (new ChantierRepository($this->pdo))->getSiByDirLink($post['CODE_STE'], $post['CODE_DIR']);
        $listeSI = implode('/', array_column($listeSITmp, 'CODE_SI', 'CODE_SI'));

        return new Response(200, [
            
        ], (string) \json_encode([
            'listeChantier' => $listeSI
        ]));
    }
}
