<?php

namespace Modules\Fournisseur\Controller;

use Modules\GlobalApplication\Repository\LicenceOxalys;
use Skeleton\Controller\Controller;
use Entity\Model\DocCat;
use Entity\Model\PJTypes;
use Entity\Model\Docatt;
use Helpers\Fichier\Fichier;
use Entity\Model\Fourniss;
use Helpers\Outil\Sql;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;
use GuzzleHttp\Psr7\Response;

class ModifierDocFournisseurController extends Controller
{


    public function editDocAttAction()
    {
        $codeFrs = $this->request->getAttribute('id');
        $ordre = $this->request->getAttribute('ordre');
        $post = $this->request->getParsedBody();

        $titreURL = $post['TITRE'] ?? $post['titre'] ?? null;

        /* trad */

        $trad = $this->getTranslationService();

        $docAtt = new Docatt($this->pdo);
        $docAttRepo = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $frsIsWF = $docAttRepo->fournissIsDemandeCreation($codeFrs);

        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($codeFrs);

        $demandeWithOutCode = false;
        if ($fournis) {
            $codeDemande = null;
            $libelle = $fournis["RS"];
        } else {
            if ($frsIsWF) {
                $libelle = $frsIsWF['WDEN_LIBELLE_ENREG'];
                $codeDemande = $frsIsWF['CODE_DEMANDE'];
            } else {
                $demandeWithOutCode = true;
                $codeDemande = $codeFrs;
                $libelle = $docAttRepo->libelleDemandeFrs($codeDemande)['VALEUR_CHAMP'];
            }
        }
        
        $docAtt = $docAttRepo->docAttAvecMemos($codeFrs, $titreURL, $codeDemande);

        if (SQL::boolSql($docAtt["NPRELANCE"])) {
            $docAtt["NPRELANCE"] = 1;
        }
        if (SQL::boolSql($docAtt["PJ_CDE"])) {
            $docAtt["PJ_CDE"] = 1;
        }

        /* On verifie que le document n'est pas géré par l'ALG*/
        $listLicPartn = (new LicenceOxalys($this->pdo))->getPartenaireList();
        $ALG = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        if (!empty($listLicPartn)) {
            $licenceALG = $ALG->PartenaireALG($codeFrs);
            if ($licenceALG) {
                $docALG = $ALG->DocumentALG($docAtt["TITRE"]);
                if ($docALG["ALPHA3"] != " " && $docALG) {
                    return $this->redirect('Fournisseur.DocFournisseur.docRattache', ["id" => $codeFrs]);
                }
            }
        }
        
        /* ******************************** */

        /** Pour chargé les menu déroulent**/
        $tabDossier = [];
        $dossier = new DocCat($this->pdo);
        $dossier = $dossier->findAll(["CODE_TABLE" => "FOURNISS"]);
        for ($i = 0; $i < count($dossier); $i++) {
            $tabDossier[$dossier[$i]["CODE_CAT"]] = $dossier[$i]["LIBELLE_CAT"];
        }

        $tabTypePj = [];
        $typePj = new PJTypes($this->pdo);
        $typePj = $typePj->fetchAll();
        for ($i = 0; $i < count($typePj); $i++) {
            $tabTypePj[$typePj[$i]["PJ_TYPE"]] = $typePj[$i]["PJLIBELLE"];
        }
        /** ************************** **/


        $titre_exist = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $titre_exist = $titre_exist->titreExist($docAtt['TITRE'], $codeFrs, $fournis['CODE_PAYS']);

        /** Si le document est envoyé **/

        if ($demandeWithOutCode) {
            $path =  $this->router->generateUri('Fournisseur.DocFournisseur.docRattache', ["id" => 'noId', 'codeDemande' => $codeDemande]);
        } elseif ($codeDemande) {
            $path =  $this->router->generateUri('Fournisseur.DocFournisseur.docRattache', ["id" => $codeFrs, 'codeDemande' => $codeDemande]);
        } else {
            $path =  $this->router->generateUri('Fournisseur.DocFournisseur.docRattache', ["id" => $codeFrs]);
        }

        if ($this->request->getMethod() == 'POST' && (isset($post['sendForm']) && $post['sendForm'] == '1')) {
            /** On verifie les champs **/
            $validator = $this->createValidator();

            $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE'], 1, 120);
            $validator->zoom('HASTUTIL', $post['AUTEUR'], $trad->t('Auteur'), $this->pdo);
            $validator->zoom('Centre', $post['CENTRE'], $trad->t('Centre'), $this->pdo);

            $validator->isDate($post['DT_PARUT'], '', '', true, $trad->t('de parution'));
            $validator->isDate($post['DT_VALID'], date('Ymd'), '', true, $trad->t('de fin de validité'));
            $validator->isCoherenceDate($post['DT_PARUT'], $post['DT_VALID'], '', true);

            $validator->isCheck($post['NPRELANCE']);
            $validator->isCheck($post['PJ_CDE']);

            $validator->isStringAvecEspace($trad->t('commentaire'), $post['CONTMEMO'], 0, 3000);

            $file = $this->request->getUploadedFiles();
            if ($file) {
                $file_name = $file['importdocFrs']->getClientFilename();
                $fileSize = $file['importdocFrs']->getSize();
            } else {
                $file_name = null;
                $fileSize = 0;
            }
            $validator->fileCheck("file ", $file_name, [], $post['file_namedocFrs'], $fileSize);

            /** ***************** **/

            if (! $validator->isValid()) {
                return new Response(200, [], json_encode(['erreur' => $validator->getError(), 'statut' => 'E']));
            }

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

            if ($codeDemande) {
                $typeObjet = 'WFT_DEM_ENT';
                $code = $codeDemande;
            } else {
                $typeObjet = 'FOURNISS';
                $code = $codeFrs;
            }

            $value = [
                "langue" => $_SESSION['Session_Langue'],
                "new_name" => $newPath["new_name"] ?? '',
                "file_name" => $file_name,
                "typeObjet" => $typeObjet,
                "refObjet" => $code,
                "typePj" => $post['TYPE_PJ'],
                "titreDoc" => $post['TITRE'],
                "auteur" => $post['AUTEUR'],
                "centre" => $post['CENTRE'],
                "dateParu" => $post['DT_PARUT'],
                "dateVali" => $post['DT_VALID'],
                "PJCommande" => $post['PJ_CDE'],
                "commentaire" => $post['CONTMEMO'],
                "categorie" => $post['CODE_CAT'],
                "histo" => "FALSE",
                "docAtt" => $post['NO_ORDRE'],
                "edition" => "TRUE",
                "edit" => true,
                "doc" => true,

            ];

            $docAtt = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
            $docAtt = $docAtt->docAttHisto($codeFrs, $post['TITRE']);

            $xmlResult = new \Modules\Fournisseur\WebService\DocFournisseur();
            $xmlResult = $xmlResult->NouveauDocAttAvecHisto($value);

            $reponseDocRat = new \SimpleXMLElement($xmlResult->responseData);


            if ($reponseDocRat->Statut == "O") {
                return new Response(200, [], json_encode(['path' => $path, 'statut' => 'O']));
            }
            return new Response(200, [], json_encode(['erreur' => $reponseDocRat->MsgErreur, 'statut' => $reponseDocRat->Statut]));
        }

        ArianeSub::generate(2, 0, $trad->t('Modification document'), $_SERVER['REQUEST_URI'], 1);

        return $this->renderer->render('@Fournisseur/DocFournisseur/nouveau', [
            'menuActive'          => 'Fournisseur',
            'menuLeft'            => 'GestionFournisseur',
            "code_fournisseur"    => $codeFrs,
            "libelle_fournisseur" => $libelle,
            "code"                => $codeFrs,
            "dossier"             => $tabDossier,
            "tableau_pj"          => $tabTypePj,
            "ordre"               => $ordre,
            "docAtt"              => $docAtt,
            "modifDocFourniss"    => true,
            "lock_titre"          => true,
            "dateDuJours"         => date('Ymd'),
            'titre_button'        => $trad->t('Modifier'),
            
            'path'                => $path,
            'codeDemande'         => $codeDemande,
            'demandeWithOutCode'  => $demandeWithOutCode,
            'pathEnregistrement'  => $_SERVER['REQUEST_URI'],
            'titrePOST'           => $titreURL,
        ]);
    }
}
