<?php

namespace Modules\Facture\MenuContextuel;

use Entity\Model\Paravrac;
use Helpers\Outil\MenuContextuel;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Skeleton\Router;

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

    /**
     * @var bool|string $typePreaffectationMail
     */
    public $typePreaffectationMail;

    /**
     * @param array<mixed> $droit
     */
    public function __construct(\PDO $pdo, Router $router, ITrad $trad, $droit)
    {
        parent::__construct($pdo, $router, $trad);
        $this->droit = $droit;

        $this->typePreaffectationMail = (new Paravrac($this->pdo))->getTypePreaffectation();
    }

    /**
     * @param array<mixed> $fac
     * @param array<mixed> $infoPagination
     * @return array<mixed>
     */
    public function generate($fac, $infoPagination)
    {
        $menuContextuel = [];
        
        $isRefuse = Sql::toBool($fac['REFUSEE_FE']);
        $isAnnule = Sql::toBool($fac['ANNULE']);

        $isLocked = $isRefuse || $isAnnule;
        
        if ($this->droit['HA_FA_CMOD']
            && Sql::boolSql($fac['AFF_VALID']) == 0
            && ! $isLocked
        ) {
            $lienValidation = null;
            $routeParamCom = [
                'numFact' => $fac['NUM_FACT'],
                'fournisseur' => $fac['CODE_FOUR'],
                'societe' => $fac['CODE_STE'],
                'numCde' => $fac['NUM_CDE'] == '0'? 'all':$fac['NUM_CDE']
            ];
            if (sql::boolSql($fac['FAC_LAD']) && $fac['cdeLad'] > 0) {
                $lienValidation = $this->router->generateUri(
                    'Facture.CreationFacture.choixAffectationLad',
                    ['action' => 'lad'] + $routeParamCom
                );
            } else {
                if ($fac['TYPE'] == 'F') {
                    $lienValidation = $this->router->generateUri(
                        'Facture.CreationFacture.choixCommande',
                        ['action' => 'modification']
                        + (Sql::boolSql($fac['ACOMPTE']) ? ['acompte' => true] : [])
                        + $routeParamCom
                    );
                } else {
                    $lienValidation = $this->router->generateUri(
                        'Facture.CreationFacture.choixAvoir',
                        ['action' => 'modification'] + $routeParamCom
                    );
                }
            }
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoEntryassignments',
                'libelle' => $this->trad->t('Saisie Affectations'),
                'lien' => $lienValidation
            ];
        }

        if ($this->droit['HA_FA_VALI']
            && (
                sql::boolSql($fac['ENT_COMPT'])==false
                || sql::boolSql($fac['AFF_COMPT']) == false
                || sql::boolSql($fac['BAP_COMPT']) == false
            )
            && ! $isLocked
        ) {
            $menuContextuel['listePrincipal'][] = [
                'icone' => 'pictoValidationManagement',
                'libelle' => $this->trad->t('Gestion Validation'),
                'lienJs' => $this->ajaxPopup(
                    $this->router->generateUri('Facture.popup.choixValidationFacture', [
                        'numFact' => $fac['NUM_FACT'],
                        'fournisseur' => $fac['CODE_FOUR']
                    ]),
                    Trad::strBuild(
                        $this->trad->t('Validation de @1@ n° @2@'),
                        match ($fac['TYPE']) {
                            'F' => $this->trad->t('la facture'),
                            'C' => $this->trad->t('la facture d\'acompte'),
                            'A' => $this->trad->t('l\'avoir'),
                            default => $this->trad->t('l\'avoir'),
                        },
                        $fac['NUM_FACT']
                    )
                ),
            ];
        }

        $menuContextuel['listePrincipal'][] = [
            'icone' => 'pictoList',
            'libelle' => $this->trad->t('Suivi'),
            'lien' => $this->router->generateUri('Facture.GestionFacture.suivi', ['numFact' => $fac['NUM_FACT']]),
        ];


        if ($this->droit['HA_FA_VISU'] && $this->droit['U8zXaa77yt']) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Visualiser'),
                'lien' => $this->router->generateUri('Facture.GestionFacture.detail', ['numFact' => $fac['NUM_FACT']]),
            ];
        }

        if ($this->droit['HA_FA_CMOD'] && !sql::toBool($fac['ENT_VALID']) && !sql::toBool($fac['hasAvoir'])) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Modifier'),
                'lien' => $this->router->generateUri('Facture.ModificationFacture.modificationFacture', ['numFact' => $fac['NUM_FACT']]),
            ];
        }

        if ($this->droit['HA_FA_VAEC'] && sql::boolSql($fac['ENT_VALID']) == true && sql::boolSql($fac['ENT_COMPT']) == false) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Modification date écheance'),
                'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.popup.modifierDateEcheance', ['numFact' => $fac['NUM_FACT']]))."', '".$this->trad->t('Modification date écheance')."')",
            ];
        }

        if (($this->droit['HA_FA_SUPP'] || $this->droit['HA_FA_SUPC']) &&
            (sql::boolSql($fac['ENT_COMPT']) == false && sql::boolSql($fac['AFF_COMPT']) == false && sql::boolSql($fac['BAP_COMPT']) == false) &&
            (sql::boolSql($fac['ENT_VALID']) == false && sql::boolSql($fac['AFF_VALID']) == false && sql::boolSql($fac['BON_A_PAY']) == false && sql::boolSql($fac['LITIGE']) == false)
        ) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Supprimer'),
                'lien' => '',
                'lienJs' => $this->popupConfirm(
                    false,
                    $this->router->generateUri('Facture.popup.supprimerFacture', ['numFact' => $fac['NUM_FACT'], 'page' => $infoPagination['page']]),
                    Trad::strBuild(
                        $this->trad->t('Voulez-vous vraiment supprimer @1@ n°@2@ ?'),
                        match ($fac['TYPE']) {
                            'A' => $this->trad->t('l\'avoir'),
                            'C' => $this->trad->t('la facture d\'acompte'),
                            default => // 'F'
                                $this->trad->t('la facture'),
                        },
                        $fac['NUM_FACT']
                    ),
                    true,
                    'refreshTable',
                    '',
                    true,
                    'filtre_facture'
                )
            ];
        }

        if ($this->droit['HA_FA_LIT']
            && ! $isRefuse
            && sql::boolSql($fac['BON_A_PAY']) == false
        ) {
            if (sql::boolSql($fac['LITIGE']) == true) {
                $menuContextuel['listeSecondaire'][] = [
                    'libelle' => $this->trad->t('Lever le litige'),
                    'lienJs' => $this->ajaxPopup(
                        $this->router->generateUri(
                            'GlobalApplication.Incidents.popupLitigeDelete',
                            ['numFact' => $fac['NUM_FACT']]
                        ),
                        Trad::strBuild(
                            $this->trad->t('Lever le litige pour la facture N°@1@'),
                            $fac['NUM_FACT']
                        )
                    ),
                ];
                $menuContextuel['listeSecondaire'][] = [
                    'libelle' => $this->trad->t('Annuler la facture'),
                    'route' => 'Facture.Facture.formAnnuler',
                    'routeParam' => ['numFact' => $fac['NUM_FACT']]
                ];
            } else {
                $menuContextuel['listeSecondaire'][] = [
                    'libelle' => $this->trad->t('Créer un litige'),
                    'lien' => $this->router->generateUri(
                        'GlobalApplication.Incidents.formLitigeCreate',
                        ['numFact' => $fac['NUM_FACT']]
                    ),
                ];
            }
        }

        if ($this->droit['HA_FA_CMOD']
            && ! $isLocked
            && ! Sql::toBool($fac['ENT_VALID'])
            && ! Sql::toBool($fac['AFF_VALID'])
        ) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Refuser'),
                'lien' => $this->router->generateUri(
                    'Facture.GestionFacture.formRefus',
                    ['numFact' => $fac['NUM_FACT']]
                ),
            ];
        }

        if (in_array($fac['TYPE'], ['F', 'C']) && $fac['ligneManuelle'] > 0) {
            $titrePopup = $this->trad->t('Commande de régularisation pour la facture n°').' '.$fac['NUM_FACT'];
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Commande de régularisation'),
                'lien' => '',
                'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.popup.interrogationAjoutCdeDeRegul', ['numFact' => $fac['NUM_FACT']]))."', '".$titrePopup."', '', '', {'numFact' : '".$fac['NUM_FACT']."','codeSte' : '".$fac['CODE_STE']."', 'codeFour' : '".$fac['CODE_FOUR']."'})",
            ];
        }

        $menuContextuel['listeSecondaire'][] = [
            'libelle' => $this->trad->t('Impression unitaire'),
            'lien' => $this->router->generateUri('Facture.GestionFacture.impressionFacture', ['numFact' => $fac['NUM_FACT'], 'codeSte' => $fac['CODE_STE']]),
            'target'    => '_blank',
        ];

        if (sql::boolSql($fac['ATT_SIG']) == true) {
            if ($fac['TYPE'] == 'F') {
                $titrePopup = $this->trad->t('Signataires pour la facture n°');
            } elseif ($fac['TYPE'] == 'C') {
                $titrePopup = $this->trad->t('Signataires pour la facture d\'acompte n°');
            } else {
                $titrePopup = $this->trad->t('Signataires pour l\'avoir n°');
            }

            $titrePopup .= ' '.$fac['NUM_FACT'];

            
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Signataires attendus'),
                'lien' => '',
                'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.GestionFacture.popupListSignatPending', ['numFact' => $fac['NUM_FACT']]))."', '".$titrePopup."')",
            ];
        }

        $titrePopup = $this->trad->t('Bloc Note');
        $menuContextuel['listeSecondaire'][] = [
            'libelle' => $this->trad->t('Bloc Note'),
            'lien' => '',
            'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.popup.blocNote', ['numFact' => $fac['NUM_FACT']]))."', '".$titrePopup."')",
        ];

        $menuContextuel['listeSecondaire'][] = [
            'libelle' => $this->trad->t('Documents rattachés'),
            'lien' => $this->router->generateUri('Facture.DocumentsRattaches.docRattache', ['numFact' => $fac['NUM_FACT']]),
        ];

        $menuContextuel['listeSecondaire'][] = [
            'libelle' => $this->trad->t('Pièces-jointes'),
            'lien' => $this->router->generateUri('Facture.PiecesJointes.piecesJointes', ['numFact' => $fac['NUM_FACT']]),
        ];

        if (sql::boolSql($fac['AFF_TMP']) == true && $fac['FAC_CBY'] == $_SESSION["Session_Login"]) {
            if ($this->typePreaffectationMail == 'L') {
                $titrePopup = $this->trad->t('Préaffectation : Mail ach./dem.');
                $postPopup = "{'numFact' : '".$fac['NUM_FACT']."', 'type' : 'L' }";
            } elseif ($this->typePreaffectationMail == 'D') {
                $titrePopup = $this->trad->t('Préaffectation : Mail demandeurs');
                $postPopup = "{'numFact' : '".$fac['NUM_FACT']."', 'type' : 'D' }";
            } else {
                $titrePopup = $this->trad->t('Préaffectation : Mail acheteurs');
                $postPopup = "{'numFact' : '".$fac['NUM_FACT']."', 'type' : '' }";
            }

            
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $titrePopup,
                'lien' => '',
                'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.popup.interrogationPreaffectationMail'))."', '".$titrePopup."', '','', ".$postPopup.")",
            ];
        }

        $titrePopup = $this->trad->t('Charger une image');
        $menuContextuel['listeSecondaire'][] = [
            'libelle' => $this->trad->t('Charger une image'),
            'lien' => '',
            'lienJs' => "ajaxPopup('".($this->router->generateUri('Facture.popup.uploadImageFacture', ['numFact' => $fac['NUM_FACT']]))."', '".$titrePopup."')",
        ];

        if ($fac['FIC_LAD'] != '' && $fac['urlImageFacture'] != '') {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Voir Image'),
                'lien' => $fac['urlImageFacture'],
                'target'    => '_blank',
            ];
        }

        if ($this->droit['HA_FA_REG'] && ! $isLocked) {
            $menuContextuel['listeSecondaire'][] = [
                'libelle' => $this->trad->t('Règlement'),
                'lien' => $this->router->generateUri('Facture.ReglementFacture.reglementFacture', ['numFact' => $fac['NUM_FACT']]),
            ];
        }
        

        $menuSpecifique = \Helpers\Additional\Specifique\Specifique::specifique(
            '\\Modules\\Facture\\MenuContextuel\\GestionMenuContextuelSpecifique',
            'gestionMenuContextuelSpecifique',
            $this->pdo,
            $this->router,
            $this->trad,
            $fac
        );

        if ($menuSpecifique) {
            $menuContextuel['listeSecondaire'][] = $menuSpecifique;
        }

        return $menuContextuel;
    }
}
