<?php
namespace Modules\Fournisseur\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\ArianeSub;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Fournisseur\MenuContextuel\GestionShortListMenuContextuel;
use Modules\Fournisseur\Outil\ImportSLFournisseur;
use Skeleton\Controller\Controller;
use Modules\Fournisseur\Repository\ShortList;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Ariane\Ariane;

class GestionShortListController extends Controller
{

    
    // phpcs:ignore
    public function GestionShortListAction() : string
    {
        $post             = $this->request->getParsedBody();
        
        $listeShortList   = new ShortList($this->pdo);
        $listeShortList   = $listeShortList->ListeShortList($post);
        $menuContextuel   = new GestionShortListMenuContextuel($this->pdo, $this->router, $this->getTranslationService());

        foreach ($listeShortList as &$s) {
            $s['menuContextuel'] = $menuContextuel->generate($s['CODLST'], $s['LIBELLE']);
        }

        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($listeShortList, 0, $post, $this->renderer);

        /* trad */

        $trad = $this->getTranslationService();
        
        Ariane::generate(0, $trad->t('Gestion'), $post, count($listeShortList));

        return $this->renderer->render('@Fournisseur/GestionShortList/ShortList', [
            'menuActive'        => 'Fournisseur',
            'gestion'           => true,
            'post'              => $post,
            'infoPagination'    => $infopagination,
            'listShortList'     => $listeShortList,
            'nombreResultat'    => count($listeShortList),
        ]);
    }
    
    public function suppressionShortListAction(): string
    {
        $code = $this->request->getAttribute('code');
        
        $shortList = new \Entity\Model\ShortList($this->pdo);
        $shortList->delete($code);
        
        return '';
    }
    
    public function creationShortListAction()
    {
        $post = $this->request->getParsedBody();
        
        /* trad */
        
        $trad = $this->getTranslationService();
        
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();
            
            $validator->isDate($post['DTE_FIN'], '', '', true, $trad->t('de début'));
            $validator->isDate($post['DTE_DEB'], '', '', true, $trad->t('date de fin'));
            $validator->isStringAvecEspace($trad->t('Libellé'), $post['LIBELLE'], 1, 60);
            $validator->isStringAvecEspace($trad->t('Commentaires'), $post['COMM'], 0, 3000);
            
            if ($validator->isValid()) {
                $shortList = new ShortList($this->pdo);
                $shortList->CreationShortList($post);
                
                return $this->redirect('Fournisseur.GestionShortList.gestionShortList');
            } else {
                $ErreurValid = $validator->getError();
            }
        }
        
        Ariane::generate(1, $trad->t('Nouvelle ShortList'), $post);
        
        return $this->renderer->render('@Fournisseur/GestionShortList/creationShortList', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'Fournisseur.GestionShortList.gestionShortList',
            'creationSL' => true,
            'ErreurValid' => $ErreurValid??'',
            'shortList' => $post,
            
        ]);
    }
    
    public function modificationShortListAction()
    {
        $idSL = $this->request->getAttribute('idSL');
        $post = $this->request->getParsedBody();

        /* trad */
        
        $trad = $this->getTranslationService();
        
        $shortList = new \Entity\Model\ShortList($this->pdo);
        $shortList = $shortList->find($idSL);
        
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();
            
            $validator->isDate($post['DTE_FIN'], '', '', true, $trad->t('Date de début'));
            $validator->isDate($post['DTE_DEB'], '', '', true, $trad->t('Date de fin'));
            $validator->isStringAvecEspace($trad->t('Libellé'), $post['LIBELLE'], 1, 60);
            $validator->isStringAvecEspace($trad->t('Commentaires'), $post['COMM'], 0, 3000);
            
            if ($validator->isValid()) {
                $shortList = new ShortList($this->pdo);
                $shortList->UpdateShortList($idSL, $post);
                
                return $this->redirect('Fournisseur.GestionShortList.gestionShortList');
            } else {
                $shortList = $post;
                $ErreurValid = $validator->getError();
            }
        }
        
        Ariane::generate(1, $trad->t('Modification short list'), $post);
        
        return $this->renderer->render('@Fournisseur/GestionShortList/creationShortList', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'Fournisseur.GestionShortList.gestionShortList',
            'modificationSL' => true,
            'ErreurValid' => $ErreurValid??'',
            'shortList' => $shortList,
            
        ]);
    }
    
    public function exportShortListAction() : string
    {
        $post = $this->request->getParsedBody();
        $listeShortList = new ShortList($this->pdo);
        $listeShortList = $listeShortList->ListeShortList($post, true);
        
        foreach ($listeShortList as &$shortListe) {
            $shortListe['DATE_DEBUT']=DATE::dateConverte($shortListe['DATE_DEBUT']);
            $shortListe['DATE_FIN']=DATE::dateConverte($shortListe['DATE_FIN']);
        }
        
        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            'export_short_list',
            $listeShortList,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService()
        );

        return 'ok';
    }

    /**
     * @return mixed
     */
    public function importFournisseurShortListAction()
    {
        $post = $this->request->getParsedBody();

        Ariane::init();
        ArianeSub::init();

        $trad = $this->getTranslationService();

        $tailleMaximumFichierValue = 5;
        $paravrac = new \Entity\Model\Paravrac($this->pdo);
        if ($tailleMaximumFichier = $paravrac->find(['TYPEPARV' => 'PARAMGEN', 'CODEPARV' => 'PJ_TAILLEMAX'], ['LIB01PARV'])) {
            if (isset($tailleMaximumFichier['LIB01PARV']) && $tailleMaximumFichier['LIB01PARV'] != 0) {
                $tailleMaximumFichierValue = $tailleMaximumFichier['LIB01PARV'];
            }
        }

        $libelleForm = Trad::strBuild(
            $trad->t('Déposez votre fichier de Short Lists Fournisseurs ci-dessus. Le fichier est attendu au format xls, xlsx, csv, son poids doit être inférieur à @1@ Mo et comporter moins de @2@ lignes. Les colonnes suivantes sont attendues :'),
            $tailleMaximumFichierValue,
            ImportSLFournisseur::MAX_LINE
        );

        $exampleData = [
            [
                'name' => $trad->t('Code fournisseur'),
                'required' => $trad->t('Oui'),
                'format' => $trad->t('A').' / 12',
            ],
            [
                'name' => $trad->t('Code Short List'),
                'required' => $trad->t('Oui'),
                'format' => $trad->t('N').' / ',
            ],
            [
                'name' => $trad->t('Statut (C:Création/D:Suppression)'),
                'required' => $trad->t('Oui'),
                'format' => $trad->t('S').' / 1',
            ],
        ];

        Ariane::generate(0, $trad->t('Import de Shortlists'));

        return $this->renderer->render('@Fournisseur/GestionShortList/import', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'Fournisseur.GestionShortList.importFournisseurShortList',
            'post' => $post,
            'libelleForm' => $libelleForm,
            'exampleData' => $exampleData,
        ]);
    }

    /**
     * @return Response|string
     * @throws \PhpOffice\PhpSpreadsheet\Calculation\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function ajaxImportFournisseurShortListAction()
    {
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $fileName = null;
        $fileSize = 0;

        if ($post) {
            $validator = $this->createValidator();

            $file = $this->request->getUploadedFiles();

            if ($file) {
                $fileName = $file['importshortListFournisseur']->getClientFilename();
                $fileSize = $file['importshortListFournisseur']->getSize();
            }

            $validator->fileCheck($trad->t('Fichier d\'import'), $fileName, ['xls', 'xlsx', 'csv'], '', $fileSize);

            if ($validator->isValid()) {
                $newPath = $_SESSION['dir_tmp'].$fileName;
                $file['importshortListFournisseur']->moveTo($newPath);

                $import = new ImportSLFournisseur($this->pdo, $newPath, $trad);
                $import->import();

                $result = $import->getResult();

                if (!$import->isValid()) {
                    return $this->renderer->render('@popup-erreur/ErreurCreation', [
                        'ErreurValid' => implode('<br>', $import->getErrors()),
                        'titrePopup' => $trad->t('Erreur fichier incorrect'),
                        'desactiveRow' => true,
                    ]);
                } else {
                    return new Response(443, [

                    ], (string) \json_encode([
                        'statut' => 'O',
                        'path' => $this->router->generateUri('Fournisseur.GestionShortList.recapImport'),
                        'postGestion' => ['retour' => $result],
                    ]));
                }
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                    'titrePopup' => $trad->t('Erreur fichier incorrect'),
                    'desactiveRow' => true,
                ]);
            }
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $trad->t('Fichier obligatoire'),
                'titrePopup' => $trad->t('Erreur fichier incorrect'),
            ]);
        }
    }

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

        $trad = $this->getTranslationService();

        Ariane::generate(1, $trad->t('Résultat de l\'import'));

        return $this->renderer->render('@Fournisseur/GestionShortList/recapImport', [
            'menuActive' => 'Fournisseur',
            'menuLeft' => 'GestionShortList',
            'result' => $post['retour']
        ]);
    }
}
