<?php
namespace Modules\Commande\Controller;

use Entity\Model\CaEvent;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Date;
use Helpers\Validator\Validator;
use Skeleton\Controller\Controller;
use Helpers\Ariane\ArianeSub;
use Helpers\Outil\Sql;
use Entity\Model\CaEntet;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Roles;
use Helpers\Trad\Trad;
use Modules\Commande\MenuContextuel\SuiviMenuContextuel;
use Modules\Commande\Repository\CommandeEventRepo;

class CommandeEventController extends Controller
{
    public function suiviAction() : string
    {
        $code = $this->request->getAttribute('idCommande');
        $MODULE = $this->request->getAttribute('MODULE');

        $cde_Repo = new CommandeEventRepo($this->pdo);
        $commande = $cde_Repo->commandeEntete($code);
        
        $listeEvent = $cde_Repo->listeEventCommande(
            $code,
            $MODULE == 'signataire' ? [
                'CA_EVENT.CODE' => 'SIG',
            ] : []
        );

        $menuContextuel = new SuiviMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), []);
        foreach ($listeEvent as &$event) {
            $event['menuContextuel'] = $menuContextuel->generate($commande, $event);
        }

        $trad = $this->getTranslationService();

        ArianeSub::init();
        Ariane::generate(4, $trad->t('Suivi des évènements'));
        Ariane::setFocus($code);

        switch ($MODULE) {
            case 'Tables':
                break;
            case 'ListeDA':
                break;
            case 'Fournisseur':
                $menuActive = 'Fournisseur';
                $menuLeft = 'GestionFournisseur';
                break;
            case 'signataire':
                $menuActive = 'eproc';
                $menuLeft = 'commande';
                break;
            default:
                $menuActive = 'CollecteBesoins';
                $menuLeft = 'Commande.GestionCommande.index';
                $droitActif = true;
                $droit = [
                    'HA_CA_CEV' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_CEV'),
                ];
                break;
        }
        
        return $this->renderer->render('@Commande/SuiviCommande/suiviCommande', [
            'menuActive' => $menuActive ?? null,
            'menuLeft' => $menuLeft ?? null,
            'commande' => $commande,
            'listeEvent' => $listeEvent,
            'MODULE' => $MODULE,
            'droitActif' => $droitActif??false,
            'droit' => $droit??[],
        ]);
    }
    
    public function ajoutEvenementCommandeAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();
        
        $commande_repo = new CommandeEventRepo($this->pdo);
        $event = $commande_repo->listeEvent();
        
        $listeEvent= [];
        for ($i=0; $i<count($event); $i++) {
            $listeEvent[$event[$i]['CODE_SCD']] = $event[$i]['LIBELLE'];
        }
        
        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace('Texte', $post['CONTMEMO'], 0, 3000);
            
            $trad = $this->getTranslationService();
            
            $validator->isTrue(
                ! empty(
                    (new CaEvent($this->pdo))->find([
                        'NO_CDE' => $idCommande,
                        'CODE' => $post['CODE_EVE'],
                    ])
                ),
                $trad->t('Vous ne pouvez pas créer 2 fois le même évènement')
            );
            
            if ($validator->isValid()) {
                $id_memossql = sql::updateMemo($this->pdo, '', $post['CONTMEMO']);
                
                $array = [
                    'NUM_CDE' => $idCommande,
                    'DTE' => date('Ymd'),
                    'HEURE' => date('His'),
                    'CODE' => $post['CODE_EVE'],
                    'UTIL' => $_SESSION['Session_Login'],
                    'SIGNAT' => '',
                    'NM_COMME' => $id_memossql,
                ];
                
                $commande_repo->ajoutEvenement($array);
                
                $message = $trad->t("Votre événement a été créé");
                
                return $this->renderer->render('@popup-erreur/confirmationGestion', [
                    'message' => $message,
                    'refresh' => true,
                    'div_refresh' => 'commandes',
                    'iconePopup' => 'information',
                ]);
            } else {
                $erreur = $validator->getError();
            }
        }
        return $this->renderer->render('@GlobalApplication/Popup/ajoutEvenement', [
            'liste_event' => $listeEvent,
            'idCommande' => $idCommande,
            'event' => $post,
            'erreur' => $erreur??'',
            'pathEvent' => $this->router->generateUri('Commande.Event.ajoutEvenementCommande', ['idCommande' => $idCommande]),
        ]);
    }
    
    public function suppressionEventCommandeAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $numOrdre = $this->request->getAttribute('numOrdre');
        $trad = $this->getTranslationService();
        
        $commandeRepo = new CommandeEventRepo($this->pdo);
        
        $event = $commandeRepo->findEvent($idCommande, $numOrdre);
        $commandeRepo->deleteEvenement($idCommande, $numOrdre);
        
        sql::deleteMemos($this->pdo, $event['NODEMEMO']);
        
        $message = $trad->t("Votre événement a été supprimer");
        
        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'reload' => false,
            'iconePopup' => 'information',
            'div' => 'suivi-evenements',
        ]);
    }
    
    public function modificationtEvenementCommandeAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $numOrdre = $this->request->getAttribute('numOrdre');
        
        $post = $this->request->getParsedBody();
        
        $commande_repo = new CommandeEventRepo($this->pdo);
        $event = $commande_repo->listeEvent();
        
        $this_event = $commande_repo->findEvent($idCommande, $numOrdre);
        
        $listeEvent= [];
        for ($i=0; $i<count($event); $i++) {
            $listeEvent[$event[$i]['CODE_SCD']] = $event[$i]['LIBELLE'];
        }
        
        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace('Texte', $post['CONTMEMO'], 0, 3000);
            
            if ($validator->isValid()) {
                $id_memossql = sql::updateMemo($this->pdo, $this_event['NODEMEMO'], $post['CONTMEMO']);
                
                $array = [
                    'NUM_CDE' => $idCommande,
                    'NO_ORD' => $numOrdre,
                    'NM_COMME' => $id_memossql,
                ];
                
                $commande_repo->modificationEvenement($array);
                
                $trad = $this->getTranslationService();
                $message = $trad->t("Votre événement a été créé");
                
                return $this->renderer->render('@popup-erreur/confirmationGestion', [
                    'message' => $message,
                    'refresh' => true,
                    'iconePopup' => 'information',
                    'div_refresh' => 'commandes',
                ]);
            } else {
                $erreur = $validator->getError();
            }
        } else {
            $post = $this_event;

            $post['CODE_EVE'] = $post['CODE'];
        }
        
        return $this->renderer->render('@GlobalApplication/Popup/ajoutEvenement', [
            'liste_event' => $listeEvent,
            'idCommande' => $idCommande,
            'event' => $post,
            'erreur' => $erreur??'',
            'modification' => true,
            'pathEvent' => $this->router->generateUri('Commande.Event.modificationtEvenementCommande', ['idCommande' => $idCommande, 'numOrdre' => $numOrdre]),
        ]);
    }

    public function exportAction() :string
    {
        $commandeId = $this->request->getAttribute('idCommande');
        $MODULE = $this->request->getAttribute('MODULE');
        $trad = $this->getTranslationService();

        $this->getEmailCsvService()->sendCsv(
            $this->JWTKEY,
            'export_commande_event_' . date('Ymd'),
            (new CommandeEventRepo($this->pdo))->export(
                $commandeId,
                $MODULE == 'signataire' ? [
                    'CA_EVENT.CODE' => 'SIG',
                ] : []
            ),
            function ($row) {
                return [
                    $row['CODE'],
                    $row['LIBELLE'], // TODO  : trad
                    Date::dateConverte($row['DTE']),
                    Date::heureTrad($row['HEURE']),
                    !empty($row['UTIL']) ?
                        $row['Utili_NOM'] . ' ('.$row['UTIL'].')' : '',
                    !empty($row['SIGNAT']) ?
                        $row['Signataire_NOM'] . ' ('.$row['SIGNAT'].')' : '',
                    $row['CONTMEMO']
                ];
            },
            [
                $trad->t('Code'),
                $trad->t('Libellé'),
                $trad->t('Date'),
                $trad->t('Heure'),
                $trad->t('Auteur'),
                $trad->t('Signataire'),
                $trad->t('Commentaires'),
            ]
        );
        return 'ok';
    }
}
