<?php
namespace Modules\Index\Controller;

use Entity\Model\Langues;
use Helpers\Cache\Cache;
use Helpers\Cache\OPCache;
use Helpers\Session\ParseBase1;
use Helpers\Trad\Trad;
use Skeleton\Controller\Controller;

class CacheClearController extends Controller
{
    public function suppressionCacheAction() :string
    {
        $cache = new Cache;
        $cache->clear();

        $cache = $this->getContainer()->get(OPCache::class);
        $cache->clear();

        return 'O';
    }

    public function suppressionCacheUserAction() : bool
    {
        $type = $this->request->getAttribute('type');

        $parsebase1 = new ParseBase1();

        if (!\extension_loaded('apcu')) {
            return true;
        }
        
        $cache = new Cache();
        if ($type) {
            switch ($type) {
                case 'PARAM':
                    if ($cache->get('PARAM'.$parsebase1->getBroker())) {
                        $cache->delete('PARAM'.$parsebase1->getBroker());
                    }
                    break;
                
                default:
                    if ($cache->get($type.$parsebase1->getBroker())) {
                        $cache->delete($type.$parsebase1->getBroker());
                    }
                    
                    if ((new Langues($this->pdo))->find($type)) {
                        $trad = $this->getTranslationService();
                        if ($trad instanceof Trad) {
                            $trad->setLang($type)->deleteCache();
                        }
                    }
                    break;
            }
        } else {
            $langues = new Langues($this->pdo);

            $trad = $this->getTranslationService();
            if ($trad instanceof Trad) {
                foreach ($langues->fetchAll() as $langue) {
                    $trad->setLang($langue['COD_LNG']);
                    $trad->deleteCache();
                }
            }
            
            if ($cache->get('PARAM'.$parsebase1->getBroker())) {
                $cache->delete('PARAM'.$parsebase1->getBroker());
            }

            $cache = $this->getContainer()->get(OPCache::class);
            $cache->clear();
        }
        
        return true;
    }
}
