<?php
namespace Modules\GlobalApplication\Controller;

use Helpers\Outil\Sql;
use Helpers\QueryBuilder\QueryBuilder;
use Modules\Tables\Controller\FirmTableReferenceController;
use Skeleton\Controller\Controller;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Trad\Trad;

/**
 * Fournisseur
 * Groupement Fournisseur
 * Articles
 *
 */
/*
 * TODO MSA : A DEPLACER DANS AJAX
*/
class ExportController extends Controller
{
    public function popupExportAction() : string
    {
        $post = $this->request->getParsedBody();
        $idEntity = $this->request->getAttribute('entity');
        $entityPdo = $this->getEntityByKey($idEntity);
        $tab = $this->_exportGetTab($entityPdo);
        
        $primaryKey = $entityPdo->getPrimaryKey();

        if ($primaryKey) {
            $post['multiSelectexportOBLI1'] = $primaryKey;
            $tabObli = [$primaryKey];
        }
        return $this->renderer->render('@GlobalApplication/Popup/popupExport', [
            'pathExport' => $this->router->generateUri('GlobalApplication.export.export', ['entity' => $idEntity]),
            'formFilter' => $post['divCode'], // divCode contient le nom du formulaire a exporter
            'coloneExport' => $tab,
            'post' => $post,
            'tabObli' => $tabObli??[],
        ]);
    }

    public function exportAction() : string
    {
        $post = $this->request->getParsedBody();
        $idEntity = $this->request->getAttribute('entity');
        
        $arrayMultiSelect = array_filter($post, function ($k) {
            return stristr($k, 'multiSelect');
        }, ARRAY_FILTER_USE_KEY);

        $entityPdo = $this->getEntityByKey($idEntity);

        // Filter any unauthorized fields
        $arrayMultiSelect = array_intersect(
            $arrayMultiSelect,
            array_keys($this->_exportGetTab($entityPdo))
        );

        /*$listeSelect = implode(',', $arrayMultiSelect);*/
        
        if (empty($post['okFilter'])) {
            $post= [];
        }
        
        $listeChp = $entityPdo->getArchitecture($this->getTranslationService());

        $liste = $entityPdo->fetchAll($arrayMultiSelect, $post, $this->pdo::FETCH_ASSOC);

        /* trad */
       
        $trad = $this->getTranslationService();
        
        foreach ($listeChp as $key => $value) {
            $keyValue[$key] = $value['nomChamp'];
            
            if (isset($value['type'])) {
                foreach ($liste as &$ligne) {
                    if (isset($ligne[$key])) {
                        if ($value['type']=='DATE') {
                            $ligne[$key] = Date::dateConverte($ligne[$key]);
                        }
                        if ($value['type']=='RADIO') {
                            $ligne[$key] = Sql::toBool($ligne[$key])? $trad->t('Oui'):$trad->t('Non');
                        }
                    }
                }
            }
        }
        
        foreach ($arrayMultiSelect as $value) {
            $tab[$value] = $keyValue[$value];
        }
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_'.$idEntity.'_'.date('Ymd'),
            $liste,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );

        return 'ok';
    }

    /**
     * @param mixed|QueryBuilder $entityPdo
     * @return string[] label indexed by export key
     */
    private function _exportGetTab($entityPdo) :array
    {
        $tab = [];
        $listeChp = $entityPdo->getArchitecture($this->getTranslationService());
        foreach ($listeChp as $key => $value) {
            $tab[$key] = $value['nomChamp'];
        }
        return $tab;
    }

    // TODO : factorize with FirmTableReferenceController::getEntityByKey
    public function getEntityByKey(string $s) :QueryBuilder
    {
        $entity_class = self::getEntityClassByKey($s);

        /** @var QueryBuilder $entity */
        $entity = new $entity_class($this->pdo);

        return $entity;
    }

    public static function getEntityClassByKey(string $s) :string
    {
        switch ($s) {
            case 'CaractSelective':
                return \Entity\Model\CaractSelective::class;
            case 'CatIncid':
                return \Entity\Model\CatIncid::class;
            case 'Categorie':
                return \Entity\Model\Categorie::class;
            case 'CondPaie':
                return \Entity\Model\CondPaie::class;
            case 'ConversionUnite':
                return \Entity\Model\ConversionUnite::class;
            case 'Country':
                return \Entity\Model\Country::class;
            case 'Cqualite':
                return \Entity\Model\Cqualite::class;
            case 'Document':
                return \Entity\Model\Document::class;
            case 'DomaineCompetence':
                return \Entity\Model\DomaineCompetence::class;
            case 'DomaineFonctionnel':
                return \Entity\Model\DomaineFonctionnel::class;
            case 'Douanes':
                return \Entity\Model\Douanes::class;
            case 'EvenementAo':
                return \Entity\Model\EvenementAo::class;
            case 'EvenementBr':
                return \Entity\Model\BrEvent::class;
            case 'BrEvent':
                return \Entity\Model\BrEvent::class;
            case 'EvenementCde':
                return \Entity\Model\EvenementCde::class;
            case 'EvenementDa':
                return \Entity\Model\EvenementDa::class;
            case 'EvenementDcc':
                return \Entity\Model\EvenementDcc::class;
            case 'EvenementDossierAchat':
                return \Entity\Model\EvenementDossierAchat::class;
            case 'EvenementFa':
                return \Entity\Model\EvenementFa::class;
            case 'EvenementReferentiel':
                return \Entity\Model\EvenementReferentiel::class;
            case 'EvenementTermePaiement':
                return \Entity\Model\EvenementTermePaiement::class;
            case 'Fcontfrn':
                return \Entity\Model\Fcontfrn::class;
            case 'GrpSociete':
                return \Entity\Model\GrpSociete::class;
            case 'Incident':
                return \Entity\Model\Incident::class;
            case 'Langues':
                return \Entity\Model\Langues::class;
            case 'ListeDocument':
                return \Entity\Model\ListeDocument::class;
            case 'ListeObjet':
                return \Entity\Model\ListeObjet::class;
            case 'Messstan':
                return \Entity\Model\Messstan::class;
            case 'ModTrans':
                return \Entity\Model\ModTrans::class;
            case 'Modelivr':
                return \Entity\Model\Modelivr::class;
            case 'Modepaie':
                return \Entity\Model\Modepaie::class;
            case 'MotClef':
                return \Entity\Model\MotClef::class;
            case 'NiveauUo':
                return \Entity\Model\NiveauUo::class;
            case 'Ordonanc':
                return \Entity\Model\Ordonanc::class;
            case 'TVA':
                return \Entity\Model\TVA::class;
            case 'TableClausierCaDaAo':
                return \Entity\Model\TableClausierCaDaAo::class;
            case 'TextesTypes':
                return \Entity\Model\TextesTypes::class;
            case 'TypeAchat':
                return \Entity\Model\TypeAchat::class;
            case 'TypeDoc':
                return \Entity\Model\TypeDoc::class;
            case 'TypePj':
                return \Entity\Model\TypePj::class;
            case 'TypeTVA':
                return \Entity\Model\TypeTVA::class;
            case 'UO':
                return \Entity\Model\UO::class;
            case 'UniteExpedition':
                return \Entity\Model\UniteExpedition::class;
            case 'Unites':
                return \Entity\Model\Unites::class;
        }
        throw new \Exception('Invalid key "'.$s.'"');
    }
}
