<?php

namespace Modules\GlobalApplication\Controller;

use Entity\Model\Docatt;
use Helpers\Ariane\Ariane;
use Helpers\ExportTo\Outils;
use Helpers\Outil\Date;
use Helpers\Outil\Sql;
use Helpers\Pagination\Paginator;
use Helpers\Pagination\PaginatorGestion;
use Modules\GlobalApplication\MenuContextuel\WorkflowMenuContextuel;
use Skeleton\Controller\Controller;

class WorkflowDocumentController extends Controller
{

    /**
     * @return string
     */
    public function suiviDocumentAction(): string
    {
        $post   = $this->request->getParsedBody();
        $module = $this->request->getAttribute('type');
        $trad   = $this->getTranslationService();

        $titre = $trad->t('Suivi des documents déposés sur les 12 derniers mois');

        if (!$post) {
            $post['tri_DOC#point#DT_PARUT']   = 'desc';
        }

        $repo = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);

        $menuContextuel = new WorkflowMenuContextuel(
            $this->pdo,
            $this->router,
            $this->getTranslationService(),
            'Global'
        );

        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(0, 'COD_ENR');
        $liste = $repo->getDocumentsDetailed('FOURNISS', $post);
        Ariane::generate(0, $trad->t('Gestion'), $post, PaginatorGestion::getNbrArticle());
        $infoPagination = PaginatorGestion::getInfoPagination();

        foreach ($liste as &$doc) {
            $doc['menuContextuel'] = $menuContextuel->generateSuiviDoc($doc);
        }

        return $this->renderer->render('@GlobalApplication/WorkflowDocument/suiviDocument', [
            'titre'             => $titre,
            'menuLeft'          => null,
            'menuActive'        => 'Fournisseur',
            'module'            => $module,
            'sousModule'        => 'Suivi',
            'post'              => $post,
            'liste'             => $liste,
            'infoPagination'    => $infoPagination,
        ]);
    }

    /**
     * @return string
     */
    public function ficheDocumentAction(): string
    {
        $post       = $this->request->getParsedBody();
        $codEnr     = $this->request->getAttribute('codEnr');
        $noOrdre    = $this->request->getAttribute('noOrdre');
        $trad       = $this->getTranslationService();

        $docRepo = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $doc = $docRepo->getFicheDocument([
            'COD_ENR'   => $codEnr,
            'NO_ORDRE'  => $noOrdre,
            'MODULE'    => 'FOURNISS'
        ]);

        Ariane::generate(1, $trad->t('Détail document'));

        return $this->renderer->render('@GlobalApplication/WorkflowDocument/ficheDoc', [
            'doc' => $doc,
        ]);
    }

    /**
     * @return string
     */
    public function popupExportAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $repo = new Docatt($this->pdo);
        $listeChpDoc = $repo->getArchitecture($this->getTranslationService());

        $tab = [];
        foreach ($listeChpDoc as $key => $value) {
            $tab['DOC.'.$key] = $value['nomChamp'];
        }

        $tab['M.CONTMEMO'] = $trad->t('Commentaire');

        asort($tab);
        return $this->renderer->render(
            '@GlobalApplication/Popup/popupExport',
            [
                'pathExport'    => $this->router->generateUri('GlobalApplication.WorkflowDocument.exportDoc'),
                'formFilter'    => 'filtre_document',
                'coloneExport'  => $tab,
                'post'          => $post,
                'modeDebug'     => false,
            ]
        );
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function exportDocAction()
    {
        ini_set('memory_limit', '500M');

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

        $entity = new Docatt($this->pdo);
        $listeChpsExport = $entity->getArchitecture($trad);

        $arrayMultiSelect = array_filter($post, function ($k) {
            return (bool)stristr($k, 'multiSelect');
        }, ARRAY_FILTER_USE_KEY);


        $listeChpsDate      = [];
        $listeChpsBool      = [];
        $keyValue           = [];
        foreach ($listeChpsExport as $key => $value) {
            $keyValue['DOC.'.$key] = $value['nomChamp'];

            if (isset($value['type'])) {
                if ($value['type']=='DATE') {
                    $listeChpsDate[] = $key;
                }
                if ($value['type']=='RADIO') {
                    $listeChpsBool[] = $key;
                }
            }
        }

        $keyValue['M.CONTMEMO'] = $trad->t('Commentaire');

        $tab = [];
        foreach ($arrayMultiSelect as $key => $value) {
            $tab[$value] = $keyValue[$value];
        }

        $listeDoc = new \Modules\Fournisseur\Repository\DocAtt($this->pdo);
        $listeDoc = $listeDoc->getDocumentsDetailed('FOURNISS', $post, $arrayMultiSelect);

        $oui = $trad->t('Oui');
        $non = $trad->t('Non');

        foreach ($listeDoc as &$ligne) {
            foreach ($listeChpsDate as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Date::dateConverte($ligne[$chps]);
                }
            }

            foreach ($listeChpsBool as $chps) {
                if (isset($ligne[$chps])) {
                    $ligne[$chps] = Sql::toBool($ligne[$chps]) ? $oui : $non;
                }
            }
        }

        Outils::gestionEmailAsync2(
            "export_DOCATT_".date('Ymd'),
            $listeDoc,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );
        return 'ok';
    }
}
