<?php

namespace Modules\ProjetAchat\Controller;

use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Modules\ProjetAchat\Repository\Action;
use Modules\ProjetAchat\Repository\BibliothequeDonnee;
use Entity\Model\DoaStruct;
use Helpers\Outil\Sql;
use Entity\Model\DoaActionsData;
use Entity\Model\DoaActionsDon;

class ActionDataController extends Controller
{
    
    public function addDataAction() : string
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        
        $actionRepo = new Action($this->pdo);
        $listeCategorieTMP = $actionRepo->getListCategorieOnObjet($typeObjet, $idObjet, $idTasks, $idAction);
        
        $listeCategorie = [];
        foreach ($listeCategorieTMP as $cat) {
            $listeCategorie[$cat['ID']] = $cat['LIB'];
        }
        
        return $this->renderer->render('@projetAchat/action/tabs/addData', [
            'idObjet'       => $idObjet,
            'typeObjet'     => $typeObjet,
            'idAction'      => $idAction,
            'idTasks'       => $idTasks,
            'listeCategorie' => $listeCategorie,
        ]);
    }
    
    public function generateInputAction() : string
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        
        $post = $this->request->getParsedBody();
        
        $actionRepo = new Action($this->pdo);
        $listeDataTMP = $actionRepo->getListeDataOnObjet($typeObjet, $idObjet, $post['categorie'], $idTasks, $idAction);
        
        $listeData = [];
        foreach ($listeDataTMP as $cat) {
            $listeData[$cat['ID_DONNEE']] = $cat['NOM_DONNEE'];
        }
        
        return $this->renderer->render('@projetAchat/action/tabs/ajaxGenerateInputData', [
            'listeData' => $listeData,
            ]);
    }
    
    public function validateDataAction()
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        
        $post = $this->request->getParsedBody();
        
        $trad = $this->getTranslationService();
        
        $validator = $this->createValidator();
        
        $validator->isFalse($post['CAT'], Trad::strBuild($trad->t('Le champ @1@  est un champ obligatoire.'), $trad->t('Catégorie')));
        $validator->isFalse($post['DATA']??'', Trad::strBuild($trad->t('Le champ @1@  est un champ obligatoire.'), $trad->t('Donnée')));
        
        if ($validator->isValid()) {
            $doaStructEntity = new DoaStruct($this->pdo);
            $bibliothequeRepo = new BibliothequeDonnee($this->pdo);
            $listeData = $bibliothequeRepo->getChampByDonnee($typeObjet, $idObjet, $post['DATA']);
            
            foreach ($listeData as &$donnee) {
                if ((Sql::boolSql($donnee['LIE_A_OBJET']) && !sql::boolSql($donnee['FLAG_ID_OBJET'])) || (!Sql::boolSql($donnee['LIE_A_OBJET']) && (Sql::boolSql($donnee['DATA_LIE_A_OBJ']) && !sql::boolSql($donnee['ID_OBJET_DATA'])))) {
                    $donnee['MODIFIABLE'] = 'F';
                } else {
                    $donnee['MODIFIABLE'] = 'T';
                }
                $donnee['AFFICHEE'] = 'T';
            }
            
            $trad = $this->getTranslationService();
            
            $data = $doaStructEntity->find($post['DATA']);
            
            $data['ListeChamps'] = $listeData;
            
            $listStruct[] = $data;

            return new Response(200, [
                
            ], (string) \json_encode([
                'statut' => 'O',
                'content' => $this->renderer->render('@projetAchat/action/tabs/gestionData', [
                    'listStruct' => $listStruct,
                    'idObjet'       => $idObjet,
                    'typeObjet'     => $typeObjet,
                    'idAction'      => $idAction,
                    'idTasks'       => $idTasks,
                    'createModif' => true,
                    'idData' => $post['DATA'],
                    'editMode' => true,
                ])
            ]));
        } else {
            return new Response(200, [
                
            ], (string) \json_encode([
                'statut' => 'E',
                'content' => $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ])
            ]));
        }
    }
    
    public function editGestionDataAction() : string
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        $idData = $this->request->getAttribute('idData');
        
        $actionRepo = new Action($this->pdo);
        $listStruct = $actionRepo->getListStruct($idAction, $idData);
        
        foreach ($listStruct as &$struct) {
            $struct['ListeChamps'] = $actionRepo->getListData($idAction, $struct['ID_DONNEE']);
        }
        
        return $this->renderer->render('@projetAchat/action/tabs/gestionData', [
            'listStruct' => $listStruct,
            'idObjet'       => $idObjet,
            'typeObjet'     => $typeObjet,
            'idAction'      => $idAction,
            'idTasks'       => $idTasks,
            'idData' => $idData,
            'editMode' => true,
        ]);
    }
    
    public function saveDataAction()
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        $idData = $this->request->getAttribute('idData');
        
        $post = $this->request->getParsedBody();
        
        $bibliothequeRepo = new BibliothequeDonnee($this->pdo);
        $listeData = $bibliothequeRepo->getChampByDonnee($typeObjet, $idObjet, $idData);
        
        $validator = $this->createValidator();
        $doaActionsDataRepo = new DoaActionsData($this->pdo);
        $doaActionDonRepo = new DoaActionsDon($this->pdo);
        
        $actionRepo = new Action($this->pdo);

        $actionRepo->deleteDataAction($typeObjet, $idObjet, $idTasks, $idAction, $idData);
        
        foreach ($listeData as $data) {
            $affiche = $validator->isCheck($post['checkbox_AFF_'.$data['ID_DATA']]);
            $modif = $validator->isCheck($post['checkbox_MOD_'.$data['ID_DATA']]);
            
            if ($modif) {
                $affiche = true;
            }
            
            $dataInsert = [
                'TYPE_OBJET' => $typeObjet,
                'ID_OBJET' => $idObjet,
                'ID_TACHE' => $idTasks,
                'ID_ACTION' => $idAction,
                'ID_DONNEE' => $idData,
                'ID_DATA' => $data['ID_DATA'],
                'numerique_AFFICHEE' => $affiche? '0x54':'0x46',
                'numerique_MODIFIABLE' => $modif? '0x54':'0x46',
            ];
            
            $doaActionsDataRepo->insert($dataInsert);
            
            $doaActionDonRepo->delete([
                'TYPE_OBJET' => $typeObjet,
                'ID_OBJET' => $idObjet,
                'ID_TACHE' => $idTasks,
                'ID_ACTION' => $idAction,
                'ID_DONNEE' => $idData,
            ]);
            
            $doaActionDonRepo->insert([
                'TYPE_OBJET' => $typeObjet,
                'ID_OBJET' => $idObjet,
                'ID_TACHE' => $idTasks,
                'ID_ACTION' => $idAction,
                'ID_DONNEE' => $idData,
                'numerique_CRITERE_SEL' => '0x46',
                'NUM_ORDRE' => ((int)$actionRepo->getRightDoaActionsDonOrder($typeObjet, $idObjet, $idTasks, $idAction))+1,
            ]);
        }
        
        return new Response(200, [
            
        ], (string) \json_encode([
            'statut' => 'O',
            'path' => $this->router->generateUri('ProjetAchat.Action.showDetail', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet, 'idAction' => $idAction]),
            'post' => ['onglet' => 'dataAction']
        ]));
    }
    
    public function deleteDataAction()
    {
        $idObjet = $this->request->getAttribute('idObjet');
        $typeObjet = $this->request->getAttribute('typeObjet');
        $idTasks  = $this->request->getAttribute('idTasks');
        $idAction = $this->request->getAttribute('idAction');
        $idData = $this->request->getAttribute('idData');
        
        $actionRepo = new Action($this->pdo);
        
        $actionRepo->deleteDataAction($typeObjet, $idObjet, $idTasks, $idAction, $idData);
        $actionRepo->deleteDonAction($typeObjet, $idObjet, $idTasks, $idAction, $idData);
        
        return new Response(200, [
            
        ], (string) \json_encode([
            'statut' => 'O',
            'path' => $this->router->generateUri('ProjetAchat.Action.showDetail', ['typeObjet' => $typeObjet, 'idObjet' => $idObjet, 'idAction' => $idAction]),
            'post' => ['onglet' => 'dataAction']
        ]));
    }
    
    public function ajaxReorderDataAction() : string
    {
        $post = $this->request->getParsedBody();
        
        if ($post['initialPosition'] > $post['newPosition']) {
            $post['sign'] = "+";
        } else {
            $post['sign'] = "-";
        }

        $actionRepo = new Action($this->pdo);
        $actionRepo->reorderData($post);
        
        return "true";
    }
}
