<?php
namespace Modules\Commande\Controller;

use Modules\GlobalApplication\Repository\LicenceOxalys;
use Skeleton\Controller\Controller;
use Helpers\Ariane\ArianeSub;
use Entity\Model\CaPijo;
use Modules\Commande\Repository\Commande;
use Helpers\Fichier\Fichier;
use Helpers\Ariane\Ariane;
use Helpers\Fichier\Gestion_Fic_PJ;
use Modules\Commande\MenuContextuel\GestionMenuContextuel;
use Modules\Commande\Repository\Avenant;
use Modules\Commande\Repository\PJ;
use Modules\GlobalApplication\MenuContextuel\PiecesJointesMenuContextuel;

class PieceJointeController extends Controller
{

    public function indexAction(
        LicenceOxalys $licenceOxalys
    ): string {
        $numCde = $idCommande = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        
        $avenant = $this->request->getAttribute('idAvenant');
        
        $modeHisto = false;
        $posAriane = 1;
        if ($avenant || $avenant === '0') {
            $modeHisto = true;
            $posAriane = 2;
        }

        if ($modeHisto) {
            $avenantRepo = new Avenant($this->pdo);
            $listePJ = $avenantRepo->getListePJ($numCde, $avenant, $post);
        } else {
            $pj = new PJ($this->pdo);
            $listePJ = $pj->listePJ($numCde, $post);
        }
        
        $typePj = new Commande($this->pdo);
        $typePj = $typePj->getListeTypePj();
        
        $listeTypePj = array_column($typePj, 'PJLIBELLE', 'PJ_TYPE');

        $commande = new Commande($this->pdo);
        $commande = $commande->commandeEntete($idCommande);

        $menuContextuel = new GestionMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), []);
        $commande['menuContextuel'] = $menuContextuel->lightGenerate($commande);
        
        $paginator = new \Helpers\Pagination\Paginator();
        $paginator->generate($listePJ, 0, $post, $this->renderer);
        
        $trad = $this->getTranslationService();

        ArianeSub::init();
        if ($_SESSION['navigation']['menuActive'] == 'eproc') {
            Ariane::generate(2, $trad->t('Pièces-jointes'), $post);
            ariane::setFocus($numCde);
        } else {
            Ariane::generate($posAriane, $trad->t('Détail commande'), $post);
            ariane::setFocus($numCde);
            ArianeSub::generate(0, 0, $trad->t('Articles commande'), $this->router->generateUri('Commande.Commande.article', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 0);
            ArianeSub::generate(0, 1, $trad->t('Informations commande'), $this->router->generateUri('Commande.Commande.commande', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 0);
            if (!$modeHisto) {
                ArianeSub::generate(0, 2, $trad->t('Documents rattachés'), $this->router->generateUri('GlobalApplication.DocumentRattaches.document', ['MODULE' => 'Commande', 'id' => $numCde, 'idAvenant' => $avenant]), 0, $post);
            }
            ArianeSub::generate(0, 3, $trad->t('Pièces-jointes'), $this->router->generateUri('Commande.PieceJointe.index', ['idCommande' => $numCde, 'idAvenant' => $avenant]), 1);
            ArianeSub::generate(0, 4, $trad->t('Clauses'), $this->router->generateUri('Commande.Clause.index', ['idCommande' => $numCde, 'idAvenant' => $avenant]));
            if (!$modeHisto) {
                ArianeSub::generate(0, 5, $trad->t('Interactions'), $this->router->generateUri('Commande.Interaction.interactions', ['idCommande' => $numCde, 'idAvenant' => $avenant]));
            }
            if ($licenceOxalys->termPaieActive()) {
                ArianeSub::generate(0, 6, $trad->t('Termes de paiement'), $this->router->generateUri('Commande.TermeDePaiementCommande.index', ['idCommande' => $numCde, 'MODULE' => 'Commande']));
            }
        }

        if ($avenant) {
            $idCdeAvt = $numCde.' - '.$avenant;
        } else {
            /** @phpstan-ignore-next-line */
            $idCdeAvt = $numCde.($commande['AVENANT']? (' - '.$commande['AVENANT']):'');
        }

        $titreModule = $trad->t('Commandes');
        if ($modeHisto) {
            $titre = $trad->t('Commande historisée'). ' '.$idCdeAvt;
        } else {
            $titre = $trad->t('Commande'). ' '.$idCdeAvt;
        }

        
        $pathCreation = ($modeHisto || $commande['ETAT_CDE'] != 'A')? '':$this->router->generateUri('Commande.PieceJointe.create', ['idCommande' => $idCommande]);
        $pathModification = ($modeHisto || $commande['ETAT_CDE'] != 'A')? '':$this->router->generateUri('Commande.PieceJointe.edit', ['idCommande' => $idCommande]);
        $pathSuppresion = ($modeHisto || $commande['ETAT_CDE'] != 'A')? '':$this->router->generateUri('Commande.PieceJointe.delete', ['idCommande' => $idCommande]);

        $menuContextuel = new PiecesJointesMenuContextuel($this->pdo, $this->router, $this->getTranslationService());
        foreach ($listePJ as &$pj) {
            $pj['menuContextuel'] = $menuContextuel->generate($pj, $idCommande, 'CDE', $pathModification, $pathSuppresion);
        }
        
        return $this->renderer->render('@GlobalApplication/Piecesjointes/pieces-jointes', [
            'module'       => 'CDE',
            'id'           => $numCde,
            'post'         => $post,
            'tableau_pj'   => $listeTypePj,
            'listePJ'      => $listePJ,
            'pathCreation' => $pathCreation,
            'pathModification' => $pathModification,
            'pathSuppression' => $pathSuppresion,
            'titreModule'  => $titreModule,
            'titre'        => $titre,
            'commande'      => $commande,
        ]);
    }





    public function createAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        
        /** Pour charger les menus déroulants **/
        $typePj = new \Entity\Model\PJTypes($this->pdo);
        $typePj = $typePj->fetchAll();
        foreach ($typePj as $value) {
            $tabTypePj[$value["PJ_TYPE"]]=$value["PJLIBELLE"];
        }
        /* ***************************** */;

        \Helpers\Ariane\ArianeSub::generate(1, 1, $trad->t('Création Pièce Jointe'), $_SERVER['REQUEST_URI'], 1);

        $titreModule = $trad->t('Commandes');
        $titre = $trad->t('Commande'). ' '.$idCommande;

        $post['IMP_PJ'] = 'On';
        $post['IMP_TITRE'] = 'On';
        
        return $this->renderer->render('@GlobalApplication/Piecesjointes/creation-pieces-jointes', [
            'menuActive'        => 'CollecteBesoins',
            'menuLeft'          => 'Commande.GestionCommande.index',
            'tableau_pj'         => $tabTypePj??[],
            'titreModule'        => $titreModule,
            'titre'              => $titre,
            'id'                 => $idCommande,
            'pj'               => $post,
            'pathAnnuler'        => $this->router->generateUri('Commande.PieceJointe.index', ['idCommande' => $idCommande]),
            'pathEnregistrement' => $this->router->generateUri('GlobalApplication.AjaxPiecesJointes.enregistrementCreationPJ', [ 'MODULE' => 'CDE', 'id' => $idCommande, 'action' => 'creation']),
            'erreur'             => '',
        ]);
    }

    public function editAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $post  = $this->request->getParsedBody();

        $trad = $this->getTranslationService();

        $titreModule = $trad->t('Commandes');
        $titre = $trad->t('Commande'). ' '.$idCommande;
        
        /* Données PJ */
        $value=[
            "NO_ORDRE" => $post['noOrdre'],
            "NO_CA" => $idCommande,
        ];
        $facPijo = new CaPijo($this->pdo);
        $pj = $facPijo->find($value);
        
        /** Pour chargé les menu déroulent **/
        $typePj = new \Entity\Model\PJTypes($this->pdo);
        $typePj = $typePj->fetchAll();
        foreach ($typePj as $value) {
            $tabTypePj[$value["PJ_TYPE"]]=$value["PJLIBELLE"];
        }
        /* ***************************** */;
                
        \Helpers\Ariane\ArianeSub::generate(1, 1, $trad->t('Modification Pièce Jointe'), $_SERVER['REQUEST_URI'], 1);
        
        return $this->renderer->render('@GlobalApplication/Piecesjointes/creation-pieces-jointes', [
            'menuActive'   => 'CollecteBesoins',
            'menuLeft'     => 'Commande.GestionCommande.index',
            'tableau_pj' => $tabTypePj??[],
            'titreModule' => $titreModule,
            'titre' => $titre,
            'id' => $idCommande,
            'post' => $post,
            'pj' => $pj,
            'pathAnnuler'        => $this->router->generateUri('Commande.PieceJointe.index', ['idCommande' => $idCommande]),
            'pathEnregistrement' => $this->router->generateUri('GlobalApplication.AjaxPiecesJointes.enregistrementCreationPJ', [ 'MODULE' => 'CDE', 'id' => $idCommande, 'action' => 'modification']),
            'erreur' => '',
        ]);
    }

    public function deleteAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $post = $this->request->getParsedBody();
        
        $value=[
            "NO_ORDRE" => $post['option'],
            "NO_CA" => $idCommande,
        ];
        
        $facPijo = new CaPijo($this->pdo);
        $infoPJ = $facPijo->find($value);

        $facPijo->delete($value);

        $ficPJ = new Gestion_Fic_PJ($this->pdo);
        $ficPJ->deleteFichier($infoPJ['NOM_FIC']);
        
        $trad = $this->getTranslationService();
        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $trad->t('Votre pièce-jointe a été supprimée.'),
            'div_refresh' => 'pieces_jointes',
            'iconePopup' => 'information',
            'form_refresh' => 'formulaireGeneral',
            'refresh' => true,
        ]);
    }
}
