<?php
namespace Modules\Fournisseur\Controller;

use API\Partenaire\IFournissDocExt;
use Helpers\Ariane\Ariane;
use Modules\Fournisseur\MenuContextuel\DocFournisseurMenuContextuel;
use Modules\GlobalApplication\Repository\LicenceOxalys;
use Skeleton\Controller\Controller;
use Entity\Model\Paravrac;
use Entity\Model\DocCat;
use Entity\Model\Fourniss;
use Helpers\Ariane\ArianeSub;
use API\Hiveo\Hiveo;
use API\Eattestations\Eattestations;
use Modules\Fournisseur\Repository\DocAtt;
use Modules\GlobalApplication\Repository\Workflow;

class DocFournisseurController extends Controller
{
    /** Page document rattaches **/
    public function docRattacheAction()
    {
        $resultAPI = '';
        $post = $this->request->getParsedBody();
        $codeFrs = $this->request->getAttribute('id');
        $codeDemande=$this->request->getAttribute('codeDemande');
        
        $docAttRepo = new DocAtt($this->pdo);
        $trad = $this->getTranslationService();
        
        $demandeCreation = false;
        if ($codeDemande) {
            $workflow = new Workflow($this->pdo);
            $demande = $workflow->getInfoDemande('FOURNISS', $codeDemande);
            
            if ($demande['TYPE_DEMANDE']=='C') {
                $libelle = $demande['WDEN_LIBELLE_ENREG'];
                $codeDemande = $demande['CODE_DEMANDE'];
                $codePays = $docAttRepo->getCodePaysDemande($demande['CODE_DEMANDE'])['VALEUR_CHAMP'];
                
                $demandeCreation = true;
            }
        }

        $listPartnDocAtt =
            $this->getPartenaireService()
            ->listWithInterface(IFournissDocExt::class);
        
        if (!$demandeCreation) {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($codeFrs);

            if (empty($fournis)) {
                return $this->create404Response();
            }
            
            $codeDemande = null;
            $libelle = $fournis["RS"];
            $codePays = $fournis['CODE_PAYS'];
            
            foreach ($listPartnDocAtt as $partn) {
                $partn->preprocessDocAtt($fournis);
            }
        }
        
        /* Gestion Partenaire */
        $mapPartn = [];

        $fournis_ALG=false;
        $partenaireDocument = $docAttRepo->PartenaireALG($codeFrs)['CODEPARTENAIRE'] ?? '';
        if ((
                (new LicenceOxalys($this->pdo))->isActive('OXA360', 'M', 'ALG')
                || $_SESSION['Session_NumClient']=='0'
            ) && ! empty($partenaireDocument)
        ) {
            $fournis_ALG=true;
            $mapPartn['ALG'] = [
                'label' => 'Attestation Légale',
                'template' => '@Fournisseur/DocFournisseur/_rowDocAlg.twig',
            ];
        }
        
        /**
         * Commencement du conditionnement des differentes API
         */
        $repoPartenaire = new \Modules\API\APIExterne\Repository\Partenaire($this->pdo);

        $paramDico = new \Entity\Model\ParamDico($this->pdo);
        $resParamDico = $paramDico->find([
            'ID3' => $codeFrs,
            'TYPEDICO' => 'INVIT_PARTFOU'
        ]);
        
        $partenairePasValider= 0;

        $partenCodeList = $repoPartenaire->fournisseurListPartenaireConnectDoc($codeFrs);
        
        if (in_array('HIVEO', $partenCodeList)) {
            $Hiveo = new Hiveo($this->pdo);
            $siren = $fournis['NO_SIRET'];

            $resultAPI = $Hiveo->relationsDocument('FR-'.$siren);
            $fournis_ALG=true;
            $mapPartn['HIVEO'] = [
                'label' => 'Hiveo',
                'template' => '@Fournisseur/DocFournisseur/_rowDocHiveo.twig',
            ];
        } elseif ($partenaireDocument =='HIVEO' && ($resParamDico['ALPHA2'] ?? null) == 'E') {
            $partenairePasValider= 1;
        }

        if (in_array('EAT', $partenCodeList) && $repoPartenaire->countConcordance('EAT')) {
            $resultAPI = [];
            $eattestation = new Eattestations($this->pdo);
            $resultAPITMP = $eattestation->getDossierBySiret($fournis['NO_SIRET']);
            
            if (isset($resultAPITMP['content'][0]['documents'])) {
                $contentTMP = $resultAPITMP['content'][0]['documents'];
            } elseif (isset($resultAPITMP['content']['documents'])) {
                $contentTMP = $resultAPITMP['content']['documents'];
            } else {
                $contentTMP = [];
            }
            
            foreach ($contentTMP as $API) {
                if ($API['present']) {
                    $resultAPI[$API['documentCode']]['state']['validityEnd'] = $API['evidences'][0]['expirationDate'];
                    $resultAPI[$API['documentCode']]['state']['validityStart'] = $API['evidences'][0]['uploadDate'];
                    $resultAPI[$API['documentCode']]['documentId'] = $API['documentId'];
                    $resultAPI[$API['documentCode']]['dossierId'] = $API['dossierId'];
                    $resultAPI[$API['documentCode']]['fileId'] = $API['evidences'][0]['id'];
                    $resultAPI[$API['documentCode']]['revisionId'] = $API['evidences'][0]['id'];
                }
            }

            $fournis_ALG=true;
            $mapPartn['EAT'] = [
                'label' => 'e-Attestation',
                'template' => '@Fournisseur/DocFournisseur/_rowDocEAttestation.twig',
            ];
        } elseif ($partenaireDocument =='EAT' && isset($resParamDico['ALPHA2']) && $resParamDico['EAT'] == 'E') {
            $partenairePasValider= 1;
        }

        /* ***************************************** */
        
        /* parametre pour le formulaire */
        $paravra = new Paravrac($this->pdo);

        $tabDossier = array_column(
            (new DocCat($this->pdo))->findAll(['CODE_TABLE' => 'FOURNISS']),
            'LIBELLE_CAT',
            'CODE_CAT'
        );
        $tabDossier["Autre"] = $trad->t('Autre');
        
        /* Liste des documents attaché */
        $listDocAtt = $docAttRepo->listForFourniss(
            $demandeCreation ? 'WFT_DEM_ENT' : 'FOURNISS',
            $demandeCreation ? $codeDemande : $codeFrs,
            $post
        );

        list(,$delaiRel) = explode("|", $paravra->getValue('PARAMGEN', 'FOURN_DOCRAT_DELAIRELANCE'));
        foreach ($listDocAtt as &$docAtt) {
            if ($docAtt["DT_VALID"]==0) {
                continue;
            }

            
            /**
             * Commencement du conditionnement des differentes API
             */
            switch ($docAtt['CodePartenaire']) {
                case 'HIVEO':
                    $matching = $docAtt['Matching'];
                    $docAtt["DT_PARUT"] = Hiveo::convertDateToSql(
                        $resultAPI[$matching]['state']['validityStart'] ?? $docAtt["DT_PARUT"]
                    );
                    $docAtt["DT_VALID"] = Hiveo::convertDateToSql(
                        $resultAPI[$matching]['state']['validityEnd'] ?? $docAtt["DT_VALID"]
                    );
                
                
                    $docAtt["relance"] = $docAtt["DT_VALID"];
                    if (isset($resultAPI[ $docAtt['Matching'] ]['state']['validityEnd'])) {
                        if ($docAtt["DT_PARUT"]!='00000000') {
                            $docAtt["NOM_FIC"] = 'HiveoAPI';
                        } else {
                            $docAtt["NOM_FIC"] = '';
                        }

                        $docAtt["DOC_INUTILE"] = '0';
                    }
                    break;
                default:
                    $docAtt["relance"] = '00000000';
                    if ($docAtt["DT_VALID"] != '00000000') {
                        $date = strtotime($docAtt["DT_VALID"]) - (intval($delaiRel) * 3600 * 24);
                        $docAtt["relance"] = date('Ymd', $date);
                    }
            }
        }

        if (str_contains(Ariane::getBackPath(), 'Consultation')) {
            Ariane::generate(
                3,
                $trad->t('Documents rattachés')
                . ArianeSub::generateDocAttImage(
                    $this->contenaire->get('baseUrl'),
                    $partenCodeList
                ),
                $post,
                null,
                $this->router->generateUri(
                    'Fournisseur.DocFournisseur.docRattache',
                    ['id' => $codeFrs]
                    + ($codeDemande ? [
                    'codeDemande' => $codeDemande,
                    ] : [])
                )
            );
            $menuActive = $_SESSION['typeMenu'] == 'P2P'? 'eproc':'Consultations';
            $menuLeft = 'gestionAO';
            $mainTitle = $trad->t('Consultations');
            $subTitle = $trad->t('Documents rattachés du fournisseur');
        } else {
            $menuActive = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            $mainTitle = $trad->t('Fournisseurs');
            $subTitle = $trad->t('Fournisseur');
            ArianeSub::generate(
                0,
                1,
                $trad->t('Documents rattachés')
                    . ArianeSub::generateDocAttImage(
                        $this->contenaire->get('baseUrl'),
                        $partenCodeList
                    ),
                $this->router->generateUri(
                    'Fournisseur.DocFournisseur.docRattache',
                    ['id' => $codeFrs]
                    + ($codeDemande ? [
                        'codeDemande' => $codeDemande,
                    ] : [])
                ),
                1,
                $post
            );
        }


        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($listDocAtt, 0, $post, $this->renderer);
        
        $codeEntity = $demandeCreation ? $codeDemande : $codeFrs ;

        $menuContextuel = new DocFournisseurMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($listDocAtt as &$doc) {
            $doc['menuContextuel'] = $menuContextuel->generate(
                $doc,
                $codeEntity,
                $fournis_ALG
            );
        }
        unset($doc);

        
        // Post-processing Partenaire
        foreach ($listPartnDocAtt as $partn) {
            $listDocAtt = $partn->processListDocAtt($codeFrs, $listDocAtt);
            $mapPartn[ $partn->getCode() ] = [
                'label' => $partn->getLabel(),
                'template' => $partn->getDocAttTemplate(),
            ];
        }

        return $this->renderer->render('@Fournisseur/DocFournisseur/index', [
            'menuActive'              => $menuActive,
            'menuLeft'                => $menuLeft,
            'mainTitle'               => $mainTitle,
            'subTitle'                => $subTitle,
            "code_entity"             => $codeEntity,
            "code_fournisseur"        => $codeFrs,
            "libelle_fournisseur"     => $libelle??'',
            "siret"                   => $fournis['NO_SIRET']??'',
            "docAtts"                 => $listDocAtt,
            "date"                    => date('Ymd'),
            "dossier"                 => $tabDossier,
            "gestionALG"              => $fournis_ALG,
            "post"                    => $post,
            'infoPagination'          => $infopagination,
            'partenaireDocument'      => $partenaireDocument,
            'resultAPI'               => $resultAPI,
            'demandeActif'            => $codeDemande? true:false,
            'codeDemande'             => $codeDemande,
            'partenairePasValider'    => $partenairePasValider,
            'mapPartn'                => $mapPartn,
        ]);
    }
}
