<?php
namespace Modules\Fournisseur\Controller;

require_once 'application/helpers/downloadHelper.php';
use API\Provigis\ProvigisService;
use Entity\Model\FourPartenaireData;
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 Helpers\Outil\Sql;
use Helpers\Trad\Trad;
use Modules\Fournisseur\Repository\DocAtt;
use Modules\GlobalApplication\Repository\Workflow;

class DocFournisseurController extends Controller
{
    /** Page document rattaches **/
    public function docRattacheAction()
    {
        $partenaireDocument = '';
        $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;
            }
        }
        
        if (!$demandeCreation) {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($codeFrs);
            
            $codeDemande = null;
            $libelle = $fournis["RS"];
            $codePays = $fournis['CODE_PAYS'];
        }
        
        /* Gestion Partenaire */
        $fournis_ALG=false;
        $partenaireDocument = $docAttRepo->PartenaireALG($codeFrs)['CODEPARTENAIRE'] ?? '';
        $post['code_partenaire'] = $partenaireDocument;
        if ((
                (new LicenceOxalys($this->pdo))->isActive('OXA360', 'M', 'ALG')
                || $_SESSION['Session_NumClient']=='0'
            ) && ! empty($partenaireDocument)
        ) {
            $fournis_ALG=true;
        }
        
        /**
         * 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('password', $this->pdo);
            $siren = $fournis['NO_SIRET'];

            $resultAPI = $Hiveo->relationsDocument('FR-'.$siren);
            $fournis_ALG=true;
        } 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;
        } elseif ($partenaireDocument =='EAT' && isset($resParamDico['ALPHA2']) && $resParamDico['EAT'] == 'E') {
            $partenairePasValider= 1;
        }
        
        // Case : Provigis
        $mapProvigisDoc = [];
        if (in_array('PROVIGIS', $partenCodeList)) {
            // Request API Provigis & Update DB
            $mapProvigisDoc = $this->getProvigisDocAtt($codeFrs);
        }

        /* ***************************************** */
        
        /* parametre pour le formulaire */
        $paravra = new Paravrac($this->pdo);
        $paravra = $paravra->find([
            'TYPEPARV' => 'PARAMGEN',
            'CODEPARV' => 'FOURN_DOCRAT_DELAIRELANCE'
        ]);

        $dossier = (new DocCat($this->pdo))
            ->findAll(['CODE_TABLE' => 'FOURNISS']);
        $tabDossier = array_column($dossier, 'LIBELLE_CAT', 'CODE_CAT');
        $tabDossier["Autre"] = $trad->t('Autre');

        /* Liste des documents attaché */
        $listDocAtt = $docAttRepo->detail(
            $codeFrs,
            $codePays,
            $post,
            $codeDemande,
            $partenaireDocument
        );

        $paravra = explode("|", $paravra["LIB01PARV"]);
        foreach ($listDocAtt as &$docAtt) {
            if ($docAtt["DT_VALID"]==0) {
                continue;
            }
            
            /**
             * Commencement du conditionnement des differentes API
             */
            switch ($docAtt['ALPHA3']) {
                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;
                case 'PROVIGIS':
                    // Here NOM_FIC is a provigis identifier "provigis:{name}[:{id}]"
                    /** @phpstan-ignore-next-line */
                    $docAtt['ProvigisStatus'] = $mapProvigisDoc[ $docAtt['NOM_FIC'] ]->status;
                    break;
                default:
                    $dateDepartTimestamp = strtotime($docAtt["DT_VALID"]);
                    $date = $dateDepartTimestamp + ($paravra[1] * -3600 * 24);
                    $relance = date('Ymd', $date);
                    $docAtt["relance"] = $relance;
            }
        }

        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);
        
        if ($codeFrs=='noId') {
            $codeFrs = $codeDemande;
            $id = 'noId';
        }

        $menuContextuel = new DocFournisseurMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($listDocAtt as &$doc) {
            if ($doc['NO_ORDRE'] || $doc['NO_ORDRE'] == '0') {
                $noOrdre = $doc['NO_ORDRE'];
                $type = 'D';
            } else {
                $noOrdre = trim($doc['ORDRE_PARAM']);
                $type = 'P';
            }

            $doc['menuContextuel'] = $menuContextuel->generate($codeFrs, $doc['CODE_CAT'], $doc['NO_ORDRE'], $doc['TITRE'], Sql::boolSql($doc['DOC_INUTILE']), $noOrdre, $type, $doc['ALPHA3'], $fournis_ALG);
        }

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

    /**
     * @return array<object>
     */
    private function getProvigisDocAtt(string $fournissCode) :array
    {
        $listDoc = $this->getProvigisService()->getFourDocAtt($fournissCode);
        if ($listDoc === null) {
            return [];
        }
        return array_column($listDoc, null, 'tmpId');
    }

    private function getProvigisService() :ProvigisService
    {
        return $this->contenaire->get('ProvigisService');
    }
}
