<?php
namespace Modules\ProjetAchat\Controller;

use Helpers\Trad\Trad;
use Modules\ProjetAchat\Service\DonneeService;
use Modules\ProjetAchat\Service\ElementsConcernedService;
use Psr\Container\ContainerInterface;
use Skeleton\Controller\Controller;
use Skeleton\Renderer\RendererInterface;
use Skeleton\Router;
use Modules\ProjetAchat\Repository\ElementConcerned;
use Helpers\ChampsSupplementaire\ChampSupp;
use Entity\Model\DoaElem;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Modules\ProjetAchat\Service\ModeleProjetService;

class ElementsConcernedController extends Controller
{
    /**
     * @var ElementsConcernedService
     */
    private $elementsConcernedService;

    private $champSuppHelpers;

    private $dataService;

    public function __construct(RendererInterface $renderer, \PDO $pdo, Router $router, ContainerInterface $contenaire)
    {
        parent::__construct($renderer, $pdo, $router, $contenaire);
        $this->elementsConcernedService = new ElementsConcernedService($this->pdo, $this->getTranslationService());
        $this->champSuppHelpers = new ChampSupp($this->pdo);
        $this->dataService = new DonneeService($this->pdo);
    }

    public function createAction() : string
    {
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idObjet = $this->request->getAttribute('idObjet');
        $typeElement = $this->request->getAttribute('typeElement');
        
        if ($typeElement) {
            $arrayZoom = $this->champSuppHelpers->generateImput($this->router, $this->getTranslationService(), $typeElement);
        }
        
        return $this->renderer->render('@projetAchat/elementsConcerned/create', [
            'typeObjet'                 => $typeObjet,
            'idObjet'                   => $idObjet,
            'arrayZoom'                 => $arrayZoom??[],
            'typeElement'               => $typeElement,
            'linkedObjects'             => $this->elementsConcernedService->generateArrayElementConcerned(),
        ]);
    }
    
    public function editAction() : string
    {
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idObjet = $this->request->getAttribute('idObjet');
        $typeElement = $this->request->getAttribute('typeElement');
        $idElement = $this->request->getAttribute('idElement');

        $arrayZoom = $this->champSuppHelpers->generateImput($this->router, $this->getTranslationService(), $typeElement);

        return $this->renderer->render('@projetAchat/elementsConcerned/create', [
            'typeObjet'                 => $typeObjet,
            'idObjet'                   => $idObjet,
            'arrayZoom'                 => $arrayZoom??[],
            'linkedObjects'             => $this->elementsConcernedService->generateArrayElementConcerned(),
            'typeElement'               => $typeElement,
            'idElement'                 => $idElement,
            'valueInputGenerate'        => $idElement,
        ]);
    }
    
    public function generateInputAction() : string
    {
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idObjet = $this->request->getAttribute('idObjet');
        $post = $this->request->getParsedBody();
        
        $arrayZoom = $this->champSuppHelpers->generateImput($this->router, $this->getTranslationService(), $post['typeElem']);
        

        return $this->renderer->render('@projetAchat/elementsConcerned/ajaxInputGenerate', [
            'csType' => $arrayZoom['csType']??null,
            'arrayZoom' => $arrayZoom,
            'typeObjet' => $typeObjet,
            'idObjet' => $idObjet,
        ]);
    }
    
    public function ajaxInsertElementAction()
    {
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idObjet = $this->request->getAttribute('idObjet');
        $typeElement = $this->request->getAttribute('typeElement');
        $idElement = $this->request->getAttribute('idElement');
        $trad = $this->getTranslationService();
        
        $post = $this->request->getParsedBody();
        
        if ($post) {
            $validator = $this->createValidator();
            
            $validator->isFalse($post['typeElem'], Trad::strBuild($trad->t('Le champ @1@  est un champ obligatoire.'), $trad->t('Type d\'élément')));
            
            $elementConcernedRepository = new ElementConcerned($this->pdo);
            $champSupp = new ChampSupp($this->pdo);
            $listObjet = $this->dataService->getLinkedObjectsList();
            
            if ($csType = $champSupp->tsDonExist($post['typeElem'])) {
                $validator->validatorTSDON($listObjet[$csType['TYPE']], $post['inputGenerate'], $csType['TYPE'], $this->pdo, false);
            } else {
                $array = ChampSupp::getListeTableStd();
                $zoom=[];
                foreach ($array as $key => $valeur) {
                    $valeur;
                    if ($key == $post['typeElem']) {
                        $zoom=$array[$key];
                        break;
                    }
                }
                
                if (key_exists(2, $zoom)) {
                    $where = [$zoom[2] => 'T'];
                } else {
                    $where = [];
                }
                
                $validator->zoom($zoom[0], $post['inputGenerate'], $listObjet[$post['typeElem']], $this->pdo, false, $where);
            }

            if ($elementConcernedRepository->elementExistProjet((int)$idObjet, $post['typeElem'], (int)$post['inputGenerate'])) {
                $validator->setError($trad->t('Cet élément existe déjà.'));
            }
            
            if ($validator->isValid()) {
                $commentaire = trad::strBuild(('Ajout de l\'élément concerné @1@ - @2@'), $post['typeElem'], $post['inputGenerate']);
                ModeleProjetService::updateDoaEvent($this->pdo, $idObjet, $typeObjet, $commentaire);
                
                if ($idElement && $typeElement) {
                    $ElementConcernedRepo = new ElementConcerned($this->pdo);
                    $ElementConcernedRepo->deleteElement($idObjet, $typeElement, $idElement);
                }
                
                $doaElem = new DoaElem($this->pdo);
                $doaElem->insert([
                    'ID_DOA' => $idObjet,
                    'TYPE_ELEM' => $post['typeElem'],
                    'ID_ELEM' => $post['inputGenerate'],
                ]);
                
                return new Response(200, [
                    
                ], (string) \json_encode([
                    'statut' => 'O',
                    'path' => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet]),
                    'post' => ['onglet' => 'subjectsElements']
                ]));
            } else {
                return new Response(200, [
                    
                ], (string) \json_encode([
                    'statut' => 'E',
                    'content' => $this->renderer->render('@popup-erreur/ErreurCreation', [
                        'ErreurValid' => $validator->getError(),
                    ])
                ]));
            }
        }
    }
    
    public function deleteAction()
    {
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idObjet = $this->request->getAttribute('idObjet');
        $typeElement = urldecode($this->request->getAttribute('typeElement'));
        $idElement = urldecode($this->request->getAttribute('idElement'));
        
        $ElementConcernedRepo = new ElementConcerned($this->pdo);
        $ElementConcernedRepo->deleteElement($idObjet, $typeElement, $idElement);
        $trad = $this->getTranslationService();

        $commentaire = trad::strBuild(('Suppression de l\'élément concerné @1@ - @2@'), $typeElement, $idElement);
        ModeleProjetService::updateDoaEvent($this->pdo, $idObjet, $typeObjet, $commentaire);
        
        return new Response(200, [], (string) \json_encode([
            'statut' => 'O',
            'path' => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet]),
            'post' => ['onglet' => 'subjectsElements'],
        ]));
    }
}
