<?php

namespace Modules\Consultation\Controller;

use Entity\Model\AoEntet;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Helpers\Ariane\ArianeSub;
use Modules\Consultation\Repository\GestionConsultation;
use Modules\Consultation\Repository\AoEvent;
use GuzzleHttp\Psr7\Response;
use Helpers\Validator\Validator;
use Helpers\Outil\Sql;
use Entity\Model\LstDocs;
use Entity\Model\AoDocAttendus;

class DocAttenduController extends Controller
{
    public function creatEditAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');
        $noOrdre = $this->request->getAttribute('noOrdre');
        $blockObligatoire = $this->request->getAttribute('noOrdre');
        $post = $this->request->getParsedBody();
        
        $gestionConsu = new GestionConsultation($this->pdo);
        $consultation = $gestionConsu->getInfoAo($idAO);
        
        $aoEvent = new AoEvent($this->pdo);
        $AOEventCreat = $aoEvent->getNameCreate($idAO);
        
        $trad = $this->getTranslationService();
        
        $lstDoc = new LstDocs($this->pdo);
        $listDocTMP = $lstDoc->fetchAll();
        
        $listDoc = [];
        foreach ($listDocTMP as $doc) {
            $listDoc[$doc['CODE_DOC']] = $doc['TITRE_DOC'];
        }
        
        if ($noOrdre) {
            $AoDocAttendus = new AoDocAttendus($this->pdo);
            $post = $AoDocAttendus->find(['NO_AO' => $idAO, 'NUM_ORDRE' => $noOrdre]);
            
            ArianeSub::generate(1, 0, $trad->t('Modification document de la réponse'), $this->router->generateUri('Consultation.DocAttendu.creatEdit', ['idAO' => $idAO, 'noOrdre' => $noOrdre]), 1);
        } else {
            ArianeSub::generate(1, 0, $trad->t('Ajout document de la réponse'), $this->router->generateUri('Consultation.DocAttendu.creatEdit', ['idAO' => $idAO]), 1);
            
            $post['OBLIGATOIRE'] = true;
        }
        
        return $this->renderer->render('@Consultation/DocAttendu/creatEdit', [
            'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc':'Consultations',
            'menuLeft'          => 'gestionAO',
            'idAO'              => $idAO,
            'noOrdre'           => $noOrdre,
            'post'              => $post,
            'consultation'      => $consultation,
            'AOEventCreat'      => $AOEventCreat,
            'listDoc'           => $listDoc,
        ]);
    }
    
    public function validateAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $noOrdre = $this->request->getAttribute('noOrdre');
        $post = $this->request->getParsedBody();
        
        $trad = $this->getTranslationService();
        
        $validator = $this->createValidator();
        $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE_DOC'], 1, 120);
        $validator->isStringAvecEspace($trad->t('Commentaire'), $post['COMMENTAIRE'], 0, 3000);
        $validator->isCheck($post['OBLIGATOIRE']);
        
        if ($validator->isValid()) {
            $path = $this->router->generateUri('Consultation.Consultation.details', ['idAO' => $idAO, 'onglet' => 'DocRep']);
            
            $AoDocAttendus = new AoDocAttendus($this->pdo);
            
            if ($noOrdre) {
                $AoDocAttendus->update([
                    'CODE_DOC' => $post['CODE_DOC']??'',
                    'TITRE_DOC' => $post['TITRE_DOC'],
                    'COMMENTAIRE' => $post['COMMENTAIRE'],
                    'numerique_OBLIGATOIRE' => sql::setBoolSql($post['OBLIGATOIRE']),
                ], ['NO_AO' => $idAO, 'NUM_ORDRE' => $noOrdre]);
            } else {
                $gestionConsu = new GestionConsultation($this->pdo);
                $noOrdre = (int) ($gestionConsu->getMaxOrderdocAttendu($idAO)['MAX_ORDER']??'');
                
                $AoDocAttendus->insert([
                    'NO_AO' => $idAO,
                    'NUM_ORDRE' => $noOrdre +1,
                    'CODE_DOC' => '',
                    'TITRE_DOC' => $post['TITRE_DOC'],
                    'COMMENTAIRE' => $post['COMMENTAIRE'],
                    'numerique_OBLIGATOIRE' => sql::setBoolSql($post['OBLIGATOIRE']),
                ]);
            }
            
            return new Response(443, [
                
            ], (string) \json_encode([
                'statut' => 'O',
                'path' => $path,
            ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }
    
    public function deleteAction(): Response
    {
        $idAO = $this->request->getAttribute('idAO');
        $noOrdre = $this->request->getAttribute('noOrdre');
        
        $AoDocAttendus = new AoDocAttendus($this->pdo);
        $AoDocAttendus->delete(['NO_AO' => $idAO, 'NUM_ORDRE' => $noOrdre]);

        return new Response(200, [], (string) \json_encode([]));
    }

    public function ajaxChangeCtrlDossierFournisseurAction(): Response
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();
        $trad= $this->getTranslationService();

        $possibleValues = ['', 'N', 'B'];

        if (!isset($post['CTRL_DOSSIER_FOURNISSEUR']) || !in_array(strtoupper($post['CTRL_DOSSIER_FOURNISSEUR']), $possibleValues)) {
            return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurCreation', ['ErreurValid' => $trad->t('Une erreur est survenue.')]));
        }

        $AoEntet = new AoEntet($this->pdo);
        $AoEntet->update(['CTRL_DOSSIER_FOURNISSEUR' => $post['CTRL_DOSSIER_FOURNISSEUR']], ['NO_AO' => $idAO]);

        return new Response();
    }
}
