<?php

namespace Modules\RechercheArticles\Repository;

use Entity\Model\Articles;
use Entity\Model\SsFamFou;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\QueryBuilder\AbsRepository;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Service\PanierService;

class Article extends AbsRepository
{
    /**
     * rqGetListePrixDegressifByArt
     * @return array<mixed>
     */
    public function getPrixDegressif(string $provenance, string $id_cat, string $id_ligne_cat, string $code_art, string $qte = '')
    {
        $top = '';
        if ($qte != null) {
            $top = " top 1";
        }
        $arrayReq = [];

        $req = " select 
                   $top RQTECAT.IDCAT, RQTECAT.IDVERCATA, RQTECAT.IDLIGNE, RQTECAT.COD_ART, RQTECAT.QTETRANCHE, RQTECAT.REMQTE, RQTECAT.PRIXNET 
                from RQTECAT with(nolock) 
                where 1=1 ";

        // Si l'articl est du type catalogue alors on rehcerche les prix degressif selon l'id catalogue et l'id de la ligne catalogue
        if ($provenance == 'CAT') {
            $req .= " and IDCAT = :idCat and IDLIGNE = :idLigne ";

            $arrayReq[':idCat'] = $id_cat;
            $arrayReq[':idLigne'] = $id_ligne_cat;
        } elseif ($provenance == 'HAP') {
            // S'il s'agit d'un article Haplus alors on le sélectionne à partir de son code article
            $req .= " and COD_ART = :codeArt";
            $arrayReq[':codeArt'] = $code_art;
        }
        
        if ($qte != null) {
            $req .= " and RQTECAT.QTETRANCHE <= :qte ";
            $arrayReq[':qte'] = $qte;
            $req .= ' order by RQTECAT.QTETRANCHE desc ';
        } else {
            $req .= ' order by RQTECAT.QTETRANCHE';
        }

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

    /**
     * @return array<mixed>
     */
    public function getListeDocArticle(string $artcie, string $typeFt = '')
    {
        $req = " select 
                    DOC_ATT.COPIE,DOC_ATT.TYPE_FT,DOC_ATT.TITRE, DOC_ATT.NOM_ORI, DOC_ATT.AUTEUR, HASTUTIL.NOM,
                    DOC_ATT.CENTRE, DOC_ATT.DT_PARUT, DOC_ATT.DT_VALID, DOC_ATT.NOM_FIC, DOC_ATT.NO_ORDRE, DOC_ATT.COD_ENR,
                    CENTRE.RAIS_SOC, MEMOS.NODEMEMO,CAST(MEMOS.CONTMEMO AS TEXT) AS CONTMEMO
            from DOC_ATT with (nolock)
            left outer join MEMOS    with(nolock) on MEMOS.NODEMEMO = DOC_ATT.NM_COMM
            left outer join HASTUTIL with(nolock) on HASTUTIL.CODE  = DOC_ATT.AUTEUR
            left outer join CENTRE with(nolock) on CENTRE.CODE_CTR  = DOC_ATT.CENTRE
            where NO_DA='ARTICLES'
            AND   COD_ENR = :codeArt
            AND   (DT_VALID = '00000000' OR DT_VALID >= '".date('Ymd')."') ";
        $arrayReq[':codeArt'] = $artcie;

        if ($typeFt) {
            if ($typeFt == 'U') {
                $req .= ' AND (TYPE_FT = \'U\' OR COPIE = 0x54) ';
            } else {
                $req .= " AND TYPE_FT = :typeFT ";
                $arrayReq[':typeFT'] = $typeFt;
            }
        }

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

    /**
     * @return array<mixed>
     */
    public function isArticleHaPlus(string $codeArt, bool $clauseSsFam = false)
    {
        $req = "SELECT ARTICLES.*, FABRICAN.AUTOCC 
                FROM ARTICLES WITH (NOLOCK)
                LEFT OUTER JOIN FABRICAN WITH (NOLOCK) ON FABRICAN.CODE = ARTICLES.CODEFAB
                WHERE ARTICLES.CODE_ART = :codeArt";


        $arrayReq = [
            ':codeArt' => $codeArt,
        ];

        if ($clauseSsFam) {
            $codeFrsRegul = PanierService::getFrsRegul(null, $this->pdo);

    
            if (isset($_SESSION['PANIER_FOURNISSEUR_IMPOSE']) && trim($_SESSION['PANIER_FOURNISSEUR_IMPOSE'])  != '') {
                $codeFrsRegul = $_SESSION['PANIER_FOURNISSEUR_IMPOSE'];
            }
    
            if (!$codeFrsRegul) {
                $param = sql::paravrac($this->pdo, 'OXAPROC', 'ARTGEN_LISTEFOURN_LIMITEE');
                $droit = Roles::droitsUtilisateur($this->pdo, 'OX_AG_LF_L');
                
                if ($param == 'O' && !$droit) {
                    $limitationSsfam = '';
                    $ssFamFou = new SsFamFou($this->pdo);
    
                    // On récupère la liste des sous-familles liées au fournisseur
                    $listeSsFamilleTmp = $ssFamFou->findAll(['CODE_FOUR' => $codeFrsRegul]);
    
                    if ($listeSsFamilleTmp) {
                        $limitationSsfam .= " AND (
                            SSFAM in (SELECT distinct(CODE_SFAM) FROM SSFAMFOU with(nolock) where CODE_FOUR=:codeFou) 
                            or SSFAM not in (SELECT distinct(CODE_SFAM) FROM SSFAMFOU)
                        )";
                        
                        $arrayReq[':codeFou'] = $codeFrsRegul;
                    }
    

                    $req .= $limitationSsfam;
                }
            }
        }

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

    /**
     * @return array<mixed>
     */
    public function getInfoStock(string $codeArt, string $ctrLivraison)
    {
        $req = "select 
                    SSTOCKLO.QTE_PHYS, SSTOCKLO.QTE_RES, SSTOCKLO.QTE_INDIS, SSTOCKLO.QTE_TRF,
                    SSTOCKLO.QTE_REAP, SSTOCKLO.QTE_LIV, SSTOCKLO.QTE_ACHEM, 
                    SSTOCKLO.STK_PRO,SSTOCKLO.VAL_LOCAL,
                    SSTOCKLO.QTE_PREV, SARTICLE.STRATEG, SSTOCKLO.QTE_STSUR
                from SSTOCKLO with (nolock)
                left join SARTICLE with (nolock) on SARTICLE.CODE_ART = SSTOCKLO.CODE_ART
                left join CENTRE with (nolock) on CENTRE.SITSTOCK = SSTOCKLO.SITE
                where CODE_CTR = :ctrLivraison and SSTOCKLO.CODE_ART = :codeArt";

        $arrayReq = [
            ':codeArt' => $codeArt,
            ':ctrLivraison' => $ctrLivraison
        ];

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