<?php

class ArticleSelect
{

    const MOT_CACHE = 'CACHE_COMPAR';

    private $cache = array();

    public function __construct()
    {
        $this->saveSession();
    }

    public static function restoreSession()
    {
        return unserializeSecure($_SESSION[ArticleSelect::MOT_CACHE]);
    }

    public function saveSession()
    {
        $_SESSION[ArticleSelect::MOT_CACHE] = serializeSecure($this);
    }

    public function isExiste($serialisation)
    {
        return array_key_exists($serialisation, $this->cache);
    }

    public function &getCache()
    {
        return $this->cache;
    }

    public function erase()
    {
        $this->cache = array();
        $this->saveSession();
    }

    /**
     *
     * @param string $idCat
     * @param string $serialisation
     * @param string $zoneEcran
     * @param string $valeur
     * @return boolean
     */
    public function set($name, $idCat, $serialisation, $zoneEcran, $valeur)
    {
        if ($valeur == '') {
            if ($this->isExiste($serialisation)) {
                unset($this->cache[$serialisation]);
                $this->saveSession();
            }
            return true;
        } else if (count($this->cache) > 3)
            Affichage::messageJS(Trad('Vous devez sélectionner au maximum 4 articles afin de pouvoir lancer le comparateur'));
        else if ($listeArt = unserializeSecure($_SESSION['CACHE_CATALOGUE'])) {
            $this->cache[$serialisation] = array(
                'zone' => $zoneEcran,
                'ID_CAT' => $idCat,
                'name' => $name,
                'info_art' => $listeArt['CAT'][$serialisation]
            );
            $this->saveSession();
            return true;
        }
        
        return false;
    }

    public function &getXmlArray()
    {
        $array = array();
        $array['infoBoxComparateur']['nbArtCmp'] = count($this->getCache());
        foreach ($this->cache as $serialization => & $data) {
            $array['infoBoxComparateur']['listeArtCmp'][] = array(
                '!texte' => $data['info_art']['DES_ART'],
                '!onclick' => "Traite('recherche_article.php?OBJECT=SUP_CMP_{$serialization}&SUP_CMP_{$serialization}={$data['name']}',null);"
            );
        }
        return $array;
    }

    public function afficheInfo()
    {
        $htmlEngine = new GenXslt();
        
        echo 'getObj("id_compar_info_art").innerHTML="', HttpReplacePointeur($htmlEngine->XslHtml('application/xsl/info_compararetur.xsl', $this->getXmlArray())), '";';
    }
}