<?php
namespace Modules\Contrat\Controller;

use Helpers\Outil\Sql;
use Modules\Contrat\MenuContextuel\TypeDeMarcheContextuel;
use Skeleton\Controller\Controller;
use Entity\Model\TypeDeMarche;
use Helpers\Trad\Trad;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Ariane\Ariane;

class TypeDeMarcheeController extends Controller
{
    public function indexAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $listeTypeMarche = new TypeDeMarche($this->pdo);
        $listeTypeMarche = $listeTypeMarche->fetchAll([], $post);
        $count = count($listeTypeMarche);
        
        $paginator = new \Helpers\Pagination\Paginator();
        $infoPagination = $paginator->generate($listeTypeMarche, 0, $post, $this->renderer);

        $menuContextuel = new TypeDeMarcheContextuel($this->pdo, $this->router, $this->getTranslationService());

        foreach ($listeTypeMarche as &$type) {
            $type['menuContextuel'] = $menuContextuel->generate($type['CODE_TYMA']);
        }

        Ariane::generate(0, $trad->t('Gestion'), $post, $count);
        
        return $this->renderer->render('@Contrat/typeDeMarchee/index', [
            'menuActive'         => 'Contrats',
            
            'infoPagination'     => $infoPagination,
            'nombreResultat'     => $count,
            'liste_TypeDeMarche' => $listeTypeMarche,
        ]);
    }
    
    public function creationAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $TypeMarche = new TypeDeMarche($this->pdo);
        $trad = $this->getTranslationService();
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();

            if ($validator->isTrue(count($TypeMarche->find(['CODE_TYMA' => $post['CODE_TYMA']])), Trad::strBuild($trad->t("Le code Type Marché @1@ existe déjà."), $post['CODE_TYMA']))) {
                $validator->isStringSansEspace($trad->t('Type marché'), $post['CODE_TYMA'], 1, 10);
            }
            $validator->isStringAvecEspace($trad->t('Libelle'), $post['LIBELLE'], 1, 60);
            $specCaract = array("&", "?", ">", "|", "*", "^", "<", "'", '"', "%" );
            $validator->nocontentInArray($trad->t('Code Type de marché'), $post['CODE_TYMA'], $specCaract);
            $typeDeMarche = new TypeDeMarche($this->pdo);
            
            if ($validator->isValid()) {
                $typeDeMarche->insert([
                    'CODE_TYMA' => $post['CODE_TYMA'],
                    'LIBELLE' => $post['LIBELLE'],
                ]);
                
                return $this->redirect('Contrat.TypeDeMarchee.index');
            } else {
                $ErreurValid = $validator->getError();
            }
        }
        
        Ariane::generate(1, $trad->t('Nouveau Type de Marché'));
        
        return $this->renderer->render('@Contrat/typeDeMarchee/creation', [
            'menuActive'  => 'Contrats',
            
            'menuLeft'    => 'Contrat.TypeDeMarchee.index',
            'mode'        => 'creation',
            'post'        => $post,
            'ErreurValid' => $ErreurValid??'',
        ]);
    }
    
    public function modificationAction()
    {
        $id = $this->request->getAttribute('id');
        $typeDeMarche = new TypeDeMarche($this->pdo);
        $post = $typeDeMarche->find($id);
        $trad = $this->getTranslationService();
        
        if ($this->request->getMethod() == 'POST') {
            $post = $this->request->getParsedBody();
            $validator = $this->createValidator();
            
            $validator->isStringAvecEspace($trad->t('Libelle'), $post['LIBELLE'], 1, 60);
            
            if ($validator->isValid()) {
                $typeDeMarche->update([
                    'LIBELLE' => $post['LIBELLE'],
                ], $id);
                
                return $this->redirect('Contrat.TypeDeMarchee.index');
            } else {
                $ErreurValid = $validator->getError();
            }
        }

        Ariane::generate(1, $trad->t('Modification'), $post);
        
        return $this->renderer->render('@Contrat/typeDeMarchee/creation', [
            'menuActive'  => 'Contrats',
            'menuLeft'    => 'Contrat.TypeDeMarchee.index',
            'mode'        => 'modification',
            'post'        => $post,
            'ErreurValid' => $ErreurValid??'',
        ]);
    }
    
    public function deleteAction()
    {
        $id = $this->request->getAttribute('id');
        
        $typeDeMarche = new TypeDeMarche($this->pdo);
        $typeDeMarche->delete($id);
    }


    public function exportTypeMarcheAction() : string
    {
        $post = $this->request->getParsedBody();

        $TypeDeMarche  = new \Entity\Model\TypeDeMarche($this->pdo);
        $TypeMarche =new \Modules\Contrat\Repository\TypeMarche($this->pdo);
        $trad = $this->getTranslationService();

        // Récupération des formats des champs
        $listeChps = $TypeDeMarche->getArchitecture($this->getTranslationService());
        
        //On récupère la liste des champs DATE & BOOL afin de les traités après
        $listeChpsDate = [];
        $listeChpsBool = [];
        foreach ($listeChps as $key => $value) {
            $keyValue[$key] = $value['nomChamp'];
            
            if (isset($value['type'])) {
                if ($value['type']=='DATE') {
                    $listeChpsDate[] = $key;
                }
                if ($value['type']=='RADIO') {
                    $listeChpsBool[] = $key;
                }
            }
        }
        $keyValue['CONTMEMO'] = $trad->t('Commentaire');

        // On récupère la liste des marchés
        $select = "CODE_TYMA, LIBELLE";
        $listeTypeMarche = $TypeMarche->listExport($select, $post);

        
        //On génère l'entete du fichier d'export
        $listeSelect = explode(',', $select);
        foreach ($listeSelect as $value) {
            $tab[trim($value)] = $keyValue[trim($value)];
        }

        $oui = $trad->t('Oui');
        $non = $trad->t('Non');
        // on traite les différents champs de l'export (date/bool...)
        foreach ($listeTypeMarche as &$ligne) {
            foreach ($listeChpsDate as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Date::dateConverte($ligne[$chps]);
                }
            }
            
            foreach ($listeChpsBool as $chps) {
                if (isset($ligne[$chps])) {
                    if ($ligne[$chps]!=null) {
                        $ligne[$chps] = Sql::toBool($ligne[$chps]) ? $oui : $non;
                    }
                }
            }
        }
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            "export_type_marches",
            $listeTypeMarche,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );

        return 'ok';
    }
}
