<?php
namespace Modules\Parametrage\Oxalink\Controller;

use Entity\Model\Langues;
use Helpers\Sanitizer\Sanitizer;
use Skeleton\Controller\Controller;
use Helpers\Trad\Trad;
use Helpers\Outil\Sql;
use Helpers\Validator\Validator;
use Helpers\Ariane\ArianeSub;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Gestion_Fic_PJ;
use Modules\Parametrage\Oxalink\Repository\ParametrageOxalink;
use Helpers\Fichier\Fichier;
use Entity\Model\ParamDico;
use Helpers\Securite\Securite;
use Helpers\Session\ParseBase1;

class ParametragePageOxalinkController extends Controller
{
    public string $menuActive = '';
    public string $menuLeft   = '';

    public function init(): void
    {
        if (($_SESSION['ariane'][0]['path'] ?? null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $this->menuActive = 'Parametrage';
            $this->menuLeft   = 'Parametrage';
        } else {
            $this->menuActive = 'Fournisseur';
            $this->menuLeft   = 'Parametrage';
        }
    }

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

        $parametrageRepo = new ParametrageOxalink($this->pdo);

        $listePage = $parametrageRepo->listePageClient();

        $CGU = sql::paramDico($this->pdo, 'PF_OXALINK', 'CGU', '', 'CGU_DEFAUT');

        ArianeSub::generate(0, 2, $trad->t('Pages OXA.LINK'), $this->router->generateUri('Parametrage.ParametrageOxalink.page'), 1);

        return $this->renderer->render('@ParamOxalink/page', [
            'menuActive' => $this->menuActive,
            'menuLeft'   => $this->menuLeft,
            'listePage'  => $listePage,
            'post'       => $post,
            'CGU'        => $CGU,
        ]);
    }

    public function ajaxDetailPageAction(): string
    {
        $page            = $this->request->getAttribute('page');
        $parametrageRepo = new ParametrageOxalink($this->pdo);

        $listePageLangue = $parametrageRepo->listePageClientLangue($page);

        return $this->renderer->render('@ParamOxalink/detailPage', [
            'listePageLangue' => $listePageLangue,
        ]);
    }

    public function ajaxDetailCGUAction(): string
    {
        $parametrageRepo = new ParametrageOxalink($this->pdo);

        $listeCGULangue = $parametrageRepo->listeCGULangue();

        $CGU = sql::paramDico($this->pdo, 'PF_OXALINK', 'CGU', '', 'CGU_DEFAUT');

        return $this->renderer->render('@ParamOxalink/detailCGU', [
            'listeCGULangue' => $listeCGULangue,
            'CGU'            => $CGU,
        ]);
    }

    /**
     * @return Response|string
     */
    public function ajouterPageAction()
    {
        $post    = $this->request->getParsedBody();
        $page    = $this->request->getAttribute('page');
        $codeLng = $this->request->getAttribute('codeLng');
        $trad    = $this->getTranslationService();

        $parametrageRepo = new ParametrageOxalink($this->pdo);
        $complOnglet     = '';
        if ($page) {
            $detailPage = [];
            if ($codeLng) {
                $detailPage = $parametrageRepo->detailPageClient($page, $codeLng);
            }
            if (!$detailPage) {
                $detailPage = $parametrageRepo->detailPageClient($page, '');
            }
            $complOnglet = ' : ' . ($detailPage['TITRE'] ?? '');

            if ($codeLng) {
                $lang         = (new \Entity\Model\Langues($this->pdo))->find($codeLng);
                $complOnglet .= ' ' . $trad->t('en') . ' ' . ($lang['LIBELLE'] ?? 'Unknown');
            }
        }

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

            $validator->zoom('Langues', $codeLng ?? '', $trad->t('Langue'), $this->pdo, true);
            $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE'], 1, 30);
            $validator->isCheck($post['PAGE_PUBLIC']);

            $modeUrl = $post['TYPE_URL'] == 'URL' ? true : false;

            if ($modeUrl) {
                $post['URL'] = trim(addslashes($post['URL']));
                $validator->isUrlValide($trad->t('URL de la page'), $post['URL'], 1, 3000);
            }

            if ($validator->isValid()) {
                if ($modeUrl) {
                    $post['FIC_OU_URL'] = $post['URL'];
                } else {
                    $fileName = 'PAGEOXALINK_' . date('YmdHis') . '_' . rand(0, 999999999) . '.txt';

                    $creationFile = new Gestion_Fic_PJ($this->pdo);
                    $fileSave     = $creationFile->insertFichier($fileName, $post['FIC']);

                    $post['FIC_OU_URL'] = $fileSave;

                    if (!$fileSave) {
                        return $this->renderer->render('@popup-erreur/ErreurCreation', [
                            'ErreurValid' => $trad->t('Une erreur est survenue lors de l\'enregistrement, veuillez recommencer.'),
                        ]);
                    }
                }

                $arrayInsert = [
                    'CODE'        => $page ?? '',
                    'CODE_LNG'    => $codeLng ?? '',
                    'TITRE'       => $post['TITRE'],
                    'TYPE_URL'    => $modeUrl,
                    'FIC_OU_URL'  => $post['FIC_OU_URL'],
                    'PAGE_PUBLIC' => $post['PAGE_PUBLIC'],
                ];

                $parametrageRepo = new ParametrageOxalink($this->pdo);
                $parametrageRepo->insertPageClient($arrayInsert);

                return new Response(443, [

                ], (string) \json_encode([
                        'statut' => 'O',
                        'path'   => $this->router->generateUri('Parametrage.ParametrageOxalink.page'),
                    ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        } else {
            $post['TYPE_URL'] = 'CONTENT';
        }

        $listeTypeEnregistrement = [
            'CONTENT' => $trad->t('Création d\'une page'),
            'URL'     => $trad->t('Url exterieur'),
        ];

        ArianeSub::generate(1, 0, $trad->t('Nouvelle page') . $complOnglet, $this->router->generateUri('Parametrage.ParametrageOxalink.ajouterPage'), 1);

        return $this->renderer->render('@ParamOxalink/nouvellePage', [
            'menuActive'     => $this->menuActive,
            'menuLeft'       => $this->menuLeft,
            'post'           => $post,
            'listeTypeEnreg' => $listeTypeEnregistrement,
            'pathValidation' => $_SERVER['REQUEST_URI'],
            'langueActif'    => $codeLng ? true : false,
        ]);
    }

    /**
     * @return Response|string
     */
    public function modificationPageAction(
        Sanitizer $sanitizer,
        Gestion_Fic_PJ $creationFile,
        ParametrageOxalink $parametrageRepo,
        Langues $Langues,
        ParseBase1 $parseBase1,
    ) {
        $page    = $this->request->getAttribute('page');
        $codeLng = $this->request->getAttribute('codeLng');
        $post    = $this->request->getParsedBody();
        $trad    = $this->getTranslationService();

        $detailPage  = $parametrageRepo->detailPageClient($page, $codeLng ?? '');
        $complOnglet = $codeLng
            ? ' : ' . $parametrageRepo->detailPageClient($page, '')['TITRE'] . ' ' . $trad->t('en') . ' ' . $Langues->find($codeLng)['LIBELLE']
            : ' : ' . $detailPage['TITRE'];

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

            $validator->isStringAvecEspace($trad->t('Titre'), $post['TITRE'], 1, 30);
            $validator->isCheck($post['PAGE_PUBLIC']);

            $modeUrl = $post['TYPE_URL'] == 'URL' ? true : false;

            if ($modeUrl) {
                $post['URL'] = trim(addslashes($post['URL']));
                $validator->isUrlValide($trad->t('URL de la page'), $post['URL'], 1, 3000);
            }

            if ($validator->isValid()) {
                $detailPage['TYPE_URL'] = Sql::toBool($detailPage['TYPE_URL']) ? 'URL' : 'CONTENT';
                $contentSanitize        = $sanitizer->sanitize($post['FIC']);

                if ($detailPage['TYPE_URL'] != $post['TYPE_URL'] && !$modeUrl) {
                    $fileName = 'PAGEOXALINK_' . date('YmdHis') . '_' . rand(0, 999999999) . '.txt';


                    $fileSave = $creationFile->insertFichier($fileName, $contentSanitize);

                    $post['FIC_OU_URL'] = $fileSave;

                    if (!$fileSave) {
                        return $this->renderer->render('@popup-erreur/ErreurCreation', [
                            'ErreurValid' => $trad->t('Une erreur est survenue lors de l\'enregistrement, veuillez recommencer.'),
                        ]);
                    }
                } elseif ($detailPage['TYPE_URL'] == $post['TYPE_URL'] && !$modeUrl) {
                    $creationFile->createFolderOxalinkPages($parseBase1->getRep()->pj . \explode('\\', $detailPage['FIC_OU_URL'])[0]);
                    $creationFile->updateContenuFichier($detailPage['FIC_OU_URL'], $contentSanitize);

                    $post['FIC_OU_URL'] = $detailPage['FIC_OU_URL'];
                } elseif ($modeUrl && $detailPage['TYPE_URL'] == $post['TYPE_URL']) {
                    $post['FIC_OU_URL'] = $contentSanitize;
                } else {
                    $creationFile->deleteFichier($detailPage['FIC_OU_URL']);
                    $post['FIC_OU_URL'] = $contentSanitize;
                }


                $arrayInsert = [
                    'CODE'        => $page ?? '',
                    'CODE_LNG'    => $codeLng ?? '',
                    'TITRE'       => $post['TITRE'],
                    'TYPE_URL'    => $modeUrl,
                    'FIC_OU_URL'  => $post['FIC_OU_URL'],
                    'PAGE_PUBLIC' => $post['PAGE_PUBLIC'],
                ];

                $parametrageRepo->updatePageClient($arrayInsert);

                return new Response(443, [

                ], (string) \json_encode([
                        'statut' => 'O',
                        'path'   => $this->router->generateUri('Parametrage.ParametrageOxalink.page'),
                    ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        } else {
            if (!sql::boolSql($detailPage['TYPE_URL'])) {
                $detailPage['FIC_OU_URL'] = @file_get_contents($parseBase1->getRep()->pj . $detailPage['FIC_OU_URL']);
                $detailPage['TYPE_URL']   = 'CONTENT';
            } else {
                $detailPage['TYPE_URL'] = 'URL';
            }

            $post = $detailPage;
        }

        $listeTypeEnregistrement = [
            'CONTENT' => $trad->t('Création d\'une page'),
            'URL'     => $trad->t('Url extérieure'),
        ];

        ArianeSub::generate(1, 0, $trad->t('Modification page') . $complOnglet, $this->router->generateUri('Parametrage.ParametrageOxalink.modificationPage', ['page' => $page]), 1);

        return $this->renderer->render('@ParamOxalink/nouvellePage', [
            'menuActive'     => $this->menuActive,
            'menuLeft'       => $this->menuLeft,
            'post'           => $post,
            'listeTypeEnreg' => $listeTypeEnregistrement,
            'pathValidation' => $_SERVER['REQUEST_URI'],
            'langueActif'    => $codeLng ? true : false,
        ]);
    }

    public function suppresionPageAction(): string
    {
        $page    = $this->request->getAttribute('page');
        $codeLng = (string) $this->request->getAttribute('codeLng');


        if ($codeLng) {
            $parametrageRepo = new ParametrageOxalink($this->pdo);
            $detailPage      = $parametrageRepo->detailPageClient($page, $codeLng);

            if (!sql::boolSql($detailPage['TYPE_URL'])) {
                $deleteFile = new Gestion_Fic_PJ($this->pdo);
                $deleteFile->deleteFichier($detailPage['FIC_OU_URL']);
            }

            $parametrageRepo->deletePageClient($page, $codeLng);
        } else {
            $parametrageRepo = new ParametrageOxalink($this->pdo);
            $detailPage      = $parametrageRepo->detailPageClient($page, $codeLng);

            //delete page
            if (!sql::boolSql($detailPage['TYPE_URL'])) {
                $deleteFile = new Gestion_Fic_PJ($this->pdo);
                $deleteFile->deleteFichier($detailPage['FIC_OU_URL']);
            }

            $listePage = $parametrageRepo->listePageClientLangue($page);

            foreach ($listePage as $value) {
                if ($value['FIC_OU_URL']) {
                    if (!sql::boolSql($value['TYPE_URL'])) {
                        $deleteFile = new Gestion_Fic_PJ($this->pdo);
                        $deleteFile->deleteFichier($value['FIC_OU_URL']);
                    }
                }
            }

            $parametrageRepo->deletePageClient($page);
        }

        return '';
    }

    /**
     * @return Response|string
     */
    public function modificationCGUAction()
    {
        $codeLng   = $this->request->getAttribute('codeLng');
        $post      = $this->request->getParsedBody();
        $file      = $this->request->getUploadedFiles();
        $paramdico = new ParamDico($this->pdo);
        $trad      = $this->getTranslationService();

        if (!$codeLng) {
            $codeLng = 'CGU_DEFAUT';
        }

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

            $validator->isDate($post['DATE_CGU'], '', '', false, $trad->t('de création'));
            $validator->isStringSansEspace($trad->t('Référence CGU'), $post['REF_CGU'], 1, 50);

            $file_cgu = null;
            if ($file) {
                if (isset($file['importCGU'])) {
                    $file_cgu = $file['importCGU']->getClientFilename();
                    $fileSize = $file['importCGU']->getSize();
                }
            }

            $searchCGU = $paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'CGU', 'ID2' => $codeLng]);

            if (!$searchCGU) {
                $validator->fileCheck($trad->t('CGU'), $file_cgu, [], '', $fileSize ?? 0);
            }

            if ($validator->isValid()) {
                $gestionFic = new Gestion_Fic_PJ($this->pdo);

                if ($file_cgu) {
                    $newPath = Fichier::UploadDocAtt($file_cgu);

                    $nameFile = pathinfo($file_cgu);

                    $nameFile = $nameFile['filename'] . '.' . ($nameFile['extension'] ?? '');

                    $file['importCGU']->moveTo($newPath["racine"] . $newPath["new_name"]);

                    /** @phpstan-ignore-next-line */
                    $fileSave = $gestionFic->updateFicher(sql::paramDico($this->pdo, 'PF_OXALINK', 'CGU', 'LIBELLE', $codeLng), $newPath['new_name']);

                    $checkParamdico = $paramdico->find(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'CGU', 'ID2' => $codeLng]);

                    if ($checkParamdico) {
                        $paramdico->update(['LIBELLE' => $fileSave, 'ALPHA1' => $nameFile, 'ALPHA2' => $post['REF_CGU'], 'ALPHA3' => $post['DATE_CGU']], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'CGU', 'ID2' => $codeLng]);
                    } else {
                        $paramdico->insert(['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'CGU', 'ID2' => $codeLng, 'LIBELLE' => $fileSave, 'ALPHA1' => $nameFile, 'ALPHA2' => $post['REF_CGU'], 'ALPHA3' => $post['DATE_CGU']]);
                    }
                } else {
                    $paramdico->update(['ALPHA2' => $post['REF_CGU'], 'ALPHA3' => $post['DATE_CGU']], ['TYPEDICO' => 'PF_OXALINK', 'ID1' => 'CGU', 'ID2' => $codeLng]);
                }

                return new Response(443, [

                ], (string) \json_encode([
                        'statut' => 'O',
                        'path'   => $this->router->generateUri('Parametrage.ParametrageOxalink.page'),
                    ]));
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        } else {
            $CGU = sql::paramDico($this->pdo, 'PF_OXALINK', 'CGU', '', $codeLng);

            $post = [
                // @phpstan-ignore-next-line
                'REF_CGU'  => $CGU['ALPHA2'] ?? '',
                // @phpstan-ignore-next-line
                'CGU'      => $CGU['ALPHA1'] ?? '',
                'DATE_CGU' => date('Ymd'),
            ];
        }

        ArianeSub::generate(1, 0, 'Modification CGU', $_SERVER['REQUEST_URI'], 1);

        return $this->renderer->render('@ParamOxalink/modificationCGU', [
            'menuActive'     => $this->menuActive,
            'menuLeft'       => $this->menuLeft,
            'post'           => $post,
            'pathValidation' => $_SERVER['REQUEST_URI'],
            'pathAnnuler'    => $this->router->generateUri('Parametrage.ParametrageOxalink.page'),
        ]);
    }

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

        if (!$codeLng) {
            $codeLng = 'CGU_DEFAUT';
        }

        $CGU = sql::paramDico($this->pdo, 'PF_OXALINK', 'CGU', '', $codeLng);

        /** @phpstan-ignore-next-line */
        $message = Fichier::UploadClient((new ParseBase1())->getRep()->pj . $CGU['LIBELLE'], $CGU['ALPHA1']);
        return $message;
    }
}
