<?php
namespace Modules\GlobalApplication\Controller;

use Entity\Model\CaEvent;
use Entity\Model\FactEnt;
use Entity\Model\Fourninc;
use Entity\Model\Hastutil;
use Helpers\Log\LogSysteme;
use Modules\Ajax\Repository\Listes;
use Modules\Commande\Repository\Commande;
use Modules\GlobalApplication\Service\IncidentService;
use Skeleton\Controller\Controller;
use Entity\Model\Fourniss;
use Entity\Model\Incident;
use Entity\Model\CatIncid;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Modules\Fournisseur\Outil\DroitUtilisateur;
use Helpers\Ariane\ArianeSub;
use Modules\GlobalApplication\Repository\Incidents;
use Entity\Model\CaEntet;
use Entity\Model\CaLigne;
use Entity\Model\BrRecep;
use Entity\Model\BrLigne;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Modules\Commande\Repository\CommandeEventRepo;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Sql;
use Helpers\Parametres\Constante;
use Modules\GlobalApplication\MenuContextuel\IncidentMenuContextuel;
use Modules\GlobalApplication\WebService\Incidents as WebServiceIncidents;
use Modules\Reception\Service\IncidentService as ServiceIncidentService;

class IncidentsController extends Controller
{
    public function incidentsAction() : string
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $menuActifUrl = $this->request->getAttribute('menuActif');
        $menuLeftUrl = $this->request->getAttribute('menuLeft');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $btnAjouter = true;

        $menuLeft = '';
        $menuActif = '';
        $sousTitre = false;
        
        if ($module=='Fournisseur') {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);
            
            $titre =$trad->t('Fournisseur');
            
            $libelle = $fournis["RS"];
            $Chps_Filter = 'FOU';
            
            $menuActif = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            
            $DroitUtilisateur = new DroitUtilisateur($this->router);

            $DroitUtilisateur->DroitUtilisateur($this->pdo, $fournis);
            
            ArianeSub::generate(1, 0, $trad->t('Incident'), $_SERVER['REQUEST_URI'], 1, $post);
        } elseif ($module=='MultiFournisseur') {
            $Chps_Filter='';
            $menuActif = 'Fournisseur';
            $menuLeft = 'GlobalApplication.Incidents.incidents';
            $titre = $trad->t('Incidents Fournisseur');
            
            Ariane::generate(0, $trad->t('Gestion'));
            ArianeSub::init();
        } elseif ($module=='Commande') {
            $menuActif = 'CollecteBesoins';
            $menuLeft = 'Commande.GestionCommande.index';
            
            $titre = $sousTitre = $trad->t('Commande');
            
            $Chps_Filter = 'NO_CDE';

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

            $libelleAvenant = $id.($commande['AVENANT']? ' - '.$commande['AVENANT']:'');
            ;
            
            Ariane::generate(2, $trad->t('Incident'), $post);
            ariane::setFocus($id);
            ArianeSub::init();
        } elseif ($module=='Reception' || $module=='suiviBR') {
            $menuActif = 'CollecteBesoins';
            $menuLeft = 'GlobalApplication.Incidents.incidents';
            
            if ($module) {
                $sousTitre = $titre = $trad->t('Réception');
            } else {
                $titre = $trad->t('Suivi');
            }
            
            $Chps_Filter = 'NO_BR';
                        
            Ariane::generate(2, $trad->t('Incidents'));
            Ariane::setFocus($id);
            ArianeSub::init();
        } elseif ($module=='Facture') {
            $menuActif = 'Facture';
            $menuLeft = 'GlobalApplication.Incidents.incidents';
            
            $Chps_Filter = 'NO_CDE';
            
            ArianeSub::generate(1, 0, $trad->t('Incident'), $_SERVER['REQUEST_URI'], 1, $post);

            Ariane::generate(1, $trad->t('Gestion des incidents'));
        } elseif ($module=='ChoixCommandeFacture') {
            $menuActif = 'Facture';
            // $menuLeft = 'GlobalApplication.Incidents.incidents';
            
            $btnAjouter = false;
            $titre = $trad->t('Factures et avoirs');
            $sousTitre = $trad->t('Commande');
            $Chps_Filter = 'NO_CDE';
            
            ArianeSub::generate(1, 0, $trad->t('Incident'), $_SERVER['REQUEST_URI'], 1, $post);
            Ariane::generate(4, $trad->t('Gestion des incidents'));
        }

        if (!isset($post['tri_DATE'])) {
            $post['tri_DATE'] = 'DESC';
        }
        
        $liste = (new Incidents($this->pdo))->listeTypeIncident(true);
        
        $listeIncident = [];
        foreach ($liste as $incident) {
            $listeIncident[$incident['COD_INC']] = $incident['LIBELLE'];
        }

        $liste = (new Incidents($this->pdo))->incidentCategoriesList(true);
        $listeCat = [];
        foreach ($liste as $CatIncid) {
            if ($CatIncid['CODE_CAT'] !== 'RELANCE' && $CatIncid['CODE_CAT'] !== 'LITFACT') {
                $listeCat[$CatIncid['CODE_CAT']] = $CatIncid['LIBELLE'];
            }
        }

        $incidentGlobal = (new Incidents($this->pdo))
            ->listeIncident($id, $post, $Chps_Filter);

        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($incidentGlobal, 0, $post, $this->renderer);
        
        if ($menuActifUrl != '') {
            $menuActif = $menuActifUrl;
        }

        if ($menuLeftUrl != '') {
            $menuLeft = $menuLeftUrl;
        }

        $menuContextuel = new IncidentMenuContextuel($this->pdo, $this->router, $this->getTranslationService(), $module);
        foreach ($incidentGlobal as &$inc) {
            $inc['menuContextuel'] = $menuContextuel->generate($inc, $id, $menuLeft, $menuActif);
        }

        if (!$sousTitre) {
            $sousTitre = $trad->t($module);
        }

        return $this->renderer->render('@GlobalApplication/Incidents/incidents', [
            'menuActive' => $menuActif,
            'post' => $post,
            'infoPagination' => $infopagination,
            "id" => $id,
            'idAvenant' => $libelleAvenant??'',
            "libelle" => $libelle??'',
            "incidents" => true,
            'listeIncident' => $listeIncident,
            'listeCat' => $listeCat,
            'IncidentFournisseur' => $incidentGlobal,
            
            'MODULE' => $module,
            'btnAjouter' => $btnAjouter,
            'titre' => $titre ?? $module,
            'sousTitre' => $sousTitre,
            //'multiFournisseur' => true,
        ]);
    }
    
    public function exportIncidentsAction() : string
    {
        $code = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $post = $this->request->getParsedBody();
        
        $Chps_Filter = '';
        switch ($module) {
            case 'Fournisseur':
                $Chps_Filter = 'FOU';
                break;
            case 'Commande':
                $Chps_Filter = 'NO_CDE';
                break;
            case 'Reception':
                $Chps_Filter = 'NO_BR';
                break;
            case 'MultiFournisseur':
            default:
                // $Chps_Filter = '';
        }
        
        $IncidentFournisseur = (new Incidents($this->pdo))
            ->listeIncidentExport($code, $post, $Chps_Filter);
        
        foreach ($IncidentFournisseur as &$value) {
            $value['DATE_CREATION'] = DATE::dateConverte($value['DATE_CREATION']);
            $value['DATE_LIVRAISON'] = DATE::dateConverte($value['DATE_LIVRAISON']);
            $value['DATE'] = DATE::dateConverte($value['DATE']);
        }
        
        $trad = $this->getTranslationService();

        $tab = [
            'DATE'                  => $trad->t('Date'),
            'CATEGORIE_INCIDENT'    => $trad->t('Categorie'),
            'INCIDENT'              => $trad->t('Incident'),
            'DESCRIPTION'           => $trad->t('Description'),
            'NIVEAU'                => $trad->t('Niveau'),
            'NUMERO_COMMANDE'       => $trad->t('Commande'),
            'NUM_LIGNE_COMMANDE'    => $trad->t('Ligne de commande'),
            'CODE_ARTICLE'          => $trad->t('Code article'),
            'NUMERO_BR'             => $trad->t('N° BR'),
            'NUM_LIGNE_BR'          => $trad->t('Ligne de BR'),
            'QTE_ANOMALIE'          => $trad->t('Quantité'),
            'DATE_CREATION'         => $trad->t('Date création de commande'),
            'DATE_LIVRAISON'        => $trad->t('Date livraison'),
            'LIBELLE_ARTLCE'        => $trad->t('Libellé article'),
            'COMMENTAIRE'           => $trad->t('Commentaire'),
            'CODE_FOURNISSEUR'      => $trad->t('Code fournisseur'),
            'LIBELLE_FOURNISSEUR'   => $trad->t('Libellé fournisseur'),
        ];

        \Helpers\ExportTo\Outils::gestionEmailAsync2(
            "incidents_".$code,
            $IncidentFournisseur,
            $this->JWTKEY,
            $this->router,
            $this->getTranslationService(),
            $tab
        );

        return 'ok';
    }
    
    public function creationIncidentsAction()
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');
        $menuActifUrl = $this->request->getAttribute('menuActif');
        $menuLeftUrl = $this->request->getAttribute('menuLeft');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if ($module=='Fournisseur') {
            $post['FOU'] = $id;
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($id);

            $titre = $trad->t('Fournisseur');
            
            $libelle = $fournis["RS"];
            
            $menuActif = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            
            $DroitUtilisateur = new DroitUtilisateur($this->router);

            $DroitUtilisateur->DroitUtilisateur($this->pdo, $fournis);
            
            ArianeSub::generate(2, 0, $trad->t('Nouvel incident'), $_SERVER['REQUEST_URI'], 1);
        } elseif ($module=='MultiFournisseur') {
            $id = 'ALL';
            $titre = $trad->t('Incidents Fournisseur');
            arianesub::init();
            
            Ariane::generate(1, $trad->t("Nouvel incident"));
            
            ArianeSub::init();
        } elseif ($module=='Commande') {
            $menuActif = 'CollecteBesoins';
            $menuLeft = 'Commande.GestionCommande.index';
            
            $titre = $trad->t('Commande');
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($id);
            
            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_egal_NO_CDE' => $id]);
            
            // Override read-only value
            $post = [
                'FOU' => $commande['CODE_FOU'],
                'NO_CDE' => $commande['NO_CDE'],
            ] + $post;
            
            $Chps_Filter = 'NO_CDE';
            Ariane::generate(2, $trad->t('Nouvel incident'));
        } elseif ($module=='Facture') {
            $menuActif = 'CollecteBesoins';
            $menuLeft = 'Commande.GestionCommande.index';
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($id);
            
            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_NO_CDE' => $id]);
            
            $post = [
                'FOU' => $commande['CODE_FOU'],
                'NO_CDE' => $commande['NO_CDE'],
            ] + $post;
            
            $Chps_Filter = 'NO_CDE';
            ArianeSub::generate(2, 0, $trad->t('Nouvel incident'), $_SERVER['REQUEST_URI'], 1);
        } elseif (in_array($module, ['Reception', 'suiviBR'])) {
            $titre = $trad->t('Réception');

            $br = new BrRecep($this->pdo);
            $br = $br->find($id);
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($br['NUM_CDE']);

            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_NO_CDE' => $br['NUM_CDE']]);

            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($commande['CODE_FOU']);
            
            $listeLigneBr = new BrLigne($this->pdo);
            $listeLigneBr = $listeLigneBr->fetchAll([], ['filter_NUM_BR' => $id]);
            
            // Override read-only value
            $post = [
                'NO_CDE' => $br['NUM_CDE'],
                'NO_BR' => $br['NUM_BR'],
                'FOU' => $commande['CODE_FOU'],
                'DTE_LIV' => $br['DATE_BL'],
            ] + $post;
            
            $Chps_Filter = 'NO_BR';

            if ($module=='suiviBR') {
                ArianeSub::init();
                Ariane::generate(3, $trad->t('Nouvel incident'));
                $menuActif = 'CollecteBesoins';
                $menuLeft = 'GlobalApplication.Incidents.incidents';
            } else {
                ArianeSub::generate(2, 0, $trad->t('Nouvel incident'), $_SERVER['REQUEST_URI'], 1);
                $menuActif = 'CollecteBesoins';
                $menuLeft = 'GestionReception';
            }
        }
        
        $liste = new Incidents($this->pdo);
        $liste = $liste->listeTypeIncident(true);
        foreach ($liste as $incident) {
            $listeIncident[$incident['COD_INC']] = $incident['LIBELLE'];
            $listeIncidentNiveau[$incident['COD_INC']] = $incident['NIVEAU'];
        }

        $liste = (new Incidents($this->pdo))->incidentCategoriesList(true);
        $listeCat = [];
        foreach ($liste as $CatIncid) {
            $listeCat[$CatIncid['CODE_CAT']] = $CatIncid['LIBELLE'];
        }

        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();

            $validator->isFalse($post['CODE'], $trad->t('L\'incident est obligatoire.'));
            $validator->isDate($post['DTE_OCCUR']);
            $validator->isStringAvecEspace('Description', $post['DESCRIPT'], 0, 60);
            $validator->isStringAvecEspace('Description', $post['CONTMEMO'], 0, 3000);

            if ($module=='Commande') {
                $brLigne = new BrLigne($this->pdo);
                if ($post['NUM_BR'] != '') {
                    $line = $brLigne->find(['NUM_BR' => $post['NUM_BR'], 'NO_PO_CDE' => $post['PO_CDE']], ['NO_PO_BR']);
                    $post['NO_BR'] = $post['NUM_BR'];
                    $post['PO_BR'] = $line['NO_PO_BR'] ?? $post['PO_BR'];
                    Date::dateToSql($post['DTE_LIV']);
                }
            } elseif (in_array($module, ['Reception', 'suiviBR'])) {
                $validator->isFloat('Qté en anomalie', $post['QTE_REFU'], Constante::formatQTE, false);
            }
            
            if ($validator->isValid()) {
                if ($menuActifUrl != '') {
                    $menuActif = $menuActifUrl;
                }
        
                if ($menuLeftUrl != '') {
                    $menuLeft = $menuLeftUrl;
                }

                $post['NIVEAU'] = $listeIncidentNiveau[$post['CODE']];
                
                (new IncidentService($this->pdo))->createIncident($module, $post);

                if ($post['NO_BR'] != '') {
                    $mailBR = Sql::paravrac($this->pdo, 'PARAMGEN', 'BR_INC_MAIL_ACH');

                    if ($mailBR=='O') {
                        $incident = (new Incident($this->pdo))->find($post['CODE']);
                        $catIncident = (new CatIncid($this->pdo))->find($incident['CODE_CAT']);

                        $arrayMail = [
                            'NO_CDE'        => $post['NO_CDE']??'',
                            'CODE_FOU'      => $post['FOU']??'',
                            'NO_PO_CDE'     => $post['PO_CDE']??'',
                            'NUM_BR'        => $post['NO_BR']??'',
                            'NO_PO_BR'      => $post['PO_BR']??'',
                            'DESIGN_ART'    => $post['DES_ART']??'',
                            'QTE_REFUS'     => $post['QTE_REFU']??'',

                            'TYP_INC'       => $incident['LIBELLE']??'',
                            'CAT_INC'       => $catIncident['LIBELLE']??'',
                        ];

                        (new ServiceIncidentService($this->pdo, $this->getTranslationService()))->sendIncMailAch($arrayMail);
                    }
                }

                return $this->redirect('GlobalApplication.Incidents.incidents', ['MODULE' => $module, "id" => $id,"menuLeft"=>$menuLeft, "menuActif"=> $menuActif]);
            } else {
                $ErreurValid = $validator->getError();
            }
        } else {
            $post['DTE_OCCUR']=date('Ymd');
            Date::dateToSql($post['DTE_LIV']);
        }

        if ($menuActifUrl != '') {
            $menuActif = $menuActifUrl;
        }

        if ($menuLeftUrl != '') {
            $menuLeft = $menuLeftUrl;
        }
        if ($module =='MultiFournisseur') {
            $incidentsFourn = (new Incidents($this->pdo))->getIncidentsByCategory('FOURN');
            $incidentsRelDoc = (new Incidents($this->pdo))->getIncidentsByCategory('RELDOC');
            $allIncidents = array_merge($incidentsFourn, $incidentsRelDoc);
            $listeIncident = [
                'DE_REF' => $allIncidents[array_search('DE_REF', array_column($allIncidents, 'code'))]['LIBELLE'],
                'RELDOC' => $allIncidents[array_search('RELDOC', array_column($allIncidents, 'code'))]['LIBELLE']
            ];
        }
        if ($module == 'Commande') {
            $incidentsLivraison = (new Incidents($this->pdo)) ->getIncidentsByCategory('LIVRAIS');
            $incidentsRelance = (new Incidents($this->pdo))->getIncidentsByCategory('RELANCE');
            
            $allIncidents = array_merge($incidentsLivraison, $incidentsRelance);
            $listeIncident = [
                'ABPART' => $allIncidents[array_search('ABPART', array_column($allIncidents, 'code'))]['LIBELLE'],
                'REL CDE' => $allIncidents[array_search('REL CDE', array_column($allIncidents, 'code'))]['LIBELLE']
            ];
        }

        return $this->renderer->render('@GlobalApplication/Incidents/creationIncidents', [
            'menuActive' => $menuActif,
            'menuLeft' => $menuLeft,
            "id" => $id,
            "libelle" => $libelle??'',
            'creationIncident' => true,
            'listeIncident' => $listeIncident ?? [],
            'listCat' => $listeCat,
            'incident' => $post,
            'ErreurValid' => $ErreurValid??'',
            'MODULE' => $module,
            'listeLigneCommande' => $listeLigneCa??[],
            'listeLigneBR' => $listeLigneBr??[],
            'titre' => $titre ?? '',
            
        ]);
    }
    
    // phpcs:ignore
    public function ModificationIncidentAction()
    {
        $idUnique = $this->request->getAttribute('idUnique');
        $module = $this->request->getAttribute('MODULE');
        $menuActifUrl = $this->request->getAttribute('menuActif');
        $menuLeftUrl = $this->request->getAttribute('menuLeft');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $liste = new Incidents($this->pdo);
        $liste = $liste->listeTypeIncident(true);
        foreach ($liste as $incident) {
            $listeIncident[$incident['COD_INC']] = $incident['LIBELLE'];
            $listeIncidentNiveau[$incident['COD_INC']] = $incident['NIVEAU'];
        }

        $liste = (new Incidents($this->pdo))->incidentCategoriesList(true);
        $listeCat = [];
        foreach ($liste as $CatIncid) {
            $listeCat[$CatIncid['CODE_CAT']] = $CatIncid['LIBELLE'];
        }
        
        $incident = new Incidents($this->pdo);
        $incident = $incident->Incident($idUnique);
        $trad = $this->getTranslationService();

        if ($module=='Fournisseur') {
            $fournis = new Fourniss($this->pdo);
            $fournis = $fournis->find($incident['FOU']);
            
            $libelle = $fournis["RS"];
            $id = $incident['FOU'];
            $Chps_Filter = 'FOU';
            
            $titre = $trad->t('Fournisseur');
            
            $menuActif = 'Fournisseur';
            $menuLeft = 'GestionFournisseur';
            
            $DroitUtilisateur = new DroitUtilisateur($this->router);

            $DroitUtilisateur->DroitUtilisateur($this->pdo, $fournis);
            
            ArianeSub::generate(2, 0, $trad->t('Modification d\'incident'), $_SERVER['REQUEST_URI'], 1);
        } elseif ($module=='MultiFournisseur') {
            $id = 'ALL';
            $titre = $trad->t('Incident fournisseur');
            arianesub::init();
            
            Ariane::generate(1, $trad->t("Modification d'incident"));
        } elseif ($module=='Commande') {
            $id = $incident['NO_CDE'];
            $menuActif = 'CollecteBesoins';
            $menuLeft = 'Commande.GestionCommande.index';
            
            $titre = $trad->t('Commande');
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($id);
            
            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_NO_CDE' => $id]);
            
            foreach ($listeLigneCa as $value) {
                $listeLigneCommande[$value['NO_PO']] = $value['DES_SOMM'].' '.$value['CODE_ART'];
            }
            
            
            if (!$post) {
                $post = [
                    'FOU' => $commande['CODE_FOU'],
                    'NO_CDE' => $commande['NO_CDE'],
                ];
            }
            
            $Chps_Filter = 'NO_CDE';
            Ariane::generate(2, $trad->t('Modification d\'incident'));
        } elseif ($module=='Facture') {
            $id = $incident['NO_CDE'];
            $menuActif = 'Facture';
            $menuLeft = 'Commande.GestionCommande.index';
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($id);
            
            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_NO_CDE' => $id]);
            
            foreach ($listeLigneCa as $value) {
                $listeLigneCommande[$value['NO_PO']] = $value['DES_SOMM'].' '.$value['CODE_ART'];
            }
            
            
            if (!$post) {
                $post = [
                    'FOU' => $commande['CODE_FOU'],
                    'NO_CDE' => $commande['NO_CDE'],
                ];
            }
            
            $Chps_Filter = 'NO_CDE';
            ArianeSub::generate(2, 0, $trad->t('Modification d\'incident'), $_SERVER['REQUEST_URI'], 1);
        } elseif ($module=='ChoixCommandeFacture') {
            $id = $incident['NO_CDE'];
            $menuActif = 'Facture';
            $menuLeft = 'GestionFacture';
            
            $commande = new CaEntet($this->pdo);
            $commande = $commande->find($id);
            
            $listeLigneCa = new CaLigne($this->pdo);
            $listeLigneCa = $listeLigneCa->fetchAll([], ['filter_NO_CDE' => $id]);
            
            foreach ($listeLigneCa as $value) {
                $listeLigneCommande[$value['NO_PO']] = $value['DES_SOMM'].' '.$value['CODE_ART'];
            }
            
            
            if (!$post) {
                $post = [
                    'FOU' => $commande['CODE_FOU'],
                    'NO_CDE' => $commande['NO_CDE'],
                ];
            }
            
            $Chps_Filter = 'NO_CDE';
            
            ArianeSub::generate(2, 0, $trad->t('Modification d\'incident'), $_SERVER['REQUEST_URI'], 1, $post);
        } elseif ($module=='Reception'  || $module=='suiviBR') {
            $id =  $incident['NO_BR'];

            $titre = $trad->t('Reception');
            
            $br = new BrRecep($this->pdo);
            $br = $br->find($id);
            
            $listeLigneBr = new BrLigne($this->pdo);
            $listeLigneBr = $listeLigneBr->fetchAll([], ['filter_NUM_BR' => $id]);
            
            if (!$post) {
                $post = [
                    'NO_CDE' => $br['NUM_CDE'],
                    'NO_BR' => $br['NUM_BR'],
                ];
            }
            
            $Chps_Filter = 'NO_BR';
            
            ArianeSub::generate(2, 0, $trad->t('Modification d\'incident'), $_SERVER['REQUEST_URI'], 1);

            if ($module=='suiviBR') {
                Ariane::generate(3, $trad->t('Modification d\'incident'));
                $menuActif = 'CollecteBesoins';
                $menuLeft = 'GlobalApplication.Incidents.incidents';
            } else {
                ArianeSub::generate(2, 0, $trad->t('Modification d\'incident'), $_SERVER['REQUEST_URI'], 1);
                $menuActif = 'CollecteBesoins';
                $menuLeft = 'GestionReception';
            }
        }




        


        
        if ($this->request->getMethod() == 'POST') {
            $validator = $this->createValidator();
            
            $validator->isFalse($post['CODE'], $trad->t('L\'incident est obligatoire.'));
            $validator->isDate($post['DTE_OCCUR']);
            $validator->isStringAvecEspace($trad->t('Description'), $post['DESCRIPT'], 0, 60);
            $validator->isStringAvecEspace($trad->t('Commentaire'), $post['CONTMEMO'], 0, 3000);
            
            if ($module=='Commande') {
                // $validator->isFalse($post['PO_CDE'], $trad->t('Le numéro de ligne commande est obligatoire.'));
            } elseif ($module=='Reception') {
                $validator->isFloat('Qté en anomalie', $post['QTE_REFU'], constante::formatQTE, false);
                $validator->isDate($post['DTE_LIV'], '', '', true, 'Date de livraison');
                // $validator->isFalse($post['PO_BR'], $trad->t('Le numéro de ligne commande est obligatoire.'));
            }
            
            if ($validator->isValid()) {
                if ($menuActifUrl != '') {
                    $menuActif = $menuActifUrl;
                }
        
                if ($menuLeftUrl != '') {
                    $menuLeft = $menuLeftUrl;
                }

                $post['NIVEAU'] = $listeIncidentNiveau[$post['CODE']];
                $updateIncident = new Incidents($this->pdo);
                $updateIncident->updateIncident($idUnique, $incident['NM_COM'], $post);
              
                return $this->redirect('GlobalApplication.Incidents.incidents', ['MODULE' => $module, "id" => $id,"menuLeft"=>$menuLeft, "menuActif"=> $menuActif]);
            } else {
                $ErreurValid = $validator->getError();
                $incident=$post;
            }
        }

        if ($menuActifUrl != '') {
            $menuActif = $menuActifUrl;
        }

        if ($menuLeftUrl != '') {
            $menuLeft = $menuLeftUrl;
        }
        
        return $this->renderer->render('@GlobalApplication/Incidents/creationIncidents', [
            'menuActive' => $menuActif??'',
            'menuLeft' => $menuLeft??'',
            "id" => $id,
            "libelle" => $libelle??'',
            'modificerIncident' => true,
            'listeIncident' => $listeIncident,
            'listCat' => $listeCat,
            'incident' => $incident,
            'ErreurValid' => $ErreurValid??'',
            'MODULE' => $module,
            'listeLigneCommande' => $listeLigneCa??[],
            'listeLigneBR' => $listeLigneBr??[],
            'titre' => $titre ?? $module,
            
        ]);
    }

    /**
     * @return Response|string
     */
    public function detailAction()
    {
        $id = $this->request->getAttribute('id');

        $incident = (new Fourninc($this->pdo))->find($id);
        if (empty($incident)) {
            LogSysteme::prefixErrorLog('Invalid incident #'.$id);
            return $this->create404Response();
        }

        return $this->renderer->render('@GlobalApplication/Incidents/detailIncident', [
            'incident' =>
                $incident
                + [
                    'Responsable' => (new Hastutil($this->pdo))->find($incident['INCF_USER']),
                    'Type' => ($type = (new Incident($this->pdo))->find($incident['CODE'])),
                    'Categorie' => (new CatIncid($this->pdo))->find($type['CODE_CAT']),
                    'Commentaire' => Sql::getMemo($this->pdo, $incident['NM_COM']),
                    'Facture' => ($facture = (new FactEnt($this->pdo))->find($incident['NO_FACT'])),
                    'Comptable' => ($comptable = new Hastutil($this->pdo))->find($facture['FAC_CBY']),
                ],
            'menuContextuel' => (new IncidentMenuContextuel(
                $this->pdo,
                $this->router,
                $this->getTranslationService(),
                'Facture'
            ))->generate($incident + [
                'CODE_CAT' => $type['CODE_CAT'],
                'COMPTABLE' => $comptable,
                'RS' => (new Fourniss($this->pdo))->find(['CODE' => $incident['FOU']])['RS']
            ], ''),
            'isLitige' => true,
            'id' => $id,
        ]);
    }
    
    public function suppresionIncidentsAction() : string
    {
        $idUnique = $this->request->getAttribute('idUnique');

        

        $trad = $this->getTranslationService();

        
        $incident = new Incidents($this->pdo);
        $incident->deleteIncident($idUnique);
        
        return $this->renderer->render('@popup-erreur/confirmationGestion', [
            'message' => $trad->t('L\'incident a été supprimé.'),
            'iconePopup' => 'information',
        ]);
    }

    // ENVOI DE MAIL DEPUIS GESTION INCIDENTS COMMANDE
    public function incidentsMailCommandeAction() : string
    {
        $post    = $this->request->getParsedBody();
        $MODULE = $this->request->getAttribute('MODULE');
        $id = $this->request->getAttribute('id');
        $idUnique = $this->request->getAttribute('idUnique');
        $menuActifUrl = $this->request->getAttribute('menuActif');
        $menuLeftUrl = $this->request->getAttribute('menuLeft');

        $trad = $this->getTranslationService();
    


        $CaEntet  = new CaEntet($this->pdo);
        $CaEntet = $CaEntet->find($id);
        
        $incident = new Incidents($this->pdo);
        $incident = $incident->Incident($idUnique);
        
        $globalParam = new \Modules\GlobalApplication\Repository\Param($this->pdo);
        $paramMail = $globalParam->getMailInt(['CODE_MAIL' => 'CDE_INCIDENT_FOU', 'CODE_LNG' => $CaEntet['COD_LNG']]);
        if (!$paramMail || (trim($paramMail['TX_SUJET'])=='' && trim($paramMail['CONTMEMO'])=='')) {
            $paramMail = $globalParam->getMailInt(['CODE_MAIL' => 'CDE_INCIDENT_FOU', 'CODE_LNG' => '']);
        }

        if (!$paramMail || (trim($paramMail['TX_SUJET'])=='' && trim($paramMail['CONTMEMO'])=='')) {
            $reponse['Sujet'] = Trad::strBuild($trad->t('Commande N° @1@, incident @2@'), $id, $incident['libelleIncident']);
        } else {
            $Langues  = new \Entity\Model\Langues($this->pdo);
            $Langues = $Langues->find($CaEntet['COD_LNG']);
            $outilIncidents = new \Modules\GlobalApplication\Outil\Incidents();
            $reponse['Sujet'] = $outilIncidents->tagIncidentsMailCommande($paramMail['TX_SUJET'], $incident, Date::getDateFormatByNumDate($Langues['TYPDTEPROC']));
            $reponse['Corps'] = $outilIncidents->tagIncidentsMailCommande($paramMail['CONTMEMO'], $incident, Date::getDateFormatByNumDate($Langues['TYPDTEPROC']));
        }

        $reponse['Destinataires'] = str_replace(' ', '', ($CaEntet['EMA_CTCT'] ?? ''));
        
        $menuActif = 'CollecteBesoins';
        $menuLeft = 'Commande.GestionCommande.index';

        if ($menuActifUrl != '') {
            $menuActif = $menuActifUrl;
        }

        if ($menuLeftUrl != '') {
            $menuLeft = $menuLeftUrl;
        }

        Ariane::generate(2, $trad->t('Mail au fournisseur'));
        ariane::setFocus($id);

        // [Dossier n°33377]
        $no_cde                 = $incident[ 'NO_CDE' ];
        $memo_id                = $incident[ 'NM_COM' ];
    
        return $this->renderer->render('@GlobalApplication/mail/mail', [
            'menuActive'       => $menuActif,
            'menuLeft'         => $menuLeft,
            'post'             => $post,
            'module'           => $MODULE,
            'uriRetour'        => $this->router->generateUri('GlobalApplication.Incidents.incidents', ['MODULE' => $MODULE, 'id' => $id, 'menuLeft' => $menuLeft, 'menuActif' => $menuActif]),
            'reponse'          => $reponse,
            
            'commandeId'       => $id,
            'societe'          => $CaEntet['CODE_STE'],
            'fournisseur'      => $CaEntet['CODE_FOU'],
            'numFact'          => $no_cde,
            'codeSte'          => $CaEntet['CODE_STE'],
            'user'             => $_SESSION['Session_Login'],
            'memo_id'          => $memo_id,
        ]);
    }

    public function recordIncidentDataAction()
    {
        $post                           = $this->request->getParsedBody();
        $suivi_commande_repo            = new CommandeEventRepo($this->pdo);

        $commande_id                    = $post[ 'NUM_CDE' ];

        if ($post) {
            $CaEvent_Exist = new CaEvent($this->pdo);
            $CaEvent_Exist = $CaEvent_Exist->find([
                'NO_CDE' => $commande_id,
                'CODE' => $post[ 'CODE_EVE' ],
            ]);

            if ($CaEvent_Exist) {
                $array                  = [
                    'NUM_CDE'           => $commande_id,
                    'DTE'               => date('Ymd'),
                    'HEURE'             => date('His'),
                    'CODE'              => $post[ 'CODE_EVE' ],
                    'UTIL'              => $post[ 'UTIL' ],
                    'SIGNAT'            => '',
                    'TYP_EVE'           => $post[ 'TYPE_EVE' ],
                    'NM_COMME'          => $post[ 'MEMO_ID' ],
                ];

                Sql::updateMemo($this->pdo, $array['NM_COMME'], $post['CONTMEMO']);
            
                $suivi_commande_repo->ajoutEvenement($array);
            }
        }

        return new Response(200, [
        ]);
    }

    public function editSheetAction(): string
    {
        $id = $this->request->getAttribute('id');
        $module = $this->request->getAttribute('MODULE');

        // en fonction du module d'où on appelle, on cherche à filtrer la liste des incidents
        // si on cherche un seul fournisseur, CodeFournMin et CodeFournMax sont tous les deux égaux au code du fournisseur en question
        $filters = [
                'CodeFournMin'    => '',
                'CodeFournMax'    => '',
                'DateIncMin'      => '',
                'DateIncMax'      => '',
                'CodeIncMin'      => '',
                'CodeIncMax'      => '',
                'NiveauIncMin'    => '',
                'NiveauIncMax'    => '',
                'NumCdeMin'       => '',
                'NumCdeMax'       => '',
                'AvecDetails'     => true,
        ];

        switch ($module) {
            case 'Commande':
                $codeFrs = (new CaEntet($this->pdo))->find($id, ['CODE_FOU'])['CODE_FOU'];
                $filters['NumCdeMin'] = $filters['NumCdeMax'] = $id;
                $filters['CodeFournMin'] = $filters['CodeFournMax'] = $codeFrs;
                $wsdl = new WebServiceIncidents();
                $xml = $wsdl->editSheet($filters);

                $response = new \SimpleXMLElement($xml->responseData);

                if ($response->Statut != 'O') {
                    return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                        'params' => [
                            'alerte' => $response->MsgErreur,
                        ],
                    ]);
                }

                $url = Fichier::URLDownload($response->FichierPDF);
                $message = Fichier::UploadClient($url, $response->FichierPDF);
                return $message;

            case 'Fournisseur':
                $filters['CodeFournMin'] = $filters['CodeFournMax'] = $id;
                $wsdl = new WebServiceIncidents();
                $xml = $wsdl->editSheet($filters);
                $response = new \SimpleXMLElement($xml->responseData);

                if ($response->Statut != 'O') {
                    return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
                        'params' => [
                            'alerte' => $response->MsgErreur,
                        ],
                    ]);
                }

                $url = Fichier::URLDownload($response->FichierPDF);
                $message = Fichier::UploadClient($url, $response->FichierPDF);
                return $message;

            default:
                return '';
        }
    }
}
