<?php
namespace Modules\Catalogue\Controller;

use Entity\Model\CataEnt;
use Entity\Model\CFormats;
use Entity\Model\ParamChg;
use Entity\Model\VersCata;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\ITrad;
use Helpers\User\User;
use Modules\Catalogue\Enum\ListeFormatEnum;
use Modules\Catalogue\Enum\MethodeChargementEnum;
use Modules\Catalogue\Enum\ModeChargementEnum;
use Modules\Catalogue\Enum\ModeDeploiementEnum;
use Modules\Catalogue\Enum\PeriodiciteEnum;
use Modules\Catalogue\Enum\StatutVersionEnum;
use Modules\Catalogue\Enum\TraitementRejetEnum;
use Modules\Catalogue\Enum\TypeCatalogueEnum;
use Modules\Catalogue\Enum\TypeFichierLogEnum;
use Modules\Catalogue\MenuContextuel\CataExterneMenuContextuel;
use Modules\Catalogue\MenuContextuel\CatalogueMenuContextuel;
use Modules\Catalogue\Repository\CatalogueExterneRepository;
use Modules\Catalogue\Validator\CatalogueExterneValidator;
use Skeleton\Controller\Controller;

class CatalogueExterneController extends Controller
{
    public function listeCatalogueAction():string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if (!$post) {
            $post['tri_ID_CATAL'] = 'ASC';
        }

        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(0, 'CATAENT.ID_CATAL');

        $listeCatalogue = (new CatalogueExterneRepository($this->pdo))->getListeCatalogue($post);

        $menuContextuel = (new CataExterneMenuContextuel($this->pdo, $this->router, $trad));
        foreach ($listeCatalogue as &$catalogue) {
            $catalogue['menuContextuel'] = $menuContextuel->generate($catalogue);
        }

        $nombreArticle  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        Ariane::generate(0, $trad->t('Gestion des catalogues externe'), $post, $nombreArticle);

        return $this->renderer->render('@catalogue/CatalogueExterne/listeCatalogue', [
            'menuActive'        => 'Catalogue',
            'listeCatalogue'    => $listeCatalogue,
            'post'              => $post,
            'typeCatlogue'      => [...TypeCatalogueEnum::getAsAssoc($trad)],
            'listeFormat'       => [...ListeFormatEnum::getAsAssoc($trad)],
            'infoPagination'    => $infopagination,
        ]);
    }

    public function ajaxDetailAction():string
    {
        $idCatalogue = $this->request->getAttribute('idCatalogue');
        
        $catalogueRepo = new CatalogueExterneRepository($this->pdo);

        return $this->renderer->render('@catalogue/CatalogueExterne/ajaxDetailCatalogue', [
            'catalogue'     => $catalogueRepo->getInfoCatalogue($idCatalogue),
            'listeVersion'  => (new VersCata($this->pdo))->findAll(['ID_CATAL' => $idCatalogue]),
            'listeStatut'   => [...StatutVersionEnum::getAsAssoc($this->getTranslationService())],
        ]);
    }

    public function createditAction():string
    {
        $idCatalogue = $this->request->getAttribute('idCatalogue');
        $trad = $this->getTranslationService();

        if ($idCatalogue) {
            $catalogue = (new CataEnt($this->pdo))->find($idCatalogue);
            $typeFormat = (new CFormats($this->pdo))->find($catalogue['IDFORMAT'], ['TYPDATAS'])['TYPDATAS'];
            Ariane::generate(1, $trad->t('Modification d\'un catalogue'));
        } else {
            Ariane::generate(1, $trad->t('Création d\'un catalogue'));
        }

        return $this->renderer->render('@catalogue/CatalogueExterne/createdit', [
            'idCatalogue'   => $idCatalogue,
            'typeCatlogue'  => [...TypeCatalogueEnum::getAsAssoc($trad)],
            'catalogue'     => $catalogue??[],
            'typeFormat'    => $typeFormat??'',
            'listeFormat'   => [...ListeFormatEnum::getAsAssoc($trad)],
        ]);
    }

    public function ajaxGetTypeFormatAction():Response
    {
        $post = $this->request->getParsedBody();
        return new Response(200, [], (string)json_encode([
            'TYPEFORMAT' => (new CFormats($this->pdo))->find($post['IDFORMAT'], ['TYPDATAS'])['TYPDATAS']]));
    }

    public function validateAction():Response
    {
        $idCatalogue = $this->request->getAttribute('idCatalogue');
        $validator = new CatalogueExterneValidator($this->pdo, $this->getTranslationService());
        $post = $this->request->getParsedBody();

        $validator->entete($post);

        $user = (new User());
        $user->initObjectSource($_SESSION);
        if ($validator->isValid()) {
            if ($idCatalogue) {
                (new CataEnt($this->pdo))->update([
                    'ID_CATAL'          => $post['ID_CATAL'],
                    'DESCRIPTION_CATA'  => $post['DESCRIPTION_CATA'],
                    'IDFORMAT'          => $post['IDFORMAT'],
                    'TYPECATA'          => $post['TYPECATA'],
                    'REGRFOUR'          => $post['REGRFOUR']??'',
                    'DATEMODIF'         => date('Ymd'),
                    'HEURMODIF'         => date('Hms'),
                    'MODIFPAR'          => $user->getCodeUser(),
                    'PRIXMODIFIABLE'    => Sql::toBool($post['PRIXMODIFIABLE']),
                    'PRIXMODIFHAUSSE'   => Sql::toBool($post['PRIXMODIFHAUSSE']),
                    'MODIFTVA'          => Sql::toBool($post['MODIFTVA']),
                    'COD_LNG'            => '',
                ], $idCatalogue);
            } else {
                (new CataEnt($this->pdo))->insert([
                    'ID_CATAL'          => $post['ID_CATAL'],
                    'DESCRIPTION_CATA'  => $post['DESCRIPTION_CATA'],
                    'IDFORMAT'          => $post['IDFORMAT'],
                    'TYPECATA'          => $post['TYPECATA'],
                    'REGRFOUR'          => $post['REGRFOUR']??'',
                    'DATECREAT'         => date('Ymd'),
                    'HEURCREAT'         => date('Hms'),
                    'CREATPAR'          => $user->getCodeUser(),
                    'DATEMODIF'         => date('Ymd'),
                    'HEURMODIF'         => date('Hms'),
                    'MODIFPAR'          => $user->getCodeUser(),
                    'PRIXMODIFIABLE'    => Sql::toBool($post['PRIXMODIFIABLE']),
                    'PRIXMODIFHAUSSE'   => Sql::toBool($post['PRIXMODIFHAUSSE']),
                    'MODIFTVA'          => Sql::toBool($post['MODIFTVA']),
                    'COD_LNG'           => '',
                ]);

                // insert VERSATA
                $versCata = new VersCata($this->pdo);
                $versCata->insert([
                    'ID_CATAL'  => $post['ID_CATAL'],
                    'VERSCATA'  => 'VERSION_'.date('Y'),
                    'DATEPUB'   => date('Ymd'),
                    'VALIDCATA' => date("Ymd", strtotime("+1 month", (int)strtotime(date('d/m/Y')))),
                    'STATUT'    => 'P',
                    //'IDATACATA' => '',
                    'DATECREAT' => date('Ymd'),
                    'HEURCREAT' => date('His'),
                    'CREATPAR'  => (new User())->getCodeUser(),
                    'DATEMODIF' => date('Ymd'),
                    'HEURMODIF' => date('His'),
                    'MODIFPAR'  => (new User())->getCodeUser(),
                    'DACTUDTA'  => date('Ymd'),
                    'HACTUDTA'  => date('His')
                ]);

                $idVersion = $versCata->getLastInsertId('VERSCATA', 'IDATACATA');

                $paramChg = new ParamChg($this->pdo);
                $paramChg->insert([
                    'IDVERSION'         => $idVersion,
                    'ORDRE'             => 1,
                    'METHCHRG'          => 'N',
                    'MODECHRG'          => 'C',
                    'TRTREJETS'         => 'R',
                    'NIVOLOG'           => 'N',
                    'MODERECUP'         => 'Fic',
                    'SEPARATE'          => ';',
                    'SETDECIM'          => '.',
                    'NBLGSTER'          => 1,
                    'PERIOVAL'          => 0,
                    'CHRGACTIF'         => 1,
                    'DATEDEB'           => '00000000',
                    'HEUREDEB'          => '000000',
                ]);
            }

            if ($idCatalogue) {
                $backPath = Ariane::getBackPath();
                $backPost = Ariane::getBackPost();
    
                return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => $backPost]));
            } else {
                return new Response(443, [], (string) json_encode([
                    'path' => $this->router->generateUri('Catalogue.VersionCataExterne.gestionVersion', ['idCatalogue' => $post['ID_CATAL']])
                ]));
            }
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    public function listeVersionCatalogueAction():string
    {
        $type = $this->request->getAttribute('type');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $paginator = new \Helpers\Pagination\PaginatorGestion();
        $paginator->generate(0, 'VERSCATA.ID_CATAL', 'ASC');

        $listeCatalogue = (new CatalogueExterneRepository($this->pdo))->listeVersionCatalogue($post);

        $menuContextuel = (new CatalogueMenuContextuel($this->pdo, $this->router, $trad));
        foreach ($listeCatalogue as &$catalogue) {
            $catalogue['menuContextuel'] = $menuContextuel->global($catalogue);
        }

        $nombreArticle  = PaginatorGestion::getNbrArticle();
        $infopagination = PaginatorGestion::getInfoPagination();

        $titre = match ($type) {
            'carac' => $trad->t('Gestion des affectations caractéristiques'),
            'rayon' => $trad->t('Gestion des affectations des rayons'),
            default => $trad->t('Liste des catalogues Actifs ou en préparation'),
        };

        Ariane::generate(0, $titre, $post, $nombreArticle);

        return $this->renderer->render('@catalogue/CatalogueExterne/listeVersionCatalogue', [
            'menuActive'        => 'Catalogue',
            'listeCatalogue'    => $listeCatalogue,
            'post'              => $post,
            'typeCatlogue'      => [...TypeCatalogueEnum::getAsAssoc($trad)],
            'listeFormat'       => [...ListeFormatEnum::getAsAssoc($trad)],
            'listeStatut'       => [...StatutVersionEnum::getAsAssoc($this->getTranslationService())],
            'infoPagination'    => $infopagination,
        ]);
    }
}
