<?php

namespace Modules\Commande\MenuContextuel;

use Entity\Model\Dilispec;
use Entity\Model\Paravrac;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\MenuContextuel;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Modules\Commande\Rules\GestionCommande;
use Modules\GlobalApplication\Repository\LicenceOxalys;
use Skeleton\Router;

class GestionMenuContextuel extends MenuContextuel
{
    /**
     * @var array<mixed> $droit
     */
    private $droit;

    /**
     * @var array<mixed> $parametrage
     */
    private $parametrage;

    /**
     * @var \stdClass $confgiAxeImp
     */
    private $confgiAxeImp;

    /**
     * @param array<mixed> $droit
     */
    public function __construct(\PDO $pdo, Router $router, ITrad $trad, $droit)
    {
        parent::__construct($pdo, $router, $trad);
        
        $this->confgiAxeImp = (new Paravrac($this->pdo))->getCommandeAxeImpConfig($_SESSION['Session_SocUsr']);

        if ($droit) {
            $this->droit = $droit;
        } else {
            $this->droit = [
                'HA_CA_MVI' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_MVI'),
                'HA_CA_CMV' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_CMV'),
                'HA_CA_VAL' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_VAL'),
                'HA_CA_CRA' => Roles::droitsUtilisateur($this->pdo, 'HA_CA_CRA'),
                'HA_SE_SATT' => Roles::droitsUtilisateur($this->pdo, 'HA_SE_SATT'),
            ];
        }

        $this->parametrage = [
            'isNoteFourActive'      => (new LicenceOxalys($this->pdo))->noteFourActive(),
            'hasTermPaieActive'     => (new LicenceOxalys($this->pdo))->termPaieActive(),
            'csModApresVal'         => ChampSupp::modifCsPostVal($this->pdo, 'CA_ENTET', 'CA_LIGNE'),
        ];
    }

    /**
     * @param array<mixed> $commande
     * @return array<mixed>
     */
    public function generateCol($commande = [])
    {
        $menuContextuel = [];
        
        $commandeId = $commande['NO_CDE'];

        $libCommande = $commandeId;
        if ($commande['AVENANT']) {
            $libCommande .= ' - '.$commande['AVENANT'];
        }

        /* Principal */

        if ($this->droit['HA_CA_VIS']) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoPreview',
                'libelle' => $this->trad->t('Visualiser'),
                'lien' => $this->router->generateUri('Commande.Commande.article', ['idCommande' => $commandeId]),
            ];
        }

        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_CMV'] || ($this->droit['HA_CA_MVI']) && $_SESSION["Session_Login"] ==$commande['ACH'])) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoEdit',
                'lien'  => $this->router->generateUri('Commande.ModificationCommande.index', ['idCommande' => $commandeId]),
                'libelle' => $this->trad->t('Modifier'),
            ];
        }

        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_VAL'] or $this->droit['HA_CA_MVI'])) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoValidate',
                'libelle' => $this->trad->t('Valider'),
                'lien' => false,
                'lienJs' => "validateCommande('".($this->router->generateUri('Commande.GestionCommande.ajaxValidate', ['idCommande' => $commandeId]))."', '".($commandeId)."', '".($commande['AVENANT'])."');",
            ];
        }

        if (($commande['ETAT_CDE'] == 'V' || $commande['ETAT_CDE'] == 'Z') && Sql::toBool($commande['SIGNEE']) && ($this->droit['HA_CA_IMP'] or $this->droit['HA_CA_MVI'])) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoSend',
                'libelle' => $this->trad->t('Envoyer'),
                'lien' => false,
                'lienJs' => "ajaxPopup('".($this->router->generateUri('Commande.Commande.popupImpression', ['idCommande' => $commandeId, 'routage' => 'envoyer']))."', '".$this->trad->t('Routage de la commande N°')." ".$libCommande."')",
            ];
        }

        $creationBROk = false;
        
        if (($commande['ETAT_CDE'] == 'L' || $commande['ETAT_CDE'] == 'E') && Roles::droitsUtilisateur($this->pdo, 'HA_BR_CM')) {
            if ($_SESSION['BR_UniqSesDemandes']) {
                if ($commande['ACH'] == $_SESSION['Session_Login']) {
                    $creationBROk = true;
                } else {
                    if ($commande['nbDARattachees'] > 0) {
                        $creationBROk = true;
                    }
                }
            } else {
                $creationBROk = true;
            }
        }

        if ($creationBROk) {
            $menuContextuel['listePrincipal'][] = [
                'icone'     => 'pictocreate',
                'libelle'   => $this->trad->t('Créer un bon de réception'),
                'lien'      => $this->router->generateUri('Reception.CreationBR.creatEdit', ['order' => $commandeId, 'type' => 'R', 'mode' => 'C', 'init' => '1'])
            ];
        }

        if ($this->droit['HA_CA_VEV']) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoList',
                'lien'  => $this->router->generateUri('Commande.Event.suivi', ['idCommande' => $commandeId]),
                'libelle' => $this->trad->t('Suivi'),
            ];
        }


        /** Général */
        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'titre' => true,
            'libelle' => $this->trad->t('Général'),
        ];


        if ($this->droit['HA_CA_CMV']) {
            $menuContextuel['listeSecondaire']['COL1']['li'][] = [
                'libelle' => $this->trad->t('Dupliquer'),
                'lien' => $this->router->generateUri('Commande.CreationCommande.formDuplicate', ['commandeId' => $commandeId]),
            ];
        }

        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'libelle' => $this->trad->t('Documents rattachés'),
            'lien' => $this->router->generateUri('GlobalApplication.DocumentRattaches.document', ['MODULE' => 'Commande', 'id' => $commandeId]),
        ];

        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'libelle' => $this->trad->t('Pièces jointes'),
            'lien' => $this->router->generateUri('Commande.PieceJointe.index', ['idCommande' => $commandeId]),
        ];

        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'libelle' => $this->trad->t('Bloc Note'),
            'lien' => false,
            'lienJs' => "ajaxPopup ('".($this->router->generateUri('Commande.GestionCommande.blocNote', ['idCommande' => $commandeId]))."', '".$this->trad->t('Bloc Note')."', '', '')",
        ];

        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'libelle' => $this->trad->t('Incidents'),
            'lien' => $this->router->generateUri('GlobalApplication.Incidents.incidents', ['MODULE' => 'Commande', 'id' => $commandeId]),
        ];

        if ($commande['INCIDENT'] !== '0') {
            $menuContextuel['listeSecondaire']['COL1']['li'][] = [
                'libelle' => $this->trad->t('Editer incidents commande'),
                'lien' => $this->router->generateUri('GlobalApplication.Incidents.editSheet', ['MODULE' => 'Commande', 'id' => $commandeId]),
                'old_lienJs' => $this->ajaxPopup(
                    $this->router->generateUri('GlobalApplication.Incidents.editSheet', ['MODULE' => 'Commande', 'id' => $commandeId]),
                    $this->trad->t('Fiche incidents')
                )
            ];
        }

        if ($commande['ETAT_CDE'] == 'E' && $commande['EVE_VAL'] != '0' && $this->droit['HA_CA_CRA'] && $commande['BLOC_MODIF_CDE_LIV'] != 'O') {
            $menuContextuel['listeSecondaire']['COL1']['li'][] = [
                'libelle' => $this->trad->t('Créer un avenant'),
                'lienJs' => "ajaxPopup('"
                    .($this->router->generateUri(
                        'Commande.GestionCommande.popupCreateAvenant',
                        ['idCommande' => $commandeId]
                    ))."', '"
                    .$this->trad->t('Créer un avenant sur la commande N°')." ".$libCommande."')",
            ];
        }

        $menuContextuel['listeSecondaire']['COL1']['li'][] = [
            'libelle' => $this->trad->t('Affichage de la commande chiffrée'),
            'lien' => $this->router->generateUri('Commande.GestionCommande.impressionPDF', ['idCommande' => $commandeId, 'mode' => 'chiffree']),
            'target'    => '_blank',
        ];

        $menuContextuel['listeSecondaire']['COL2']['li'][] = [
            'titre' => true,
            'libelle' => $this->trad->t('Modification'),
        ];
        if ($commande['DTE_VALID'] != '00000000'
            && $this->droit['HA_CA_CMV']
            && $this->parametrage['csModApresVal']
        ) {
            $menuContextuel['listeSecondaire']['COL2']['li'][] = [
                'libelle' => $this->trad->t('Modifier les CS'),
                'lien' => $this->router->generateUri('GlobalApplication.CS.editCS', [
                    'MODULE' => 'CA',
                    'id' => $commandeId
                ]),
            ];
        }

        

        if ($this->droit['HA_CA_MIM'] && $commande['DTE_VALID'] != '00000000'
            // At least one AxeImp must not be locked by the Model
            && !(
                Sql::toBool($commande['MCa_SIVER'] ?? false)
                && Sql::toBool($commande['MCa_CDCVER'] ?? false)
                && Sql::toBool($commande['MCa_SCAVER'] ?? false)
            )
            // At least one AxeImp must be activated
            && ($this->confgiAxeImp->SectImp->isActive || $this->confgiAxeImp->CodeCompl->isActive || $this->confgiAxeImp->SousCompteAna->isActive)
        ) {
            $menuContextuel['listeSecondaire']['COL2']['li'][] = [
                'libelle' => $this->trad->t('Modifier imputations'),
                'lien' => $this->router->generateUri(
                    'Commande.Imputation.formUpdate',
                    ['commandeId' => $commandeId]
                ),
            ];
        }

        if ($this->droit['HA_CA_DPR'] && in_array($commande['ETAT_CDE'], ['E','L'])) {
            $menuContextuel['listeSecondaire']['COL2']['li'][] = [
                'libelle' => $this->trad->t('Modifier les dates de livraison'),
                'lien' => $this->router->generateUri(
                    'Commande.Planning.formUpdate',
                    ['commandeId' => $commandeId]
                ),
            ];
        }

        if (GestionCommande::canUpdateCommandeTypDoc($this->pdo, $commande)) {
            $menuContextuel['listeSecondaire']['COL2']['li'][] = [
                'libelle' => $this->trad->t('Changer le type de document'),
                'lienJs' => $this->ajaxPopup(
                    $this->router->generateUri(
                        'Commande.GestionCommande.updateDocTypePopup',
                        ['commandeId' => $commandeId]
                    ),
                    Trad::strBuild(
                        $this->trad->t('Modification du type de la commande N° @1@'),
                        $commandeId
                    )
                ),
            ];
        }

        /* Avancé */
        $menuContextuel['listeSecondaire']['COL3']['li'][] = [
            'titre' => true,
            'libelle' => $this->trad->t('Avancé'),
        ];
        if (($commande['ETAT_CDE'] == 'E' || $commande['ETAT_CDE'] == 'L' || $commande['ETAT_CDE'] == 'S') && $this->droit['HA_CA_SPM']) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('(Dé)solder physiquement'),
                'lien' => $this->router->generateUri('Commande.solderCommande.physiquement', ['idCommande' => $commandeId]),
            ];
        }
        if (($commande['ETAT_CDE'] == 'E' || $commande['ETAT_CDE'] == 'L' || $commande['ETAT_CDE'] == 'S') &&
            (($this->droit['HA_CA_SFM'] && $commande['DTE_VALID'] != '00000000' && $commande['ETAT_CDE'] != 'Z' && $commande['ETAT_CDE'] != 'F') ||
            ($this->droit['HA_CA_DFM'] && ($commande['ETAT_CDE'] == 'Z' || $commande['ETAT_FIN'] == 'F' && $commande['DTE_VALID'] != '00000000' )))) {
                $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                    'libelle' => $this->trad->t('(Dé)solder financièrement'),
                    'lien' => $this->router->generateUri('Commande.Commande.soldeFinancierLigne', ['idCommande' => $commandeId]),
                ];
        }
        if ($commande['ETAT_CDE'] == 'A' && !Sql::boolSql($commande['SIGNEE']) && !Sql::boolSql($commande['REFUSEE']) && $this->droit['HA_CA_SUP']) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Supprimer'),
                'lienJs' => $this->popupConfirm(
                    false,
                    $this->router->generateUri('Commande.ajaxGestionCommande.suppresionCommande', ['idCommande' => $commandeId]),
                    $this->trad->t('Etes-vous sûr de vouloir supprimer la commande')." ".$libCommande." ?",
                    false,
                    'commandes',
                    '',
                    false,
                    'filtre_commande'
                )
            ];
        }
        if (($commande['ETAT_CDE'] == 'E' || $commande['ETAT_CDE'] == 'V')
            && $this->droit['HA_CA_DEV']
            && ($commande['BLOC_MODIF_CDE_LIV'] != 'O' && $commande['BR_EXIST'] == '0' && $commande['FAC_EXITS'] == '0' && $commande['FAC_LIG_EXISTS'] == '0')
        ) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Dévalider'),
                'lienJs' => $this->popupConfirm(
                    false,
                    $this->router->generateUri('Commande.ajaxGestionCommande.devaliderCommande', ['idCommande' => $commandeId]),
                    $this->trad->t('Etes-vous sûr de vouloir dévalider la commande')." ".$libCommande." ?",
                    false,
                    'commandes',
                    '',
                    false,
                    'filtre_commande'
                )
            ];
        }
        if (($commande['ETAT_CDE'] == 'E') && $commande['LIVR_PART'] == 0 && $this->droit['HA_CA_ANN']) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Annuler'),
                'lienJs' => "ajaxPopupV2('".($this->router->generateUri('Commande.ajaxGestionCommande.popupAnnulerCommande', ['idCommande' => $commandeId]))."', 'filtre_commande', '".$this->trad->t('Annuler la commande N°')." ".$libCommande."');",
            ];
        }
        if ($commande['AVENANT']) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Visualisation historisée'),
                'lienJs' => "redirectJSWithPost( '".($this->router->generateUri('Commande.Liste.listeEnteteHistorisees'))."' , { 'filter_NO_CDE' : '".($commandeId)."' });",
            ];
        }

        
        if ($this->droit['HA_CA_SAR'] && $commande['ETAT_CDE'] == 'E' && $commande['DTE_AR'] == '00000000') {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Enregistrer un Accusé Réception'),
                'lien' => $this->router->generateUri('Commande.AccRecep.formCreation', ['commandeId' => $commandeId]),
            ];
        } elseif ($this->droit['HA_CA_SAR'] && $commande['DTE_AR'] != '00000000') {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->droit['HA_CA_MAR'] ?
                    $this->trad->t('Visualiser/Modifier l’Accusé Réception') :
                    $this->trad->t('Visualiser l’Accusé Réception'),
                'lienJs' => $this->ajaxPopup(
                    $this->router->generateUri('Commande.AccRecep.detail', ['commandeId' => $commandeId]),
                    Trad::strBuild($this->trad->t('Accusé réception de @2@la commande n°@1@'), $libCommande)
                ),
            ];
        }

        if ($this->droit['HA_TP_SAIS'] && $this->parametrage['hasTermPaieActive'] && !empty($commande['TermPaie'])) {
            if ($commande['DTE_VALID'] != '00000000' && trim($commande['ETAT_FIN']) == '') {
                $menuContextuel['listeSecondaire']['COL2']['li'][] = [
                    'libelle' => $this->trad->t('Modifier l’avancement des termes de paiement'),
                    'lien' => $this->router->generateUri('Commande.TermPaie.formUpdate', ['commandeId' => $commandeId]),
                ];
            } else {
                $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                    'libelle' => $this->trad->t('Voir les termes de paiement'),
                    'lien' => $this->router->generateUri('Commande.TermPaie.visualize', ['commandeId' => $commandeId]),
                ];
            }
        }

        if ($this->parametrage['isNoteFourActive'] && Roles::droitsUtilisateur($this->pdo, 'HA_NOT_NM')) {
            // Case : Notation is NOT active (ever) for this commande
            if (empty($commande['Notation_NO_CDE'])) {
                // Popup activation notation
                $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                    'libelle' => $this->trad->t('Noter le fournisseur'),
                    'lienJs' => 'ajaxJsonPopup('
                        .json_encode($this->router->generateUri(
                            'Commande.Notation.popupConfirmActivate',
                            ['commandeId' => $commandeId]
                        ))
                        .')',
                ];
            // Case : Notation is Active for this commande and has an on going manual notation
            } elseif ($commande['countActiveNotation'] != 0) {
                // Case : Commande has a currently active notation
                // Form notation
                $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                    'libelle' => $this->trad->t('Noter le fournisseur'),
                    'lien' => $this->router->generateUri('Commande.Notation.formCreate', ['commandeId' => $commandeId]),
                ];
            // Case : Commande has a notation (not active anymore)
            } else {
                $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                    'libelle' => $this->trad->t('Visualisation notation commande'),
                    'lien' => $this->router->generateUri('Commande.Notation.detail', ['commandeId' => $commandeId]),
                ];
            }
        }
        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_CMV'] || ($this->droit['HA_CA_MVI']) && $_SESSION["Session_Login"] ==$commande['ACH'])) {
            $menuContextuel['listeSecondaire']['COL3']['li'][] = [
                'libelle' => $this->trad->t('Import de lignes'),
                'lien' => $this->router->generateUri('Commande.ImportLigneCommande.importLigne', ['idCommande' => $commandeId]),
            ];
        }

        if ($this->droit['HA_SE_SATT']
            /* Commande en signature */
            && $commande['ETAT_CDE'] == 'V'
            && Sql::toBool($commande['SIGNEE']) == false
            && Sql::toBool($commande['REFUSEE']) == false
        ) {
            $menuContextuel['listeSecondaire']['COL1']['li'][] = [
                'libelle' => $this->trad->t('Signataires attendus'),
                'lienJs' => $this->ajaxPopup(
                    $this->router->generateUri(
                        'Signature.SignatureCde.signatureAttendu',
                        ['idDoc' => $commandeId]
                    ),
                    $this->trad->t('Signataires attendus pour la commande N°').' '.$commandeId
                ),
            ];
        }

        return $menuContextuel;
    }

    /**
     * @param array<mixed> $commande
     * @return array<mixed>
     */
    public function lightGenerate($commande)
    {
        $menuContextuel = [];
        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_CMV'] || ($this->droit['HA_CA_MVI']) && $_SESSION["Session_Login"] ==$commande['ACH'])) {
            $menuContextuel['listeSecondaire'][] = [
                'icone' => 'pictoEdit',
                'lien'  => $this->router->generateUri('Commande.ModificationCommande.index', ['idCommande' => $commande['NO_CDE']]),
                'libelle' => $this->trad->t('Modifier'),
            ];
        }
        
        if ($commande['ETAT_CDE'] == 'E' && $commande['EVE_VAL'] != '0' && $this->droit['HA_CA_CRA'] && ($commande['BLOC_MODIF_CDE_LIV'] != 'O' || $commande['nbBrCde'] == '0' )) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Créer un avenant'),
                'lienJs' => "ajaxPopup('"
                    .($this->router->generateUri(
                        'Commande.GestionCommande.popupCreateAvenant',
                        ['idCommande' => $commande['NO_CDE']]
                    ))."', '"
                    .$this->trad->t('Créer un avenant sur la commande N°')." ".$commande['NO_CDE']."')",
            ];
        }
         
        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_VAL'] or $this->droit['HA_CA_MVI'])) {
            $menuContextuel['listeSecondaire'][] = [
                'icone' => 'pictoValidate',
                'libelle' => $this->trad->t('Valider'),
                'lien' => false,
                'lienJs' => "validateCommande('".($this->router->generateUri('Commande.GestionCommande.ajaxValidate', ['idCommande' => $commande['NO_CDE']]))."', '".($commande['NO_CDE'])."', '".($commande['AVENANT'])."');",
            ];
        }

        if ($commande['ETAT_CDE'] == 'A' && ($this->droit['HA_CA_CMV'] || ($this->droit['HA_CA_MVI']) && $_SESSION["Session_Login"] ==$commande['ACH'])) {
            $menuContextuel['listeSecondaire'][]= [
                'libelle' => $this->trad->t('Import de lignes'),
                'lien' => $this->router->generateUri('Commande.ImportLigneCommande.importLigne', ['idCommande' => $commande['NO_CDE']]),
            ];
        }

        return $menuContextuel;
    }
}
