<?php

namespace Modules\DemandeAchat\Controller;

use Helpers\Outil\Date;
use Modules\DemandeAchat\Outil\FormArray;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;
use Helpers\Outil\Sql;
use Entity\Model\DaEvent;
use Modules\DemandeAchat\Repository\DemandeAchatEventRepo;
use TwigExtension\OutilExtension;

class DemandeAchatEventController extends Controller
{
    public function suiviAction(): string
    {
        $code = $this->request->getAttribute('idDA');
        $MODULE = $this->request->getAttribute('MODULE');
        $affichageBtnNew = 1;
        $ACTION_ACTIF = 1;
        $trad = $this->getTranslationService();

        $suiviDemandeAchat = (new DemandeAchatEventRepo($this->pdo));
        $demandeAchat = $suiviDemandeAchat->demandeAchatEntete($code);
        $listeEvent = $suiviDemandeAchat->listeEventDemandeAchat($code, $MODULE);
        $listeCodeEvent = $suiviDemandeAchat->listeEvent();

        $trad = $this->getTranslationService();
        $formArray = FormArray::getFormArrays($trad);

        $menuActive = 'CollecteBesoins';
        $menuLeft = 'GestionDemandeAchat';
        switch ($MODULE) {
            case 'SignatureDA':
                $hastutil = new \Entity\Model\Hastutil($this->pdo);
                $H1 = Trad::strBuild($trad->t("Liste des DA actuellement à signer pour @1@ (@2@)"), $hastutil->find($_SESSION['Session_Login'])['NOM'], $_SESSION['Session_Login']);
                $affichageBtnNew = 0;
                $ACTION_ACTIF = 0;
                break;
            case 'signataire':
                $menuActive = 'eproc';
                $menuLeft = 'DA';
                $H1 = $trad->t('Demandes d\'achat');
                break;
            case 'DelegationSignatureDA':
                $H1 = $trad->t("Délégations des signatures");
                $affichageBtnNew = 0;
                $ACTION_ACTIF = 0;
                break;
            default:
                $H1 = $trad->t('Demandes d\'achat');
                break;
        }

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

        ariane::setFocus($code);

        return $this->renderer->render('@DemandeAchat/SuiviDemandeAchat/suiviDemandeAchat', [
            'menuActive' => $menuActive,
            'menuLeft' => $menuLeft,
            'demandeAchat' => $demandeAchat,
            'H1' => $H1,
            'listeEvent' => $listeEvent,
            'affichageBtnNew' => (($affichageBtnNew && count($listeCodeEvent) > 0) ? 1 : 0),
            'ACTION_ACTIF' => $ACTION_ACTIF,
            'typeChiffExec' => $formArray['typeChiffExec'],
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'tabTypeDate' => $formArray['tabTypeDate'],
        ]);
    }

    public function createEventAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $post = $this->request->getParsedBody();

        $suiviDemandeAchat = new DemandeAchatEventRepo($this->pdo);
        $event = $suiviDemandeAchat->listeEvent();

        $listeEvent = [];
        for ($i = 0; $i < count($event); $i++) {
            $listeEvent[$event[$i]['CODE_SDA']] = $event[$i]['LIBELLE'];
        }

        if ($post) {
            $validator = $this->createValidator();
            $validator->isStringAvecEspace('Texte', $post['CONTMEMO'], 0, 3000);
            $trad = $this->getTranslationService();

            $DaEvent_Exist = new DaEvent($this->pdo);
            $DaEvent_Exist = $DaEvent_Exist->find([
                'NO_DA' => $idDA,
                'CODE' => $post['CODE_EVE'],
            ]);

            $validator->isTrue($DaEvent_Exist, $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 = [
                    'NO_DA' => $idDA,
                    'DTE' => date('Ymd'),
                    'HEURE' => date('His'),
                    'CODE' => $post['CODE_EVE'],
                    'UTIL' => $_SESSION['Session_Login'],
                    'SIGNAT' => '',
                    'NM_COMME' => $id_memossql,
                ];

                $suiviDemandeAchat->ajoutEvenement($array);

                $message = $trad->t("Votre événement a été créé");

                return $this->renderer->render('@popup-erreur/confirmationGestion', [
                    'message' => $message,
                    'refresh' => true,
                    'div_refresh' => 'demandes',
                ]);
            } else {
                $erreur = $validator->getError();
            }
        }
        return $this->renderer->render('@GlobalApplication/Popup/ajoutEvenement', [
            'liste_event' => $listeEvent,
            'idDA' => $idDA,
            'event' => $post,
            'erreur' => $erreur ?? '',
            'pathEvent' => $this->router->generateUri('DemandeAchat.Event.createEvent', ['idDA' => $idDA]),
        ]);
    }

    public function suppressionAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $numOrdre = $this->request->getAttribute('numOrdre');

        $suiviDemandeAchat = new DemandeAchatEventRepo($this->pdo);

        $event = $suiviDemandeAchat->findEvent($idDA, $numOrdre);

        $suiviDemandeAchat->deleteEvenement($idDA, $numOrdre);
        sql::deleteMemos($this->pdo, $event['NODEMEMO']);
        $trad = $this->getTranslationService();

        $message = $trad->t("Votre événement a été supprimé");

        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $message,
            'reload' => true,
            'div' => 'suivi-evenements',
        ]);
    }

    public function modificationAction(): string
    {
        $idDA = $this->request->getAttribute('idDA');
        $numOrdre = $this->request->getAttribute('numOrdre');

        $post = $this->request->getParsedBody();

        $suiviDemandeAchat = new DemandeAchatEventRepo($this->pdo);
        $event = $suiviDemandeAchat->listeEvent();

        $this_event = $suiviDemandeAchat->findEvent($idDA, $numOrdre);

        $listeEvent = [];
        for ($i = 0; $i < count($event); $i++) {
            $listeEvent[$event[$i]['CODE_SDA']] = $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 = [
                    'NO_DA' => $idDA,
                    'NUM_ORD' => $numOrdre,
                    'NM_COMME' => $id_memossql,
                ];

                $suiviDemandeAchat->modificationEvenement($array);

                $trad = $this->getTranslationService();
                $message = $trad->t("Votre événement a été modifié");

                return $this->renderer->render('@popup-erreur/confirmationGestion', [
                    'message' => $message,
                    'refresh' => true,
                    'div_refresh' => 'commandes',
                ]);
            } else {
                $erreur = $validator->getError();
            }
        } else {
            $post = $this_event;
        }

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

    public function exportAction() :string
    {
        $demId = $this->request->getAttribute('idDA');
        $module = $this->request->getAttribute('module');
        $trad = $this->getTranslationService();
        
        $this->getEmailCsvService()->sendCsv(
            $this->JWTKEY,
            'export_demachat_event_' . date('Ymd'),
            (new DemandeAchatEventRepo($this->pdo))->export($demId, $module),
            function ($row) {
                return [
                    $row['CODE'],
                    $row['LIBELLE'],
                    Date::dateConverte($row['DTE']),
                    Date::heureTrad($row['HEURE']),
                    OutilExtension::entityLabel($row, 'Auteur_NOM', 'UTIL'),
                    OutilExtension::entityLabel($row, 'Signataire_NOM', 'SIGNAT'),
                    $row['Commentaire'],
                ];
            },
            [
                $trad->t('Code'),
                $trad->t('Évènement'),
                $trad->t('Date'),
                $trad->t('Heure'),
                $trad->t('Auteur'),
                $trad->t('Signataire'),
                $trad->t('Commentaire'),
            ]
        );
        return 'ok';
    }
}
