<?php
namespace Modules\Consultation\Controller;

use Helpers\Outil\Roles;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Entity\Model\AoEntet;
use Helpers\Ariane\ArianeSub;
use Modules\Consultation\Repository\Reponse;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Entity\Model\AoDaRep;
use Helpers\Fichier\Fichier;
use Entity\Model\AoRepPijo;
use Helpers\Fichier\Gestion_Fic_PJ;
use Entity\Model\AoDocAttendus;
use Entity\Model\Fourniss;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;

class SaisieReponsesPJController extends Controller
{
    public function listePJAction(): string
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $typeDoc = $this->request->getAttribute('typeDoc');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');

        $aoEntet     = new AoEntet($this->pdo);
        $aoDaRep     = new AoDaRep($this->pdo);
        $aoRepPijo   = new AoRepPijo($this->pdo);
        $reponseRepo = new Reponse($this->pdo);

        $consultation             = $aoEntet->find($idAO);
        $infoEnteteRep            = $aoDaRep->find(['NO_AO' => $idAO, 'C_V' => $CV, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep]);
        $infoEnteteRep['COM_FRS'] = sql::getMemo($this->pdo, $infoEnteteRep['COMMENT1']);

        $trad = $this->getTranslationService();

        $AoDocAttendus   = new AoDocAttendus($this->pdo);
        $listeDocAttendu = $AoDocAttendus->fetchAll([], ['filter_egal_NO_AO' => $idAO, 'tri_NUM_ORDRE' => 'asc']);

        Ariane::generate(2, $trad->t('Saisie réponse'));

        ArianeSub::init();

        if ($consultation['RFI_Q'] == 'Q') {
            ArianeSub::generate(0, 1, $trad->t('Postes'), $this->router->generateUri('Consultation.SaisieReponses.listeLigne', ['idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]), 1);
        }
        ArianeSub::generate(0, 2, $trad->t('Pièces jointes'), $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => 'P', 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));

        if (Sql::boolSql($consultation['COMP_QUEST']) == true) {
            ArianeSub::generate(0, 3, $trad->t('Questionnaire'), $this->router->generateUri('Consultation.SaisieReponsesQst.questionnaire', ['idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));
        }

        if (Sql::boolSql($consultation['COMP_DOC_ATT']) == true) {
            ArianeSub::generate(0, 5, $trad->t('Documents de la réponse'), $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => 'D', 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]));
        }
        if ($typeDoc == 'P') {
            ArianeSub::generate(0, 2, $trad->t('Pièces jointes'), $_SERVER['REQUEST_URI'], 1);
            $messageDelete = $trad->t('Etes-vous sûr de vouloir supprimer la pièce jointe');

            $listePJ = $aoRepPijo->findAll(['NO_AO' => $idAO, 'TYPE_DOC' => $typeDoc, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'DTE_REP' => $idRep, 'C_V' => $CV]);
        } else {
            ArianeSub::generate(0, 5, $trad->t('Documents de la réponse'), $_SERVER['REQUEST_URI'], 1);
            $messageDelete = $trad->t('Etes-vous sûr de vouloir supprimer le document de la réponse');

            $listePJ = $reponseRepo->getListDocAtt($idAO, $typeFG, $idFrs, $CV, $idRep);
        }

        // le fournisseur a accès à oxalink ? si non, on peut répondre aux questions fournisseur
        $isSupplierOxalink = Sql::boolSql((new Fourniss($this->pdo))->find(['CODE' => $idFrs], ['GEREPORTAIL'])['GEREPORTAIL']);

        $userCanEdit = Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM')
            || (Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
                && $consultation['ACH'] == $_SESSION["Session_Login"]);

        return $this->renderer->render('@Consultation/SaisieReponses/listePJ', [
            'idAO' => $idAO,
            'typeFG' => $typeFG,
            'idFrs' => $idFrs,
            'idRep' => $idRep,
            'CV' => $CV,
            'typeDoc' => $typeDoc,
            'derniereReponse' => Sql::toBool($reponseRepo->isLastResponse($idAO, $idFrs, $idRep, $typeFG, $CV)),
            'userCanEdit' => $userCanEdit,
            'listePJ' => $listePJ,
            'pathBack' => ariane::getBackPath(),
            'consultation' => $consultation,
            'reponseEntete' => $infoEnteteRep,
            'menuActive' => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc' : 'Consultations',
            'menuLeft' => 'gestionAO',
            'messageDelete' => $messageDelete,
            'canEdit' => ((($infoEnteteRep['EVE_REP'] ?? '0') == '0')
                && (!$isSupplierOxalink || Roles::droitsUtilisateur($this->pdo, 'HA_AO_SRF'))),
            'canDevalidate' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM')
                || (Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
                    && $consultation['ACH'] == $_SESSION["Session_Login"]),
            'fourRecap' => !empty($consultation['CTRL_DOSSIER_FOURNISSEUR'])
                ? $reponseRepo->getFouRecap(
                    'FOURNISS',
                    $idFrs
                )
                : null,
            'contrib' => false,
            'typeCtrlDossierFournisseur' => $consultation['CTRL_DOSSIER_FOURNISSEUR'] ?? '',
        ]);
    }

    public function createEditAction(): string
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeDoc = $this->request->getAttribute('typeDoc');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $ordre   = $this->request->getAttribute('ordre');

        $trad = $this->getTranslationService();

        // le fournisseur a accès à oxalink ? si non, on peut répondre aux questions fournisseur
        $isSupplierOxalink = Sql::boolSql((new Fourniss($this->pdo))->find(['CODE' => $idFrs], ['GEREPORTAIL'])['GEREPORTAIL']);

        $aoEntet = new AoEntet($this->pdo);
        $aoDaRep = new AoDaRep($this->pdo);

        $consultation  = $aoEntet->find($idAO);
        $infoEnteteRep = $aoDaRep->find(['NO_AO' => $idAO, 'CODE_FOU' => $idFrs, 'TYPE_FG' => $typeFG, 'DTE_REP' => $idRep, 'C_V' => $CV]);

        if ($typeDoc == 'P') {
            ArianeSub::generate(1, 0, $trad->t('Création Pièce Jointe'), $_SERVER['REQUEST_URI'], 1);
        } else {
            ArianeSub::generate(1, 0, $trad->t('Ajout document attendu'), $_SERVER['REQUEST_URI'], 1);

            $aoDocAttendu = new AoDocAttendus($this->pdo);
            $docAttendu   = $aoDocAttendu->find(['NO_AO' => $idAO, 'NUM_ORDRE' => $ordre]);
            $PJ['TITRE']  = $docAttendu['TITRE_DOC'];
        }

        return $this->renderer->render('@Consultation/SaisieReponses/createEditPJ', [
            'idAO' => $idAO,
            'typeFG' => $typeFG,
            'idFrs' => $idFrs,
            'idRep' => $idRep,
            'CV' => $CV,
            'typeDoc' => $typeDoc,
            'ordre' => $ordre,
            'canEdit' => ((($infoEnteteRep['EVE_REP'] ?? '0') == '0')
                && (!$isSupplierOxalink || Roles::droitsUtilisateur($this->pdo, 'HA_AO_SRF'))),
            'canDevalidate' => Roles::droitsUtilisateur($this->pdo, 'HA_AO_ADM')
                || (Roles::droitsUtilisateur($this->pdo, 'HA_AO_CMV')
                    && $consultation['ACH'] == $_SESSION["Session_Login"]),
            'contrib' => false,
            'consultation' => $consultation,
            'reponseEntete' => $infoEnteteRep,
            'pj' => $PJ ?? [],
        ]);
    }

    public function validateAction()
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeDoc = $this->request->getAttribute('typeDoc');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $ordre   = $this->request->getAttribute('ordre');

        $trad = $this->getTranslationService();

        $post = $this->request->getParsedBody();

        $reponseRepo = new Reponse($this->pdo);
        $validator   = $this->createValidator();
        $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE'], 1, 120);

        $file = $this->request->getUploadedFiles();

        if ($file) {
            $file_name = $file['importFILE']->getClientFilename();
            $fileSize  = $file['importFILE']->getSize();
        } else {
            $file_name = null;
            $fileSize  = 0;
        }
        $validator->fileCheck("file ", $file_name ?? '', [], '', $fileSize);
        $aoRepPijo = new AoRepPijo($this->pdo);

        if ($validator->isValid()) {
            $newPath = Fichier::UploadDocAtt($file_name);
            $file['importFILE']->moveTo($newPath["racine"] . $newPath["new_name"]);

            $creationFile = new Gestion_Fic_PJ($this->pdo);
            $fileSave     = $creationFile->insertFichier($newPath['new_name']);

            if (!$ordre) {
                $maxOrder = (int) ($reponseRepo->getMaxPJ($idAO, $idFrs, $idRep, $typeFG, $CV)['maxOrdre'] ?? '0');
                $ordre    = $maxOrder + 1;
            }

            $aoRepPijo->insert([
                'NO_AO' => $idAO,
                'CODE_FOU' => $idFrs,
                'TYPE_FG' => $typeFG,
                'DTE_REP' => $idRep,
                'C_V' => $CV,
                'TYPE_DOC' => $typeDoc,
                'NUM_ORDRE' => $ordre,
                'TITRE' => $post['TITRE'],
                'NOM_ORI' => $file_name,
                'NOM_FIC' => $fileSave,
            ]);

            return new Response(200, [], json_encode(['path' => $this->router->generateUri('Consultation.SaisieReponsesPJ.listePJ', ['typeDoc' => $typeDoc, 'idAO' => $idAO, 'typeFG' => $typeFG, 'idFrs' => $idFrs, 'idRep' => $idRep, 'CV' => $CV]), 'statut' => 'O']));
        } else {
            return new Response(200, [], json_encode(['erreur' => $validator->getError(), 'statut' => 'E']));
        }
    }

    /** retourne le fichier **/
    public function downloadFichierAction(): string
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeDoc = $this->request->getAttribute('typeDoc');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $ordre   = $this->request->getAttribute('ordre');

        $aoRepPijo = new AoRepPijo($this->pdo);
        $pj        = $aoRepPijo->find(['NO_AO' => $idAO, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'TYPE_DOC' => $typeDoc, 'DTE_REP' => $idRep, 'C_V' => $CV, 'NUM_ORDRE' => $ordre]);

        $message = Fichier::UploadClient((new ParseBase1())->getRep()->pj . $pj['NOM_FIC'], $pj['NOM_ORI']);

        return $message;
    }

    public function deleteAction()
    {
        $idAO    = $this->request->getAttribute('idAO');
        $typeDoc = $this->request->getAttribute('typeDoc');
        $typeFG  = $this->request->getAttribute('typeFG');
        $idFrs   = $this->request->getAttribute('idFrs');
        $idRep   = $this->request->getAttribute('idRep');
        $CV      = $this->request->getAttribute('CV');
        $ordre   = $this->request->getAttribute('ordre');

        $aoRepPijo = new AoRepPijo($this->pdo);
        $pj        = $aoRepPijo->find(['NO_AO' => $idAO, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'TYPE_DOC' => $typeDoc, 'DTE_REP' => $idRep, 'C_V' => $CV, 'NUM_ORDRE' => $ordre]);
        $aoRepPijo->delete(['NO_AO' => $idAO, 'TYPE_FG' => $typeFG, 'CODE_FOU' => $idFrs, 'TYPE_DOC' => $typeDoc, 'DTE_REP' => $idRep, 'C_V' => $CV, 'NUM_ORDRE' => $ordre]);

        $deleteFile = new Gestion_Fic_PJ($this->pdo);
        $deleteFile->deleteFichier($pj['NOM_FIC']);

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