<?php
namespace Modules\Fournisseur\Controller;

use API\Partenaire\IFournissDocExt;
use Entity\Model\LstDocs;
use GuzzleHttp\Psr7\Response;
use Helpers\Log\LogSysteme;
use Helpers\Outil\Sql;
use Skeleton\Controller\Controller;
use Modules\Fournisseur\Repository\DocAtt;
use Helpers\Fichier\Fichier;
use Entity\Model\Fourniss;
use Helpers\Session\ParseBase1;

class AjaxDocFournisseurController extends Controller
{
    /** Suppresion d'un document **/
    public function supprimerAction() : string
    {

        $id = $this->request->getAttribute('id');
        $noOrdre = $this->request->getAttribute('noOrdre');

        $docAttRepo = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $frsIsWF = $docAttRepo->fournissIsDemandeCreation($id);
        
        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($id);

        
        
        $trad = $this->getTranslationService();

        if ($fournis) {
            $code = $id;
            $refObjet = 'FOURNISS';
        } else {
            if ($frsIsWF) {
                $code = $frsIsWF['CODE_DEMANDE'];
                $refObjet = 'WFT_DEM_ENT';
            } else {
                $code = $id;
                $refObjet = 'WFT_DEM_ENT';
            }
        }

        $value=[
            "Langue" => $_SESSION['Session_Langue'],
            "refObjet" => $refObjet,
            "numOrdre" =>$noOrdre,
            "id" => $code,
        ];

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

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

        if ($reponseDocRat->Statut=="O") {
            $message =  $trad->t("Votre document a été supprimé");
        } else {
            $message =  $reponseDocRat->MsgErreur;
        }

        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'iconePopup' => 'information',
        ]);
    }

    /**  Déclarer sans objet un document **/
    public function sansObjetAction() : string
    {
        $codeFrs=$this->request->getAttribute('id');
        $noOrdre = $this->request->getAttribute('noOrdre');
        $cat = $this->request->getAttribute('cat');
        $post= $this->request->getParsedBody();

        $docAttRepo = new DocAtt($this->pdo);
        $frsIsWF = $docAttRepo->fournissIsDemandeCreation($codeFrs);
        
        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($codeFrs);
        
        if ($fournis) {
            $code = $codeFrs;
            $typeObjet = 'FOURNISS';
        } else {
            if ($frsIsWF) {
                $code = $frsIsWF['CODE_DEMANDE'];
                $typeObjet = 'WFT_DEM_ENT';
            } else {
                $code = $codeFrs;
                $typeObjet = 'WFT_DEM_ENT';
            }
        }
        
        $infoDoc = $docAttRepo->listForFourniss(
            'FOURNISS',
            $codeFrs,
            ['filter_equal_NUM_ORDRE' => $noOrdre],
        )[0];
        
        $value=[
            "codeFrs" => trim($code),
            "CATEGORIE" => trim($cat),
            "NO_ORDRE" => trim($noOrdre),
            "TITRE" => trim($infoDoc['TITRE']),
            'TypeObjet' => $typeObjet,
        ];


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

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

        
        
        $trad = $this->getTranslationService();

        if ($reponseSO->Statut=="O") {
            $message = $trad->t('Votre document a été déclaré sans objet');
        } else {
            $message = $reponseSO->MsgErreur;
        }

        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'iconePopup' => 'information',
        ]);
    }

    /** fonction permettent la relance (unitaire ou groupé) des documents **/
    public function relanceAction() : string
    {
        $codeFrs=$this->request->getAttribute('id');
        $post = $this->request->getParsedBody();

        // $hiveo = new Hiveo($this->pdo);
        // if($hiveo->fournisseurRattache($codeFrs))
        // {
        //     $mok = new Mok();
        //     $mok->organisationReminds();

        //     // ici il faut faire l'enregistrement
        // }

        $docAttRepo = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $frsIsWF = $docAttRepo->fournissIsDemandeCreation($codeFrs);
        
        $fournis = new Fourniss($this->pdo);
        $fournis = $fournis->find($codeFrs);
        
        if ($fournis) {
            $code = $codeFrs;
            $typeObjet = 'FOURNISS';
        } else {
            if ($frsIsWF) {
                $code = $frsIsWF['CODE_DEMANDE'];
                $typeObjet = 'WFT_DEM_ENT';
            } else {
                $code = $codeFrs;
                $typeObjet = 'WFT_DEM_ENT';
            }
        }
        
        $value=[
            "societe" => $_SESSION['Session_SocUsr'],
            "utilisateur" => $_SESSION['Session_Login'],
            "codeFrs" => $code,
            "NO_ORDRE" =>$post["NoOrdre"],
            "raison_relance" =>$post["message"],
            "TITRE" =>$post["titre"],
            'TypeObjet' => $typeObjet,
        ];
        
        $xmlResult = new \Modules\Fournisseur\WebService\DocFournisseur();
        $xmlResult= $xmlResult->relanceDocAtt($value);

        $reponseRelance = new \SimpleXMLElement($xmlResult->responseData);
        
        
        $trad = $this->getTranslationService();
        if ($reponseRelance->Statut=="O") {
            $message = $trad->t("Votre relance a bien été envoyée");
            $refresh=true;
        } else {
            $message = $reponseRelance->MsgErreur;
        }

        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'refresh' => $refresh??false,
            'form_refresh' => 'formulaireGeneral',
            'div_refresh' => 'documents_rattaches_fournisseur',
            'iconePopup' => 'information',
        ]);
    }

    /** retourne les ZIP des documents du fournisseur **/
    public function downloadAction() : string
    {
        $codeFrs=$this->request->getAttribute('id');

        $value=["codeFrs" => $codeFrs];
        $xmlResult = new \Modules\Fournisseur\WebService\DocFournisseur();
        $xmlResult= $xmlResult->DownloadDocAtt($value);

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

        $url = Fichier::URLDownload($reponse->ListeDoc->Doc->Fichier);

        $message = Fichier::UploadClient($url, $reponse->ListeDoc->Doc->Fichier);

        return $message;
    }

    /** retourne l'attestation en PDF **/
    public function downloadAttestationAction() : string
    {
        $codeFrs=$this->request->getAttribute('id');

        $value=["codeFrs" => $codeFrs];

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

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

        $url = Fichier::URLDownload($reponse->ListeDoc->Doc->Fichier);

        $message = Fichier::UploadClient($url, "Attestation_de_conformité_".date('dmY').'.pdf');
        return $message;
    }

    /** retourne le fichier **/
    public function downloadFichierAction() : Response
    {
        $codeFrs = $this->request->getAttribute('id');
        $ordre = $this->request->getAttribute('ordre');
        
        $fournis = (new Fourniss($this->pdo))->find($codeFrs);
        $isDem = !$fournis;

        $docAtt = (new DocAtt($this->pdo))->listForFourniss(
            $isDem ? 'WFT_DEM_ENT' : 'FOURNISS',
            $codeFrs,
            ['filter_equal_NO_ORDRE' => $ordre]
        )[0] ?? null;

        if (Sql::toBool($docAtt['GERE_PAR_PARTENAIRE'])) {
            $partn =
                $this->getPartenaireService()
                ->getByCode($docAtt['CodePartenaire']);
            if (! ($partn instanceof IFournissDocExt)) {
                LogSysteme::prefixErrorLog('Invalid partenaire config');
                return new Response(500, [], 'Invalid partenaire config');
            }
            return $partn->downloadDoc($codeFrs, $ordre);
        }

        $message = Fichier::UploadClient(
            (new ParseBase1())->getRep()->pj.$docAtt['NOM_FIC'],
            $docAtt['NOM_ORI']
        );
        // Expect Fichier::UploadClient to exit here
        return new Response(500, [], $message);
    }

    public function downloadFichierHistoAction() : string
    {
        $codeFrs = $this->request->getAttribute('id');
        $ordre = $this->request->getAttribute('ordre');
        
        $fournis = (new Fourniss($this->pdo))->find($codeFrs);
        
        if (!empty($fournis)) {
            $code = $codeFrs;
        } else {
            $frsIsWF =
                (new \Modules\Fournisseur\Repository\DocAtt($this->pdo))
                ->fournissIsDemandeCreation($codeFrs);
            if ($frsIsWF) {
                $code = $frsIsWF['CODE_DEMANDE'];
            } else {
                $code = $codeFrs;
            }
        }

        $docAtt = (new \Entity\Model\DocAttAnnexe($this->pdo))->find([
            'COD_TAB' => 'FOURNISS', // TODO : handle GRPFOU ?
            'COD_ENR' => $code,
            'NO_ORDRE' => $ordre,
        ]);
            
        return Fichier::UploadClient(
            (new ParseBase1())->getRep()->pj . $docAtt['NOM_FIC'],
            $docAtt['NOM_ORI']
        );
    }
}
