<?php

namespace Modules\API\APIExterne\Repository;

use Entity\Model\FourPartenaireData;
use Helpers\Outil\Sql;
use Helpers\QueryBuilder\AbsRepository;

class Partenaire extends AbsRepository
{


    /**
     * getPartenaire
     * @param String $idFournisseur
     * @return Array<mixed>
     */
    public function getPartenaire(String $idFournisseur) : ?array
    {
         $req ="select CODE_FOU, CODEPARTENAIRE, DOC_LEGAUX, ACTIVITE, DATE_DEBUT_TRAITE from FOUR_PARTENAIRE_DATA with (nolock) where DOC_LEGAUX=0x54 and CODE_FOU=:idFournisseur";
         
        $arrayReq = [':idFournisseur' => $idFournisseur];

        return $this->fetchAssocAll($req, $arrayReq);
    }

    /**
     * fournisseurIsConnectActivite
     * @param String $idFournisseur
     * @param String $partenaire
     * @return array<mixed>
     */
    public function fournisseurIsConnectActivite(String $idFournisseur, String $partenaire) : ?array
    {
        $req ="select CODE_FOU, CODEPARTENAIRE, DOC_LEGAUX, ACTIVITE, DATE_DEBUT_TRAITE from FOUR_PARTENAIRE_DATA with (nolock) where ACTIVITE=0x54 and CODEPARTENAIRE=:partenaire and CODE_FOU=:idFournisseur";
         
        $arrayReq = [':idFournisseur' => $idFournisseur,'partenaire' => $partenaire];

        return $this->fetchAssocAll($req, $arrayReq);
    }

    /**
     * fournisseurListPartenaireConnectDoc
     * @param string $idFournisseur
     * @return array<string>
     */
    public function fournisseurListPartenaireConnectDoc(string $idFournisseur) :array
    {
        $param = [];
        foreach ($this->getListPartenaireCodeRequiringInvite() as $k => $v) {
            $param[':invt_'.$k] = $v;
        }

        $req ="SELECT CODEPARTENAIRE
            FROM FOUR_PARTENAIRE_DATA with (nolock) 
            LEFT JOIN PARAMDICO as InviteAccepted with (nolock) 
                ON InviteAccepted.TYPEDICO = 'INVIT_PARTFOU'
                AND InviteAccepted.ID3 = CODE_FOU 
                AND InviteAccepted.ALPHA2 = 'A' 
                AND InviteAccepted.ID1 = CODEPARTENAIRE
            WHERE DOC_LEGAUX = 0x54 
                AND CODE_FOU = :idFournisseur
                AND (
                    CODEPARTENAIRE NOT IN (".implode(', ', array_keys($param)).")
                    OR InviteAccepted.TYPEDICO IS NOT NULL
                )
            GROUP BY CODEPARTENAIRE";

        $arrayReq = $param + [
            'idFournisseur' => $idFournisseur,
        ];

        return array_column(
            $this->fetchAssocAll($req, $arrayReq),
            'CODEPARTENAIRE'
        );
    }

    /**
     * @return array<string>
     */
    public function getListPartenaireCodeRequiringInvite() :array
    {
        return ['HIVEO','EAT'];
    }

    /**
     * insertPartenaireDataActivite
     * @param string $idFournisseur
     * @param string $partenaire
     * @return void
     */
    public function insertPartenaireDataActivite(string $idFournisseur, string $partenaire) : void
    {
        (new FourPartenaireData($this->pdo))
            ->insertEntity(
                $idFournisseur,
                $partenaire,
                false,
                true
            );
    }

    /**
     * insertPartenaireDataDocument
     * @param string $idFournisseur
     * @param string $partenaire
     * @return void
     */
    public function insertPartenaireDataDocument(string $idFournisseur, string $partenaire) : void
    {
        (new FourPartenaireData($this->pdo))
            ->insertEntity(
                $idFournisseur,
                $partenaire,
                true,
                false
            );
    }

    /**
     * isPartenaireConnect
     * @param array<mixed> $partenaire
     * @return array<mixed>
     */
    public function isPartenaireConnect(array $partenaire)
    {
        /** Test de l'existance dans le cache */
        $winCacheResult = \Helpers\Cache\WinCache::surchargeGetUcache('Partenaire_'.$_SESSION['_brokernumber']);

        if ($winCacheResult === false
            || \Helpers\Cache\WinCache::variableTest()
        ) {
            $req =" SELECT TYPEDICO, count(LIB01DICO) as nbr 
                    FROM DILISPEC with (nolock) 
                    WHERE ";

            $i=0;
            $arrayReq = [];
            foreach ($partenaire as $value) {
                if ($i) {
                    $req .=" OR ";
                }
                $req .=" TYPEDICO = :partenaire".$i;
                $arrayReq[':partenaire'.$i] = $value;
                $i++;
            }
            
            $req .=" GROUP BY TYPEDICO";

            $result = $this->fetchAssocAll($req, $arrayReq);

            /** Mise en place de la variable dans le cache */
            \Helpers\Cache\WinCache::surchargeSetUcache('Partenaire_'.$_SESSION['_brokernumber'], $result);

            return $result;
        } else {
            return $winCacheResult;
        }
    }

    /**
     * @return array<mixed>
     */
    public function getListeIsPartenaireConnect()
    {
        $req =" select TYPEDICO, COUNT(*) count from DILISPEC with (nolock)
                where TYPEDICO in ('HIVEO', 'EAT', 'INFOLG', 'BVD', 'PROVIGIS')
                group by TYPEDICO";
         
        $arrayReq = [];

        $req = $this->pdo->prepare($req);
        $req->execute($arrayReq);
  
        $return = $req->fetchAll();

        if ($return) {
            return $return;
        } else {
            return [];
        }
    }
    
  
    /**
     * listeFournisseurPartenaire
     * @param String $partenaire
     * @param Bool $demandeInvit
     * @return Array<mixed>
     */
    public function listeFournisseurPartenaire(String $partenaire, Bool $demandeInvit = false)
    {
        $req ="select CODE_FOU from FOUR_PARTENAIRE_DATA f with(nolock)";
        if ($demandeInvit) {
            $req .=" join PARAMDICO p with(nolock) on p.ID3 = f.CODE_FOU AND TYPEDICO = 'INVIT_PARTFOU' AND ID1 = :partenaireInvit AND p.ALPHA2 = 'A' ";
        }
        $req .="where DOC_LEGAUX=0x54 and f.CODEPARTENAIRE=:partenaire";
         
        $arrayReq = [':partenaire' => $partenaire];
        if ($demandeInvit) {
            $arrayReq[':partenaireInvit'] = $partenaire;
        }

        return $this->fetchAssocAll($req, $arrayReq);
    }

    /**
     * listeFournisseurPartenaireDonnee
     * @param string $partenaire
     * @return array<array<string>>
     */
    public function listeFournisseurPartenaireDonnee(String $partenaire) :array
    {
        $req ="select CODE_FOU from FOUR_PARTENAIRE_DATA with (nolock) where ACTIVITE=0x54 and CODEPARTENAIRE=:partenaire";
        
        $arrayReq = [':partenaire' => $partenaire];

        return $this->fetchAssocAll($req, $arrayReq);
    }

    /**
     * concordance
     * @param string $partenaire
     * @return array<mixed>
     */
    public function concordance(string $partenaire) : ?array
    {
        $req ="SELECT
            p1.CODE_CATEGORIE as ALPHA1,
            p1.NUM_ORDRE as ALPHA2,
            p1.TITRE_DOC as LIBELLE,
            p2.ID1 Partenaire,
            p2.LIBELLE Corresp
        FROM LST_DOCS p1 with (nolock)
        JOIN PARAMDICO p2 with (nolock)
            ON p2.ID1=:partenaire AND p2.ID2=p1.CODE_DOC AND p2.TYPEDICO=:typeDoc";
        $arrayReq = [
            ':partenaire' => $partenaire,
            ':typeDoc' => 'DOCATTFNR_LSTDOCS_PARTNER'
        ];
  
        return $this->fetchAssocAll($req, $arrayReq);
    }


    /**
     * countConcordance
     * @param String $partenaire
     * @return String
     */
    public function countConcordance(String $partenaire) : string
    {
        $req ="select count(*) as countDoc   
        from LST_DOCS p1 with (nolock)
        inner join PARAMDICO p2 with (nolock) on p2.ID1=:partenaire and p2.ID2=p1.CODE_DOC and p2.TYPEDICO=:typeDoc";
         
        $arrayReq = [':partenaire' => $partenaire, ':typeDoc' => 'DOCATTFNR_LSTDOCS_PARTNER'];

        $req = $this->pdo->prepare($req);
        $req->execute($arrayReq);
  
        return $req->fetch()['countDoc'];
    }

    /**
     * relanceFournisseurHisto
     * @param String $idFournisseur
     * @param String $partenaire
     * @return Array<mixed>
     */
    public function relanceFournisseurHisto(String $idFournisseur, String  $partenaire = 'HIVEO') : ?array
    {
         $req ="select ID1, RAIS_SOC, ID3, ID4, LIBELLE as DATE, case when NOM is not null then NOM else 'BATCH' end as DEMANDEUR
         from PARAMDICO with (nolock) 
         left JOIN SOCIETE with (nolock) on SOCIETE.CODE_STE = ID2
         left JOIN HASTUTIL with (nolock) on HASTUTIL.CODE = ALPHA1
         where TYPEDICO = 'INVIT_PARTFOU' AND ID1 = :partenaire AND ID3= :idFournisseur
         ORDER BY ID4 DESC";
         
        $arrayReq = [':idFournisseur' => $idFournisseur, ':partenaire' => $partenaire];

        return $this->fetchAssocAll($req, $arrayReq);
    }
}
