<?php

namespace Modules\ProjetAchat\Controller;

use Helpers\Outil\Sql;
use Modules\ProjetAchat\Service\ActionService;
use Psr\Container\ContainerInterface;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Entity\Model\DoaTaches;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Entity\Model\DoaAction;
use Modules\ProjetAchat\Repository\Task;
use Modules\ProjetAchat\Repository\Action;
use Entity\Model\Doa;
use Entity\Model\DoaActionsActeurs;
use Skeleton\Renderer\RendererInterface;
use Skeleton\Router;
use Modules\ProjetAchat\Service\ModeleProjetService;
use Helpers\Outil\Roles;
use Modules\ProjetAchat\Service\ElementsConcernedService;
use Helpers\ChampsSupplementaire\ChampSupp;

class ActionController extends Controller
{

    /**
     * @var ActionService $actionService
     */
    private $actionService;

    private $actionRepo;

    public function __construct(RendererInterface $renderer, \PDO $pdo, Router $router, ContainerInterface $contenaire)
    {
        parent::__construct($renderer, $pdo, $router, $contenaire);
        $this->actionService = new ActionService($this->pdo);
        $this->actionRepo = new Action($this->pdo);
    }

    /**
     * @return Response|string
     */
    public function createEditAction()
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTask = $this->request->getAttribute('idTask');
        $idAction = $this->request->getAttribute('idAction');
        
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        
        $taskRepo = new Task($this->pdo);
        $doaTachesEntity = new DoaTaches($this->pdo);
        $doaActionEntity = new DoaAction($this->pdo);
        $infoTask = $doaTachesEntity->find($idTask);
        
        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace($trad->t('Nom'), $post['LIB'], 1, 120);
            $validator->isStringAvecEspace($trad->t('Description'), $post['COMMENTAIRE'], 0, 3000);
            
            if ($validator->isValid()) {
                if ($idAction) {
                    $commentaire = Trad::strBuild(('Modification de l\'action : @1@ sur la tâche @2@'), $post['LIB'], $infoTask['LIB']);
                } else {
                    $commentaire = Trad::strBuild(('Ajout de l\'action : @1@ sur la tâche @2@'), $post['LIB'], $infoTask['LIB']);
                }
                ModeleProjetService::updateDoaEvent($this->pdo, $idObjet, $typeObjet, $commentaire);
                
                
                if ($idAction) {
                    $doaActionEntity->update([
                        'LIB' => $post['LIB'],
                        'COMMENTAIRE' => $post['COMMENTAIRE'],
                    ], $idAction);
                    
                    return new Response(200, [
                        
                    ], (string) \json_encode([
                        'statut' => 'O',
                        'action' => 'redirect',
                        'path' => $this->router->generateUri('ProjetAchat.ModeleProjet.details', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet]),
                        'post' => ['onglet' => 'tasks', 'id' => $infoTask['ID_TACHE_H']]
                    ]));
                } else {
                    $doaActionEntity->insert([
                        'TYPE_OBJET' => $typeObjet,
                        'ID_OBJET' => $idObjet,
                        'ID_TACHE' => $idTask,
                        'LIB' => $post['LIB'],
                        'COMMENTAIRE' => $post['COMMENTAIRE'],
                        'NUM_ORDRE' => ((int) $taskRepo->getActionRightOrder($idTask)) +1,
                    ]);
                    
                    $lastIdAction = $taskRepo->getLastIdAction($typeObjet, $idObjet, $idTask);
                    
                    $taskEntity = new DoaTaches($this->pdo);
                    $infoTask = $taskEntity->find($idTask);
                    
                    if ($infoTask['RESPONSABLE'] == 'P' || $infoTask['RESPONSABLE'] == 'S' || $infoTask['RESPONSABLE'] === '') {
                        $codeActeur = '';
                        $typeElem = '3';
                    } elseif (strpos($infoTask['RESPONSABLE'], 'CS_') === 0) {
                        $codeActeur = '';
                        $typeElem = $infoTask['RESPONSABLE'];
                    } else {
                        $codeActeur = $infoTask['RESPONSABLE'];
                        $typeElem = '';
                    }
                    
                    $doaActionActorEntity = new DoaActionsActeurs($this->pdo);
                    $doaActionActorEntity->insert([
                        'TYPE_OBJET'    => $typeObjet,
                        'ID_OBJET'      => $idObjet,
                        'ID_TACHE'      => $idTask,
                        'ID_ACTION'     => $lastIdAction['maxId'],
                        'ROLE'          => 'R',
                        'CODE_ACTEUR'   => $codeActeur,
                        'TYPE_ELEM'     => $typeElem
                    ]);
                    
                    return new Response(200, [
                        
                    ], (string) \json_encode([
                        'statut' => 'O',
                        'action' => 'tab',
                        'path' => $this->router->generateUri('ProjetAchat.Action.showDetail', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet, 'idAction' => $lastIdAction['maxId']]),
                        'pathRefresh' => $this->router->generateUri('ProjetAchat.Hierarchy.ajaxDetailHierarchy', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet, 'idCategorie' => $infoTask['ID_TACHE_H']]),
                        'tabLibelle' => $trad->t('Détail action'),
                    ]));
                }
            } else {
                return new Response(200, [
                    
                ], (string) \json_encode([
                    'statut' => 'E',
                    'content' => $this->renderer->render('@popup-erreur/ErreurCreation', [
                        'ErreurValid' => $validator->getError(),
                    ])
                ]));
            }
        }
        
        if ($idAction) {
            $action = $doaActionEntity->find($idAction);
        }

        
        return $this->renderer->render('@projetAchat/action/createEdit', [
            'idObjet'       => $idObjet,
            'typeObjet'     => $typeObjet,
            'idTask'        => $idTask,
            'idAction'      => $idAction,
            'infoTask'      => $infoTask,
            'action'        => $action??[],
        ]);
    }
    
    public function deleteAction()
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTask = $this->request->getAttribute('idTask');
        $idAction = $this->request->getAttribute('idAction');
        
        $doaTachesEntity = new DoaTaches($this->pdo);
        $doaActionEntity = new DoaAction($this->pdo);
        $infoTask = $doaTachesEntity->find($idTask);
        $infoAction = $doaActionEntity->find($idAction);
        $doaActionEntity->delete($idAction);
        $trad = $this->getTranslationService();
        
        $commentaire = Trad::strBuild(('Suppression de l\'action : @1@ sur la tâche @2@'), $infoAction['LIB'], $infoTask['LIB']);
        ModeleProjetService::updateDoaEvent($this->pdo, $idObjet, $typeObjet, $commentaire);
        
        return new Response(200, [], (string) \json_encode([
            'path' => $this->router->generateUri('ProjetAchat.Hierarchy.ajaxDetailHierarchy', [
                'typeObjet' => $typeObjet,
                'idObjet' => $idObjet,
                'idCategorie' => $infoTask['ID_TACHE_H'],
            ]),
        ]));
    }
    
    public function showDetailAction() : string
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idAction = $this->request->getAttribute('idAction');
        
        $doaActionEntity = new DoaAction($this->pdo);
        $action = $doaActionEntity->find($idAction);
        
        $doaEntity = new Doa($this->pdo);
        $infoDOA = $doaEntity->find($idObjet);
        
        $actionRepo = new Action($this->pdo);
        if ($infoDOA['STATUT'] == 'E' || $infoDOA['STATUT'] == 'T') {
            $listActor = $actionRepo->getListRACI($idAction);
        } else {
            $listActor = $actionRepo->getListActor($idAction);
        }
        
        $elementConcernedService = new ElementsConcernedService($this->pdo, $this->getTranslationService());
        $modeleProjetService = new ModeleProjetService($this->pdo);
        $listObjet = $elementConcernedService->generateArrayElementConcerned();
        
        $repoChampSup = new ChampSupp($this->pdo);
        foreach ($listActor as &$actor) {
            if (($actor['TYPE_ELEM']??'') != '') {
                $libelle = $modeleProjetService->generateLibelleTypeElement($actor['TYPE_ELEM'], $actor['ID_ELEM']);
                
                if ($actor['TYPE_ACTEUR'] != '') {
                    $splitTypeActor = explode('|', $actor['TYPE_ACTEUR']);
                    
                    $getInfoCS = $repoChampSup->getinfoOneCs(
                        $splitTypeActor[0],
                        $splitTypeActor[1]
                    );
                    if ($getInfoCS) {
                        $actor['LIB_TYPE_ACTEUR'] = $getInfoCS['NOM'];
                    }
                }
                $actor['LIB_TYPE_ELEM'] = $listObjet[$actor['TYPE_ELEM']]??'';
                $actor['LIB_ID_ELEM'] = $libelle;
            }
        }
        
        $listStruct = $actionRepo->getListStruct($idAction);
        
        foreach ($listStruct as &$struct) {
            $struct['ListeChamps'] = $actionRepo->getListData($idAction, $struct['ID_DONNEE']);
        }
        
        $trad = $this->getTranslationService();
        
        $listeRole = [
            'R' => $trad->t('Responsable'),
            'A' => $trad->t('Acteur'),
            'C' => $trad->t('Contributeur'),
            'I' => $trad->t('Informé'),
        ];
        
        if ($infoDOA['STATUT'] == 'E' || $infoDOA['STATUT'] == 'T') {
            $datas = $this->actionService->getData($idObjet, $idAction);
        }
        
        $listeDeclencheur['1'] = $trad->t('Propriétaire du projet');
        $listeDeclencheur['2'] = $trad->t('Prescripteur du projet');
        $listeDeclencheur['3'] = $trad->t('Responsable de la tâche');

        $modeleProjetService = new ModeleProjetService($this->pdo);
        $listeTypeActeur = $modeleProjetService->generateListTypeActeur('DOA', $trad);

        if ($listeTypeActeur) {
            foreach ($listeTypeActeur as $key => $acteur) {
                $numFix = explode('|', $key);
                $listeDeclencheur['CS_'.$numFix[1]] = $trad->t($acteur);
            }
        }

        /** ***************** **/
        $droit = [
            'DOA_DOA_CM' => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_CM', $_SESSION["Session_Login"]),
            'DOA_DOA_TT' => Roles::droitsUtilisateur($this->pdo, 'DOA_DOA_TT', $_SESSION["Session_Login"]),
            'DOA_MOD_CM' => Roles::droitsUtilisateur($this->pdo, 'DOA_MOD_CM', $_SESSION["Session_Login"]),
            'DOA_MOD_TT' => Roles::droitsUtilisateur($this->pdo, 'DOA_MOD_TT', $_SESSION["Session_Login"]),
        ];
        
        $canEdit =
            $typeObjet == 'B'
            || (
                $typeObjet == 'M'
                && (
                    ($droit['DOA_MOD_CM'] && $infoDOA['PROPRIETAIRE'] == $_SESSION["Session_Login"])
                    || $droit['DOA_MOD_TT']
                )
            ) || (
                $typeObjet == 'D'
                && ! Sql::toBool($infoDOA['SUSPENDU'] ?? false)
                && (($infoDOA['STATUT']??'')=='I' || ($infoDOA['STATUT']??'')== 'P')
            ) && (
                ($droit['DOA_DOA_CM'] && $infoDOA['PROPRIETAIRE'] == $_SESSION["Session_Login"])
                || $droit['DOA_DOA_TT']
            );
        
        return $this->renderer->render('@projetAchat/action/detail', [
            'idObjet'       => $idObjet,
            'typeObjet'     => $typeObjet,
            'idAction'      => $idAction,
            'action'        => $action,
            'listActor'     => $listActor,
            'listeRole'     => $listeRole,
            'statut'        => $infoDOA['STATUT']??'',
            'listStruct'    => $listStruct,
            'datas'         => $datas??[],
            'idForDoc'      => str_pad($idObjet, 9, '0', STR_PAD_LEFT),
            'post'          => ['onglet' => ($infoDOA['STATUT']=='E')? 'dataAction':''],
            'listeDeclencheur' => $listeDeclencheur,
            'canEdit'       => $canEdit
        ]);
    }

    public function getActionRepo()
    {
        return $this->actionRepo;
    }
}
