<?php
namespace Helpers\Trad;

use Helpers\Environnement\Recette\Traduction;

class TradRecette extends Trad
{
    public function t(string $term) :string
    {
        if (isset($this->bufferTrad[$term])) {
            return 't| ' . $this->bufferTrad[$term];
        }

        $mapTrad = [];
        
        // Note : wincache does not handle null for missing key, intead an entry with an empty string is created
        // and this is why we must use has() before get
        if ($this->_cache->has($this->_cacheKeyPrefix)) {
            $mapTrad = $this->getMapTradCache();
        }
        
        $trad = $mapTrad[$term] ?? null;
        
        // Case : retrieve from cache
        if ($trad !== null) {
            $this->setBuffer($term, $trad);
            return 't| ' . $trad;
        }

        // Get from DB
        $row = Traduction::getTradByTerm(
            $this->_pdo,
            $this->getProdCode(),
            $this->getLangCode(),
            $term
        );
        
        // Case : term does not exit in DB
        if ($row === false) {
            $_SESSION['trash']['TRAD-ABS-FOR-NONREG'][] = $term;
            return "ABS| '".$term."'";
        }
        if (is_array($row) && !empty($row['TRAD'])) {
            $trad = $row['TRAD'];
        } else {
            $trad = $term;
        }

        // Update cache
        $mapTrad[ $term ] = $trad;
        $this->setMapTradCache($mapTrad);
        
        return 't| ' . $trad;
    }
}
