<?php

namespace Modules\Contrat\Controller;

use Entity\Model\CondPaie;
use Entity\Model\Hastutil;
use Entity\Model\Modelivr;
use Entity\Model\Modepaie;
use Entity\Model\Societe;
use Entity\Model\TypeDeMarche;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Skeleton\Controller\Controller;
use Helpers\Validator\Validator;
use Helpers\Fichier\Fichier;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;
use Helpers\Outil\Date;
use Entity\Model\Marches;
use \Modules\Contrat\Repository\ContratRep;
use Modules\Contrat\MenuContextuel\GestionMarchesContextuel;
use Helpers\Parametres\Constante;
use Modules\GlobalApplication\MenuContextuel\DocumentMenuContextuel;

class MarcheeController extends Controller
{

    public function indexAction(): string
    {
        $post = $this->request->getParsedBody();
        $post['tri_LIBELLE'] = 'asc';
        $marcheRep = new ContratRep($this->pdo);
        $marches   = $marcheRep->marcheByCodeSociete($post);

        $paginator = new \Helpers\Pagination\Paginator();
        $infoPagination = $paginator->generate($marches, 0, $post);

        $trad = $this->getTranslationService();

        /* Filtre avancées */
        $filtreAvance = new \Helpers\Filter\FiltreAvance\Generator($post);
        $filtreAvance->setFiltre('MARCHES.SIGNATAIR', 'liste', $trad->t('Signataire'), '', 'Ajax.liste.utilisateur', 'Hastutil');
        $filtreAvance->setFiltre('MARCHES.CONDPAI', 'liste', $trad->t('Condition de paiement'), '', 'Ajax.liste.conditionPaiement', 'CondPaie');
        $filtreAvance->setFiltre('MARCHES.MODEPAI', 'liste', $trad->t('Mode de paiement'), '', 'Ajax.liste.modePaiement', 'Modepaie');
        $filtreAvance->setFiltre('MARCHES.MODELIV', 'liste', $trad->t('Mode de livraison'), '', 'Ajax.liste.modelivraison', 'Modelivr');

        $menuContextuel = new GestionMarchesContextuel($this->pdo, $this->router, $trad);
        foreach ($marches as &$marche) {
            $nb_marche = $marche['NBRE_MARCHE'];
            $marche['menuContextuel'] = $menuContextuel->generate($marche);
        }

        \Helpers\Ariane\Ariane::generate(0, $trad->t('Gestion'), $post);
        ArianeSub::init();


        return $this->renderer->render('@Contrat/marche/index', [
            'marches'        => $marches,
            'infoPagination' => $infoPagination,
            'filtreAvance' => $filtreAvance->getFiltres(),
            'initFiltreAvance' => $filtreAvance->getInit(),
            'menuActive' => 'Contrats',
            'post' => $post,
            
            'nb_marche' => $nb_marche ?? 0,
        ]);
    }

    // CONTROLLER du details en fonction du code en parametre
    public function visualisationAction(): string
    {
        $id = $this->request->getAttribute('id');
        $post = $this->request->getParsedBody();

        $listeCS = ChampSupp::listeIdCS('MARCHES', $this->pdo);
        $marcheRepo = new ContratRep($this->pdo);

        $marche = $marcheRepo->detail($id);
        $marcheSoc = $marcheRepo->detailSociete($id);
        
        $utiliList = (new Hastutil($this->pdo))->findAll([
            'CODE' => [$marche['ACHETEURCODE'], $marche['SIGNATAIR']],
        ]);

        $trad = $this->getTranslationService();
        \Helpers\Ariane\Ariane::generate(1, $trad->t('Visualisation'), $post);

        return $this->renderer->render('@Contrat/marche/visualisation', [
            'marche' => $marche,
            'listeCS' => $listeCS,
            'marcheSoc' => $marcheSoc,
            'marcheCommentaire' => $marche,
            'menuActive' => 'Contrats',
            'menuLeft' => 'Contrat.marche.index',
            'devise'     => $_SESSION['parametrage']['DEVISE_BASE'],
            // TODO : regroup into one query
            'utiliMap' => array_column($utiliList, null, 'CODE'),
            'modeLivr' => (new Modelivr($this->pdo))->find($marche['MODELIV']),
            'condPaie' => (new CondPaie($this->pdo))->find($marche['CONDPAI']),
            'modePaie' => (new Modepaie($this->pdo))->find($marche['MODEPAI']),
            'societe' => (new Societe($this->pdo))->find($marche['STEMARCHE']),
            'typeMarche' => (new TypeDeMarche($this->pdo))->find($marche['TYPEMARC']),
        ]);
    }



    public function modifierAction()
    {
        $id = $this->request->getAttribute('id');

        $listeCS = ChampSupp::listeIdCS('MARCHES', $this->pdo);

        $marche = new ContratRep($this->pdo);

        $commentaire = $marche->visualisationCommentaire($id);
        $marcheModification = $marche->detail($id);

        $trad = $this->getTranslationService();

        if ($this->request->getMethod() == 'POST') {
            $post = $this->request->getParsedBody();


            $validator = $this->createValidator();


            /* Marché */
            // Libellé marché - Dates de validité
            $validator->isStringAvecEspace($trad->t("Libellé marché"), $post['LIBELLE'], 1, 60);
            $validator->isDate($post['DDEBVAL'], '', '', true, $trad->t('Début de validité'));
            $validator->isDate($post['DFINVAL'], '', '', true, $trad->t('Fin de validité'));
            $validator->isCoherenceDate($post['DDEBVAL'], $post['DFINVAL']);

            /* Informations */
            // Type de marché - Société -  Acheteur - Signataire
            $validator->zoom('TypeDeMarche', $post['TYPEMARC'], $trad->t('Type de marché'), $this->pdo, true, [], $trad->t(' ne correspond pas à un code existant dans la liste Type de Marchés'));
            $validator->zoom('Societe', $post['STEMARCHE'], $trad->t('Sociétés'), $this->pdo, true);
            $validator->acheteurZoom($post['ACHETEURS'], $trad->t('Acheteurs'), $this->pdo, true, ['VALIDE' => 1]);
            $validator->utilisateurZoom($post['SIGNATAIR'], $trad->t('Signataires'), $this->pdo, true, ['VALIDE' => 1, 'filter_SIG_CDE' => 'T']);

            // Prévisionnel Mini et Maxi
            $validator->isFloat($trad->t('Prévisionnel Mini'), $post['MNTPREMIN'], Constante::formatMontant);
            $validator->isFloat($trad->t('Prévisionnel Maxi'), $post['MNTPREMAX'], Constante::formatMontant);
            $validator->montantCoherence($post['MNTPREMIN'], $post['MNTPREMAX']);

            /* Conditions */
            // Conditions de paiement - Mode de paiement - Commentaires - Mode de livraison - Délai de livraison
            $validator->zoom('CondPaie', $post['CONDPAI'], $trad->t('Conditions de paiement'), $this->pdo, true);
            $validator->zoom('Modepaie', $post['MODEPAI'], $trad->t('Mode de paiement'), $this->pdo, true);
            $validator->isStringAvecEspace($trad->t('Commentaires'), $post['CONTMEMO'], 0, 3000);
            $validator->zoom('Modelivr', $post['MODELIV'], $trad->t('Mode de livraison'), $this->pdo, true);
            $validator->isInteger($trad->t('Délais de livraison'), $post['DELAILIV'], 0, 3);

            /* CS */
            $validator->validatorCS('MARCHES', $id, $post, $this->pdo);

            if (!$validator->isValid()) {
                $ErreurValid = $validator->getError();
                $post['ErreurValid'] = true;
            } else {
                $marcheUpdate = new \Entity\Model\Marches($this->pdo);
                $memos = new \Entity\Model\Memos($this->pdo);

                $modification = [
                    'CODE' => $post['CODE'],
                    'LIBELLE' => $post['LIBELLE'],
                    'TYPEMARC' => $post['TYPEMARC'],
                    'MNTPREMIN' => $post['MNTPREMIN'],
                    'MNTPREMAX' => $post['MNTPREMAX'],
                    'DFINVAL' => $post['DFINVAL'],
                    'DDEBVAL' => $post['DDEBVAL'],
                    'CONDPAI' => $post['CONDPAI'],
                    'MODEPAI' => $post['MODEPAI'],
                    'MODELIV' => $post['MODELIV'],
                    'DELAILIV' => $post['DELAILIV'],
                    'ACHETEUR' => $post['ACHETEURS'],
                    'SIGNATAIR' => $post['SIGNATAIR'],
                    'STEMARCHE' => $post['STEMARCHE']
                ];
                $marcheUpdate->update($modification, $id);

                $memoUpdate = ['CONTMEMO' => $post['CONTMEMO'] ?? ''];
                $memos->update($memoUpdate, $post['NMCOMMEN']);

                ChampSupp::updateCS($post, $this->pdo);

                return $this->redirect('Contrat.marche.index');
            }
        }


        return $this->renderer->render('@Contrat/marche/modification', [
            'menuActive' => 'Contrats',
            'commentaire' => $commentaire,
            'menuLeft' => 'Contrat.marche.index',
            'marche' => $marcheModification,
            'listeCS' => $listeCS,
            'ErreurValid' => $ErreurValid ?? '',
            'post'   => $post ?? '',
            'id' => $id,
        ]);
    }

    public function creationAction()
    {
        $marche = [];
        $id = $this->request->getAttribute('id');
        $marche = new \Entity\Model\Marches($this->pdo);
        $memos = new \Entity\Model\Memos($this->pdo);
        $sqlMemo = new \Helpers\Outil\Sql();


        $listeCS = ChampSupp::listeIdCS('MARCHES', $this->pdo);

        $marcheRep = new ContratRep($this->pdo);

        $trad = $this->getTranslationService();
        if ($this->request->getMethod() == 'POST') {
            $post = $this->request->getParsedBody();

            $validator = $this->createValidator();

            /* Marché */
            // Code marché - Libellé marché
            $marcheFound = $marche->find(['CODE' => $post['CODE']]);
            if ($validator->isTrue($marcheFound, Trad::strBuild($trad->t("Le code marché @1@ existe déjà."), $post['CODE']))) {
                $specCaract = array("&", "?", ">", "|", "*", "^", "<", "'", '"', "%");
                $validator->nocontentInArray($trad->t('Code marché'), $post['CODE'], $specCaract, 1, 15);
                $validator->isStringSansEspace($trad->t("Code marché"), $post['CODE'], 1, 15);
            }
            $validator->isStringAvecEspace($trad->t("Libellé marché"), $post['LIBELLE'], 1, 60);

            // Dates de validité
            $validator->isDate($post['DDEBVAL'], '', '', true, $trad->t('Début de validité'));
            $validator->isDate($post['DFINVAL'], '', '', true, $trad->t('Fin de validité'));
            $validator->isCoherenceDate($post['DDEBVAL'], $post['DFINVAL']);

            /* Informations */
            // Type de marché - Société -  Acheteur - Signataire
            $validator->zoom('TypeDeMarche', $post['TYPEMARC'], $trad->t('Type de marché'), $this->pdo, true, [], $trad->t(' ne correspond pas à un code existant dans la liste Type de Marchés'));
            $validator->zoom('Societe', $post['STEMARCHE'], $trad->t('Sociétés'), $this->pdo, true);
            $validator->acheteurZoom($post['ACHETEURS'], $trad->t('Acheteurs'), $this->pdo, true, ['VALIDE' => 1]);
            $validator->utilisateurZoom($post['SIGNATAIR'], $trad->t('Signataires'), $this->pdo, true, ['VALIDE' => 1, 'filter_SIG_CDE' => 'T']);

            // Prévisionnel Mini et Maxi
            $validator->isFloat($trad->t('Prévisionnel Mini'), $post['MNTPREMIN'], Constante::formatMontant);
            $validator->isFloat($trad->t('Prévisionnel Maxi'), $post['MNTPREMAX'], Constante::formatMontant);
            $validator->montantCoherence($post['MNTPREMIN'], $post['MNTPREMAX']);

            /* Conditions */
            // Conditions de paiement - Mode de paiement - Commentaires - Mode de livraison - Délai de livraison
            $validator->zoom('CondPaie', $post['CONDPAI'], $trad->t('Conditions de paiement'), $this->pdo, true);
            $validator->zoom('Modepaie', $post['MODEPAI'], $trad->t('Modes de paiement'), $this->pdo, true);
            $validator->isStringAvecEspace($trad->t('Commentaires'), $post['CONTMEMO'], 0, 3000);
            $validator->zoom('Modelivr', $post['MODELIV'], $trad->t('Modes de livraison'), $this->pdo, true);
            $validator->isInteger($trad->t('Délais de livraison'), $post['DELAILIV'], 0, 3);


            $validator->validatorCS('MARCHES', '', $post, $this->pdo);

            if (!$validator->isValid()) {
                $ErreurValid = $validator->getError();
                $post['ErreurValid'] = true;
            } else {
                $idMemo = $sqlMemo->generateNum($this->pdo);
                $memoInsert = ['NODEMEMO' => $idMemo, 'CONTMEMO' => $post['CONTMEMO'] ?? ''];

                $insert =
                    [
                        'CODE'      => $post['CODE'],
                        'LIBELLE'   => $post['LIBELLE'],
                        'TYPEMARC'  => $post['TYPEMARC'],
                        'MNTPREMIN' => $post['MNTPREMIN'],
                        'MNTPREMAX' => $post['MNTPREMAX'],
                        'DFINVAL'   => $post['DFINVAL'],
                        'DDEBVAL'   => $post['DDEBVAL'],
                        'CONDPAI'   => $post['CONDPAI'],
                        'MODEPAI'   => $post['MODEPAI'],
                        'MODELIV'   => $post['MODELIV'],
                        'DELAILIV'  => $post['DELAILIV'],
                        'ACHETEUR'  => $post['ACHETEURS'],
                        'SIGNATAIR' => $post['SIGNATAIR'],
                        'STEMARCHE' => $post['STEMARCHE'],
                        'NMCOMMEN'  => $idMemo
                    ];

                // insertion
                $memos->insert($memoInsert);
                $marche->insert($insert);
                ChampSupp::ajouterCS($post, $this->pdo, $post['CODE']);

                return $this->redirect('Contrat.marche.index');
            }
        }

        return $this->renderer->render('@Contrat/marche/creation', [
            'menuActive'  => 'Contrats',
            'menuLeft'    => 'Contrat.marche.index',
            'listeCS'     => $listeCS,
            'marche'      => $marche,
            'ErreurValid' => $ErreurValid ?? '',
            'post'        => $post ?? ''
        ]);
    }

    public function cumulACDAction(): string
    {
        $id = $this->request->getAttribute('id');

        $Marches = new \Entity\Model\Marches($this->pdo);
        $marche = $Marches->find($id);
        $marcheRep = new ContratRep($this->pdo);
        $acd = $marcheRep->cumulAcd($id);

        $marche['MNTPREMIN'] = floatval($marche['MNTPREMIN']);
        $marche['MNTPREMAX'] = floatval($marche['MNTPREMAX']);

        return $this->renderer->render('@Contrat/marche-popup/cumulACD', [
            'marche' => $marche,
            'cumulAcd' => $acd['cumulAcd'],
        ]);
    }
    public function cumulSOCAction(): string
    {
        $id = $this->request->getAttribute('id');

        $marcheRep  = new ContratRep($this->pdo);

        $marche     = $marcheRep->detail($id);

        $marcheSoc  = $marcheRep->detailSociete($id);

        return $this->renderer->render('@Contrat/marche-popup/cumulSOC', [
            'marche'    => $marche,
            'marcheSoc' => $marcheSoc
        ]);
    }

    /** Page document rattachés **/
    public function docRattacheAction(): string
    {
        $post = $this->request->getParsedBody();
        //
        $post['NO_DA'] = 'MARCHES';
        // ID à mettre sur 9 digits
        // $idTmp = $this->request->getAttribute('id');
        // $id = str_pad($idTmp, 9, '0', STR_PAD_LEFT);
        $id = $this->request->getAttribute('id');

        /* Liste des documents attaché */
        $docAtt = new \Modules\GlobalApplication\Repository\DocumentsRattaches($this->pdo);
        $docAtt = $docAtt->detail($id, $post);

        $marche = new Marches($this->pdo);
        $marche = $marche->find($id);

        $paginator = new \Helpers\Pagination\Paginator();

        $infopagination = $paginator->generate($docAtt, 0, $post, $this->renderer);

        $trad = $this->getTranslationService();

        \Helpers\Ariane\Ariane::generate(1, $trad->t('Documents rattachés'));
        
        $menuContextuel = new DocumentMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($docAtt as &$doc) {
            $doc['menuContextuel'] = $menuContextuel->generate($doc, $post['NO_DA']);
        }

        return $this->renderer->render('@GlobalApplication/documents-rattaches/documents-rattaches', [
            'menuActive'     => 'Contrats',
            'menuLeft'       => 'Contrat.marche.index',
            'id'             => $id,
            'NO_DA'          => $post['NO_DA'],
            'docAtts'        => $docAtt,
            'date'           => date("Ymd"),
            'post'           => $post,
            'droitModif'     => Roles::droitsUtilisateur($this->pdo, 'HA_DOC_RAT'),
            'doc'            => true,
            'infoPagination' => $infopagination,
            'pathPage'       => 'Contrat.marche.docRattache',
            'pathRetour'     => $this->router->generateUri('Contrat.marche.index'),
            'titre'          => $trad->t('Documents rattachés') . ' ' . $marche['LIBELLE'] . ' (' . $id . ')',
            'MODULE'         => 'ACD',
            'droitCreation'  => Roles::droitsUtilisateur($this->pdo, 'HA_DOC_RAT'),
        ]);
    }

    public function popupCommentaireMarcheAction(): string
    {

        $id = $this->request->getAttribute('id');
        $memos = new \Entity\Model\Memos($this->pdo);
        $nmcommen = $this->request->getAttribute('nmcommen');
        $post = $this->request->getParsedBody();

        if ($this->request->getMethod() == 'POST' && isset($post['MARCHE_COMMENT']) && isset($id) && isset($nmcommen)) {
            $memoUpdate = ['CONTMEMO' => $post['MARCHE_COMMENT']];
            $memos->update($memoUpdate, $nmcommen);
        }


        $marcheRep  = new ContratRep($this->pdo);

        $commentaireMarche     = $marcheRep->visualisationCommentaire($id);

        return $this->renderer->render('@Contrat/marche-popup/popup-commentaire-marche', [
            'id'          => $id,
            'nmcommen'    => $nmcommen,
            'commentaire' => $commentaireMarche
        ]);
    }
    public function exportVisualisationMarcheAction(): string
    {
        $id = $this->request->getAttribute('idacc');
        $type = $this->request->getAttribute('type');
        $marche = new ContratRep($this->pdo);

        $accListe = $marche->listExport($id, $type);


        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_acccadre_',
            $accListe,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }


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

        $Marches  = new \Entity\Model\Marches($this->pdo);
        $marcheRep = new ContratRep($this->pdo);
        $trad = $this->getTranslationService();

        // Récupération des formats des champs
        $listeChps = $Marches->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, LIBELLE, TYPEMARC, MNTPREMIN, MNTPREMAX, DFINVAL, DDEBVAL, CONDPAI, MODEPAI, MODELIV,  DELAILIV, ACHETEUR, SIGNATAIR, STEMARCHE, CONTMEMO";
        $listeMarches = $marcheRep->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 ($listeMarches 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_marches_',
            $listeMarches,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }
}
