<?php

namespace Modules\RechercheArticles\Service;

use Helpers\Outil\Outils;
use Helpers\Outil\Sql;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Repository\PanierLigne;
use Modules\Panier\Service\RequeteArticle;
use Modules\RechercheArticles\Repository\Recherche;
use Entity\Model\Centre;
use Entity\Model\OxaUserCnt;
use Helpers\Fichier\Fichier;
use Modules\Ajax\Repository\Listes;
use Skeleton\Router;
use Helpers\Session\ParseBase1;

class OutilRechercheService
{
    
    /**
     * @var array<mixed>
     */
    private $cacheRemise;

    /**
     * @var null|RequeteArticle
     */
    private $requeteArticle;

    /**
     *
     * @var \PDO
     */
    protected $pdo;

    /**
     *
     * @param \PDO $pdo
     */
    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
        $this->requeteArticle = null;
    }

    /**
     * @param array<mixed> $infoPanier
     */
    public function getCentreRecherche($infoPanier = []) : string
    {
        if (!$infoPanier) {
            $panierEntete = new PanierEntete($this->pdo);
            $infoPanier = $panierEntete->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);
        }

        $paramCentre = Sql::paravrac($this->pdo, 'OXAPROC', 'ZGEO_SUR_CTR_EMETTEUR');
        
        if ($paramCentre == 'O') {
            $centre = ($infoPanier['CENTRE_EMETTEUR']??'')? $infoPanier['CENTRE_EMETTEUR']:($_SESSION['Session_CodeCtrEmetteur']??'');
        } else {
            $centre = ($infoPanier['LIV_CTR']??'')? $infoPanier['LIV_CTR']:($_SESSION['Session_CodeCtrLivraison']??'');
        }

        return $centre;
    }

    public function asynchroneCalculRayon(Router$router) : void
    {
        $ch = curl_init();
            
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
        curl_setopt($ch, CURLOPT_URL, Outils::getRootUrl(true) . $router->generateUri('RechercheArticles.RechercheArticles.asynchroneRayon', ['idSession' => session_id()]));

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    

        session_write_close();
        curl_exec($ch);
        
        curl_close($ch);
    }

    /**
     * @param string $centre
     * @return array<string>
     */
    public function getZoneGeoCentre(string $centre) : array
    {
        $liste = new Listes($this->pdo);
        $listeZoneGeoCentre = $liste->listeZoneGeoCentre($centre);
        
        return array_column($listeZoneGeoCentre, 'zoneGeo');
    }

    public function getAutoCompletActif() : bool
    {
        $param = Sql::paravrac($this->pdo, 'OXAPROC', 'RECH_INCREMENTALE_ART');
        if ($param == 'O') {
            $oxaUserCnt = new OxaUserCnt($this->pdo);
            $paramUser = $oxaUserCnt->find([
                'COD_USR' => $_SESSION["Session_Login"],
                'COD_CHAMP' => 'AUTOCOMPLETION',
                'COD_TYPE' => 'RECHERCHE',
            ]);

            if (($paramUser['VALEUR']??'1') == '1') {
                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    /**
     * @param array<mixed> $infoPanier
     * @return array<mixed>
     */
    public function generateRayon(\PDO $pdoOxaFT, $infoPanier = [], bool $init = false)
    {
        $user = $_SESSION["Session_Login"];
        $outilRechercheService = new OutilRechercheService($this->pdo);
        $centre = $outilRechercheService->getCentreRecherche($infoPanier);
        $langue = $_SESSION['Session_Langue'];
        
        
        $centreRepo = new Centre($this->pdo);
        $centreSite = $centreRepo->find($centre);
        $siteStock = $centreSite['SITSTOCK']??'';
        
        $keySession = $langue.'|'.$centre.'|'.$siteStock;
        $recherche = new Recherche($this->pdo);
        
        if (isset($_SESSION['ARBORAYON'][$keySession]) && !$init) {
            $listeTMP = $_SESSION['ARBORAYON'][$keySession];
            return $_SESSION['ARBORAYON'][$keySession]['return'] ?? [];
        } else {
            $listeRayonGen = [];
            if ($_SESSION['GLOB_AuthLigneGenerique'] || $_SESSION['GLOB_AuthLigneSFamille']) {
                $listeRayonGen = $recherche->getRayonGenUser($pdoOxaFT, $user, $langue);
            }
            
            $listeRayon = $recherche->getRayonUser($pdoOxaFT, $user, $centre, $siteStock);
    
            $listeTMP = [];
            foreach ($listeRayonGen as $rayon) {
                $listeTMP[$rayon['ARBORAYON']] = $rayon['ARBORAYON'];
            }
    
            foreach ($listeRayon as $rayon) {
                $listeTMP[$rayon['ARBORAYON']] = $rayon['ARBORAYON'];
            }

            $_SESSION['ARBORAYON'][$keySession] = $listeTMP;
        }

        // $implode = "'".implode("','", $listeTMP)."'";
        $listeRayonTmp = $_SESSION['ARBORAYON'][$keySession]['return'] = $recherche->getListeRayon($listeTMP);
        
        return $listeRayonTmp;
    }

    /**
     *
     * @param string $parent
     * @param array<mixed> $array
     * @return array<mixed>
     */
    public function triRayon($parent, $array)
    {
    
        $result = array();
        foreach ($array as $noeud) {
            if ($parent == trim($noeud['RAYPERE'])) {
                $result[] = array(
                    'id'        => $noeud['IDRAYON'],
                    'text'      => $noeud['LIBRAYON'],
                    'nodes'     => $this->triRayon($noeud['IDRAYON'], $array),
                    'color'     => $noeud['RAYCOULEUR'],
                    'click'     => Sql::boolSql($noeud['AUTHCLIC']),
                    'ctc_nom'   =>  $noeud['NOM'],
                    'ctc_tel'   =>  $noeud['TEL'],
                    'detail'    => $noeud['CONTMEMO']
                );
            }
        }
        return $result;
    }


    public function initRequeteArticle(\PDO $pdoOxaFT) : void
    {
        $panierEntete = new PanierEntete($this->pdo);
        $infoPanier = $panierEntete->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);

        $this->requeteArticle = new RequeteArticle($this->pdo, $pdoOxaFT, $_SESSION["Session_Login"], $infoPanier['LIV_CTR'], $infoPanier['CENTRE_EMETTEUR']);
    }

    /**
     * @param array<mixed> $article
     * @return void
     */
    public function majRecord(&$article, \PDO $pdoOxaFT, bool $getInfoRemise = true)
    {
        if ($article) {
            if (isset($article['PUNCHOUT'])) {
                $article['PUNCHOUT']        = ($article['PUNCHOUT'] == 'N' || $article['PUNCHOUT'] == '') ? false:$article['PUNCHOUT'];
            } else {
                $article['PUNCHOUT']        = false;
            }
            
            $article['FICHTECH']        = ($article['FICHTECH']??'')        == 'O'? true:false;
            $article['ARTASSOCIE']      = ($article['ARTASSOCIE']??'')      == 'O'? true:false;
            $article['MULTIIMAGE']      = ($article['MULTIIMAGE']??'')      == 'O'? true:false;
            $article['PRIXDEGRESSIF']   = ($article['PRIXDEGRESSIF']??'')   == 'O'? true:false;
            $article['RECEP_AUTO']      = ($article['RECEP_AUTO']??'')      == 'O'? true:false;
            $article['NONRECEPT']       = ($article['NONRECEPT']??'')       == 'O'? true:false;
            $article['ARTFRAISPORT']    = ($article['ARTFRAISPORT']??'')    == 'O'? true:false;

            $article['COD_GRP'] = $article['REGRFOUR']??'';
            $article['COD_DEV'] = $article['DEVISE']??'';
            /* Gestion de l'image de l'article */
            if ($article['IMGART']??null) {
                if (stripos($article['IMGART'], 'http') === 0 || mb_substr($article['IMGART'], 0, 2) == '\\\\') {
                    $article['IMGART'] = Fichier::updateImageFromSource($article['IMGART']);
                } else {
                    if ($article['TYPIMAGE'] == 'U') {
                        $article['IMGART'] = Fichier::updateImageFromSource($article['IMGART'], $article['TYPIMAGE']);
                    } else {
                        $article['IMGART'] = Fichier::updateImageFromSource((new ParseBase1())->getPath()->Imgart.$article['IMGART']);
                    }
                }
            }

            $article['RAYON'] = [
                $article['RAYON1']??'',
                $article['RAYON2']??'',
                $article['RAYON3']??'',
                $article['RAYON4']??'',
                $article['RAYON5']??''
            ];

            $article['flg_cde'] = (($article['AUTOSTD']??null) > 0 ? 1 : 0);
            $article['IS_AUTH_CDE_OXAPROC'] = (($article['AUTOSTD']??null) > 0 ? 1 : 0);
            
            $article['is_multi_frs'] = 0;

            $article['PX_ART_INIT'] = $article['PX_ART'];

            if ($article['IDLIGNE']??null) {
                $panierLigne = new PanierLigne($this->pdo);
                $listeCarac = $panierLigne->getCaractInfoFromIdLigne($article['IDLIGNE']);

                foreach ($listeCarac as &$carac) {
                    if ($carac['TYP_CAR'] == 'U') {
                        if (strpos($carac['VAL_CAR'], 'www.') === 0) {
                            $carac['VAL_CAR'] = 'http://'.$carac['VAL_CAR'];
                        } elseif (strpos($carac['VAL_CAR'], 'http') === false) {
                            $carac['chargeDocument'] = ['emplacement' => 'cata', 'urlFichier' => str_replace('/', 'debut---slash---fin', $carac['VAL_CAR'])];
                        }
                    }
                }

                $article['CATCARACT'] = $listeCarac;
            }
            
            if ($getInfoRemise && $article['TYPECATA'] == 'M') {
                if (!$this->requeteArticle) {
                    $this->initRequeteArticle($pdoOxaFT);
                }
                
                $keyCache = ($article['ID_CAT']??'').'|'.($article['COD_FAB']??'').'|'.($article['COD_GAM']??'');
                if (isset($this->cacheRemise[$keyCache])) {
                    $listeRemise = $this->cacheRemise[$keyCache];
                } else {
                    $listeRemise = $this->requeteArticle->getAllFrsAndTxForArtCatRemise($article['ID_CAT']??'', $article['COD_FAB']??'', $article['COD_GAM']??'', 'top 1');
                    $this->cacheRemise[$keyCache] = $listeRemise;
                }
                
                foreach ($listeRemise as $remise) {
                    if ($remise['CODEFOUR'] && $remise['REMGAM']) {
                        $article['COD_FOURN'] = $remise['CODEFOUR']; // On met le code fournisseur à jour
                        $article['RS_FOURN'] = (is_null($remise['ENSCOMM']) || $remise['ENSCOMM'] == '') ? $remise['RS'] : $remise['ENSCOMM'];
                        $article['CPOSTAL'] = $remise['CPOSTAL'];
                        $article['VILLE1'] = $remise['VILLE1'];
                        $article['REMGAM'] = $remise['REMGAM'];
                        $article['PX_ART'] = $article['PX_ART'] * (1 - ($remise['REMGAM'] / 100));
                        
                        $article['PX_ART_INIT'] = $article['PX_ART'];
                        $article['TYPECATA'] = 'M';
                        $article['is_multi_frs'] = 1;
                    }
                }
            }

            $article['PU'] = $article['PX_ART'];
        }
    }

    /**
     * @param array<mixed> $article
     * @return void
     */
    public function majRecordGen(&$article)
    {
        if ($article) {
            $article['COD_ART']     = $article['CODE_ART'];
            $article['COD_SFAM']    = $article['SSFAM'];
            $article['DES_ART']     = $article['DESIGN'];
            $article['DES_COMP']    = $article['DESIGNLG'];
            $article['LIB_SFAM']    = $article['DESIGN'];

            $article['COD_UNIT']    = $article['UNITE'];
            $article['COD_GAM']     = '';
            $article['PX_ART']      = '';
            $article['ID_CAT']      = '';
            $article['COD_FAB']     = '';
            $article['CONDITNT']    = '';
            $article['TXTCOND']     = '';
        }
    }

    /**
     * @param array<mixed> $post
     * @param array<mixed> $parametrage
     */
    public function changeModeCooki($post, &$parametrage) : void
    {
        if (isset($post['changeMode'])) {
            $_SESSION['MODE_AFFICHAGE_ARTICLE'] = $post['changeMode'];
            $arr_cookie_options = array ('expires' => time() + 60 * 60 * 24 * 365 * 10,);
    
            if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
                $arr_cookie_options['samesite'] = 'None';
                $arr_cookie_options['secure']   = true;
                $arr_cookie_options['httponly'] = true;
            }
            setcookie('MODE_AFFICHAGE_ARTICLE', $post['changeMode'], $arr_cookie_options);
            $parametrage['MODE_AFFICHAGE_ARTICLE'] = $post['changeMode'];
        }
    }
}
