<?php
namespace Modules\API\APIInterne\OxaMobility\Controller;

use Helpers\Log\LogSysteme;

use Helpers\Outil\Outils;
use SimpleXMLElement;
use Helpers\Outil\Sql;
use Entity\Model\Memos;
use Skeleton\Controller\Controller;
use Entity\Model\CaEntet;
use Entity\Model\Docatt as ModelDocatt;
use Entity\Model\Societe;
use Helpers\Fichier\Fichier;
use Helpers\Fichier\Gestion_Fic_PJ;
use Helpers\Trad\Trad;
use OpenApi\Annotations as OA;
use Modules\GlobalApplication\Repository\CaracteristiquesComplementaires;

class BRController extends Controller
{
    public function init()
    {
        /** A deplacer dans absAPIcontroller plus tard car pas top */
        $trad = $this->getTranslationService();
        if ($trad instanceof Trad) {
            $trad->setLang($_SESSION['Session_Langue']);
        }
    }

    /**
     * @OA\Post(
     *      path="/br/liste_cdes",
     *      summary="Displays the orders list",
     *      tags={"Receipts"},
     *      @OA\RequestBody(
     *          description="Registered application user",
     *          required=true,
     *          @OA\MediaType(
     *              mediaType="application/xml",
     *          )
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="Orders list",
     *          @OA\XmlContent(
     *             type="array",
     *             @OA\items(
     *                  type="string"))
     *       ),
     *      security={{
     *          "ApiKeyAuth": {}
     *      }}

     * )
     */
    // phpcs:ignore
    public function LISTE_CDESAction($body = [], $jwtPayload = [], $json = true)
    {
        $contents = file_get_contents(session_save_path().'\\sess_'.$jwtPayload['sessionId']);
        session_name('__OxaProc-PHPSESSID');
        @session_start();
        session_decode($contents);

        $trad = $this->getTranslationService();

        if (!is_string($body['CodeSI'])) {
            $body['CodeSI']= '';
        }
        if (!is_string($body['CodeSoc'])) {
            $body['CodeSoc']= '';
        }
        if (!is_string($body['CodeCDC'])) {
            $body['CodeCDC']= '';
        }
        if (!is_string($body['CodeSCA'])) {
            $body['CodeSCA']= '';
        }
        if (!is_string($body['Centre_E'])) {
            $body['Centre_E']= '';
        }
        if (!is_string($body['Centre_L'])) {
            $body['Centre_L']= '';
        }
        if (!is_string($body['CodeFourn'])) {
            $body['CodeFourn']= '';
        }
        if (!is_string($body['Attendu'])) {
            $body['Attendu']= '';
        }
        if (!is_string($body['DateLivr'])) {
            $body['DateLivr']= '';
        }
        if (!is_string($body['NumCde'])) {
            $body['NumCde']= '';
        }
        if (!is_string($body['RechDesign'])) {
            $body['RechDesign']= '';
        }
        if (!is_string($body['ClauseWhereAdd'])) {
            $body['ClauseWhereAdd']= '';
        }
        if (!is_string($body['OrderBy'])) {
            $body['OrderBy']= '';
        }
        if (!is_string($body['RechFourn'])) {
            $body['RechFourn']= '';
        }

        // $post_string = implode('&', $body);
        $post_string = 'ClauseWhereAdd='.$body['ClauseWhereAdd'].'&OrderBy='.$body['OrderBy'];
        $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_COOKIESESSION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
            curl_setopt(
                $ch,
                CURLOPT_URL,
                // @phpstan-ignore-next-line
                Outils::getRootUrl(true) .
                $this->contenaire->get('base') .
                'passerelleV1V2.php?sessionId='.session_id().
                '&fonction=ListeCommandeAReceptionner&societe='.($body['CodeSoc']??'').
                '&SI='.((string)$body['CodeSI']) .
                // '&Direction='.((string)$body['COD_ADR']??'').
                // @phpstan-ignore-next-line
                '&SCA='.((string)$body['CodeSCA']??'').
                // @phpstan-ignore-next-line
                '&CDC='.((string)$body['CodeCDC']??'').
                // '&SCA='.((string)$body['CodeSCA']??'').
                // @phpstan-ignore-next-line
                '&CTR_EMET='.((string)$body['Centre_E']??'').
                // @phpstan-ignore-next-line
                '&CTR_EMET='.((string)$body['Centre_E']??'').
                // @phpstan-ignore-next-line
                '&COD_FOURN='.((string)$body['CodeFourn']??'').
                // @phpstan-ignore-next-line
                '&filtre='.((string)$body['Attendu']??'').
                // @phpstan-ignore-next-line
                '&DTE_LIV='.((string)$body['DateLivr']??'').
                // @phpstan-ignore-next-line
                '&DESIGN='.(urlencode((string)$body['RechDesign']??'')).
                // @phpstan-ignore-next-line
                '&CTR_LIV='.((string)$body['Centre_L']??'').
                // @phpstan-ignore-next-line
                '&RechFourn='.(urlencode((string)$body['RechFourn']??'')).
                // @phpstan-ignore-next-line
                '&NO_CDE='.((string)$body['NumCde']??''),
            );
        session_write_close();
        $response = curl_exec($ch);
        curl_close($ch);
        $execSQL = new \Modules\API\APIExterne\Repository\Index($this->pdo);
        $resultats = $execSQL->execSQL((string)$response);
        $paginator = new \Helpers\Pagination\Paginator();
        $infopagination = $paginator->generate($resultats, $body['NbreEnreg'], ['page' => $body['NumPage']], $this->renderer);
        $return['Statut'] = 'O';

        

        $trad = $this->getTranslationService();

        $return['MsgErreur'] = '';
        if (Sql::boolSql(Sql::paravrac($this->pdo, 'OXAPROC', 'AFFTTC')) == '1') {
            $return['HT_TTC'] = $trad->t('TTC');
        } else {
            $return['HT_TTC'] =$trad->t('HT');
        }

        $ArrayString = '';
        $return['NbrePages']= $infopagination['nombreDePage']??'';

        $societe = new Societe($this->pdo);
        $listeSociete = $societe->fetchAll(['CODE_STE, RAIS_SOC']);
        $soc = [];

        foreach ($listeSociete as $liste) {
            $soc[$liste['CODE_STE']] = $liste;
        }

        if ($json) {
            $return['Liste_Type_Attendu']['Attendu'][]= [
                'CodeAttendu' => 'R',
                'LibelleAttendu' => $trad->t('En retard')
            ];
            $return['Liste_Type_Attendu']['Attendu'][]= [
                'CodeAttendu' => 'S',
                'LibelleAttendu' => $trad->t('Cette semaine')
            ];
            $return['Liste_Type_Attendu']['Attendu'][]= [
                'CodeAttendu' => 'M',
                'LibelleAttendu' => $trad->t('Ce mois')
            ];
            $return['Liste_Type_Attendu']['Attendu'][]= [
                'CodeAttendu' => 'NM',
                'LibelleAttendu' => $trad->t('Mois prochain')
            ];
            $return['Liste_Type_Attendu']['Attendu'][]= [
                'CodeAttendu' => 'T',
                'LibelleAttendu' => $trad->t('Toutes')
            ];


            foreach ($resultats as $resultat) {
                $return['Liste']['Cde'][] = [
                    'NO_CDE' => $resultat['NO_CDE'],
                    'CODE_STE' => $resultat['CODE_STE'],
                    'RS_STE' => $soc[$resultat['CODE_STE']]['RAIS_SOC'] ?? '',
                    'CODE_FOU' => $resultat['CODE_FOU'],
                    'RS_FOU' => $resultat['RS'],
                    'MNT_CDE' => $resultat['TOT_CDEHT'],
                    'DEVISE' => $resultat['DEVISE'],
                    'DTE_LIV' => $resultat['dateLivPr'],
                ];
            }
        } else {
            $return['Liste_Type_Attendu']= 'replace2';
            
            
            $ArrayString12 ='
            <Attendu>
                <CodeAttendu>R</CodeAttendu>
                <LibelleAttendu>'.$trad->t('En retard').'</LibelleAttendu>
            </Attendu>
            <Attendu>
                <CodeAttendu>S</CodeAttendu>
                <LibelleAttendu>'.$trad->t('Cette semaine').'</LibelleAttendu>
            </Attendu>
            <Attendu>
                <CodeAttendu>M</CodeAttendu>
                <LibelleAttendu>'.$trad->t('Ce mois').'</LibelleAttendu>
            </Attendu>
            <Attendu>
                <CodeAttendu>NM</CodeAttendu>
                <LibelleAttendu>'.$trad->t('Mois prochain').'</LibelleAttendu>
            </Attendu>
            <Attendu>
                <CodeAttendu>T</CodeAttendu>
                <LibelleAttendu>'.$trad->t('Toutes').'</LibelleAttendu>
            </Attendu>';
                
            foreach ($resultats as $resultat) {
                $ArrayString .= "<Cde>
                                    <NO_CDE>".$resultat['NO_CDE']."</NO_CDE>
                                    <CODE_STE>".$resultat['CODE_STE']."</CODE_STE>
                                    <RS_STE>".($soc[$resultat['CODE_STE']]['RAIS_SOC'] ?? '')."</RS_STE>
                                    <CODE_FOU>".$resultat['CODE_FOU']."</CODE_FOU>
                                    <RS_FOU>".$resultat['RS']."</RS_FOU>
                                    <MNT_CDE>".$resultat['TOT_CDEHT']."</MNT_CDE>
                                    <DEVISE>".$resultat['DEVISE']."</DEVISE>
                                    <DTE_LIV>".($resultat['dateLivPr'] ?? '')."</DTE_LIV>
                                 </Cde>";
            }
            $return['Liste'] = 'replace1';
        }
    
        if ($json) {
            $retourJSON['MPROC_Out'] = $return;
            header('content-type:application/json');
            if ($_SESSION['_debug'] == true) {
                Fichier::createFichierTmp(LogSysteme::getServerName().'.'.str_replace('|', '_', $body['Action']).'_Out.json', json_encode($retourJSON));
            }
            return json_encode($retourJSON);
        }

        $xml = new SimpleXMLElement('<MPROC_Out/>');
        header('Content-Type: application/xml; charset=utf-8');
        \Helpers\Outil\Outils::array_to_xml($return, $xml, $body['Action'], $ArrayString);
        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML(
            str_replace(
                'replace2',
                ($ArrayString12 ?? ''),
                str_replace(
                    'replace1',
                    ($ArrayString),
                    $xml->asXML()
                )
            )
        );
        return $domxml->saveXML();
    }

    /**
     * @OA\Post(
     *      path="/br/enreg_creation",
     *      summary="Create a receipt",
     *      tags={"Receipts"},
     *      @OA\RequestBody(
     *          description="Header",
     *          required=true,
     *          @OA\MediaType(
     *              mediaType="application/xml",
     *          )
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="Success",
     *          @OA\XmlContent(
     *             type="array",
     *             @OA\items(
     *                  type="string"))
     *      ),
     *      security={{
     *          "ApiKeyAuth": {}
     *      }}

     * )
     */


    // phpcs:ignore
    public function ENREG_CREATIONAction($body = [], $jwtPayload = [], $json = true)
    {
        
        $contents = file_get_contents(session_save_path().'\\sess_'.$jwtPayload['sessionId']);
        session_name('__OxaProc-PHPSESSID');
        @session_start();
        session_decode($contents);
        $entete = $body['Entete'] ?? [];
        $incident = $body['Incident'] ?? [];
        $ligneBR = $body['Lignes'] ?? [];
        $trad = $this->getTranslationService();

        
        foreach ($ligneBR as &$ligne) {
            $ligne = $ligne['Ligne'];
        }

        $pjObli = Sql::paravrac($this->pdo, 'OXAMPROC', 'PJ_OB')=='O'? true:false;
        //feature en attente RA
        if (count($body['ListePJ']['PJ'])==0 && $pjObli) {
        // if (false) {
            $return['Statut'] = 'E';
            $return['MsgErreur'] = $trad->t('Des pièces-jointes sont obligatoires');
        } else {
            $retourCreatBR = \Modules\Reception\WebService\BR::creationBR($body, $ligneBR, $entete);
            $retourBR = new \SimpleXMLElement($retourCreatBR->responseData);
            $return['Statut'] = (string)$retourBR->Statut;
            if ($retourBR->Statut=="O") {
                if (isset($incident['Code']) && $incident['Code'] != '') {
                    $caEntet = new CaEntet($this->pdo);
                    $resultCA = $caEntet->find(['NO_CDE' => $entete['NumCde']], ['CODE_FOU', 'DTE_CREAT']);
                    
                    $retourCreatIncidentBR = \Modules\Reception\WebService\BR::creationIncidentBR($retourBR->NumBR, $incident['Code'], $incident['Motif'], $incident['Comm'], $resultCA['DTE_CREAT'], $resultCA['CODE_FOU'], $entete['NumCde']);
                    $retourIncident = new \SimpleXMLElement($retourCreatIncidentBR->responseData);
                    
                    $return['Statut'] = (string)$retourIncident->Statut;
                    if ($retourIncident->Statut!="O") {
                        $return['MsgErreur'] = (string)$retourIncident->Erreur;
                    }
                }

                $return['NUM_BR'] = (string)$retourBR->NumBR;

                if (isset($body['ListePJ']) && (count($body['ListePJ']) > 0)) {
                    $i = 1;
                    if (isset($body['ListePJ'])) {
                        foreach ($body['ListePJ'] as $pieceJointe) {
                            $file = \pathinfo($pieceJointe['NomFichier']);
                            $file = $file['basename'];
                            $gestionFicPj = new Gestion_Fic_PJ($this->pdo);
                            $newFile = $gestionFicPj->insertFichier($file);

                            $docAtt = new ModelDocatt($this->pdo);
                            $docAtt->insert([
                                'NO_DA'             => 'BR_RECEP',
                                'NO_ORDRE'          => $i,
                                'TYPE_PJ'           => 'PJ',
                                'TITRE'             => $pieceJointe['NomFichierAff'],
                                'numerique_COPIE'   => '0x54',
                                'NOM_FIC'           => $newFile,
                                'DT_PARUT'          => date('Ymd'),
                                'DT_VALID'          => '00000000',
                                'COD_ENR'           => str_pad($return['NUM_BR'], 9, '0', STR_PAD_LEFT),
                                'AUTEUR'            => $_SESSION["Session_Login"],
                                'CENTRE'            => $_SESSION['Session_CodeCtrLivraison'],
                                'NOM_ORI'           => $pieceJointe['NomFichierAff'],
                            ]);
                            $i++;
                        }
                    }
                }
            } else {
                $return['MsgErreur'] = (string)$retourBR->MsgErreur;
            }
        }
        
        if ($json) {
            $retourJSON['MPROC_Out'] = $return;
            header('content-type:application/json');
            if ($_SESSION['_debug'] == true) {
                Fichier::createFichierTmp(LogSysteme::getServerName().'.'.str_replace('|', '_', $body['Action']).'_Out.json', json_encode($retourJSON));
            }
            return json_encode($retourJSON);
        }

        $xml = new SimpleXMLElement('<MPROC_Out/>');
        header('Content-Type: application/xml; charset=utf-8');
        \Helpers\Outil\Outils::array_to_xml($return, $xml, $body['Action']);
        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML($xml->asXML());
        return $domxml->saveXML();
    }

    /**
     * @OA\Info(
     *      title="OxaMobility",
     *      version="10.51ab",
     *      description="Documentation API Mobilité OxaProc",
     *      @OA\Contact(
     *        email="support@oxalys.com"
     *      )
     * ),
     *
     * @OA\SecurityScheme(
     *      securityScheme="ApiKeyAuth",
     *      type="apiKey",
     *      in="header",
     *      name="X_OXA_TOKEN",
     * ),
     *
     * @OA\Post(
     *      path="/br/ecran_creation",
     *      summary="Displays the screen for creating a receipt",
     *      tags={"Receipts"},
     *      @OA\Parameter(
     *        name="User",
     *        in="query",
     *        required=true,
     *        @OA\Schema(type="string")
     *      ),
     *      @Oa\Response(
     *          response="200",
     *          description="New receipt",
     *      ),
     *      security={{
     *          "ApiKeyAuth": {}
     *      }}
     * )
     *
     *
     */
    // phpcs:ignore
    public function ECRAN_CREATIONAction($body = [], $jwtPayload = [], $json = true)
    {
        $contents = file_get_contents(session_save_path().'\\sess_'.$jwtPayload['sessionId']);
        session_name('__OxaProc-PHPSESSID');
        @session_start();
        session_decode($contents);
        $trad = $this->getTranslationService();

        $ArrayString1 = '';
        $ArrayString2 = '';
        $return = [];
        $noCde = $body['NumCde'];
        $ca = new CaEntet($this->pdo);
        $caEntete = $ca->find(['NO_CDE' => $body['NumCde']]);

        $trad = $this->getTranslationService();

        /* Appel V1 réinitialisation du bon de réception dans la table 'oxa_br_ligne' */
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_COOKIESESSION, true);
        curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
        curl_setopt($ch, CURLOPT_URL, Outils::getRootUrl(true) . $this->contenaire->get('base').'passerelleV1V2.php?sessionId='.session_id().'&fonction=ResetOxaBrLigne&no_cde=' . $noCde);
        session_write_close();
        curl_exec($ch);
        curl_close($ch);

        if (!isset($caEntete['NO_CDE']) || ( isset($caEntete['NO_CDE']) && trim($caEntete['NO_CDE'])=='')) {
            $return['Statut'] = 'E';
            $return['MsgErreur'] = $trad->t('La commande n\'existe pas');
            $return['Entete']['NumCde'] = $body['NumCde'];
        } else {
            $return['Statut'] = 'O';
            /**
             * Recuperation du paramettrage des lignes des ecrans BR
             */
            $BRRepository = new \Modules\Reception\Repository\GestionBR($this->pdo);
            foreach ($BRRepository->getParamEcranValidationBR() as $param) {
                ${$param['CODEPARV']} = $param['LIB01PARV'];
            }

            /** @phpstan-ignore-next-line */
            $return['Param']['DateLivraisonObligatoire'] = (($BRDTELIVOB ?? 'N') == 'O')?true:false;
            /** @phpstan-ignore-next-line */
            $return['Param']['NumLivraisonObligatoire'] = (($BRNUMLIVOB ?? 'N') == 'O')?true:false;
            /** @phpstan-ignore-next-line */
            $return['Param']['ExcedentLivraisonControlBloquant'] = (($BR_LIVR_EXCEDENT_CTRL ?? 'N') == 'B')?true:false;
            /** @phpstan-ignore-next-line */
            $return['Param']['ExcedentLivraisonControlMontant'] = (isset($BR_LIVR_EXCEDENT_MONTANT))?trim($BR_LIVR_EXCEDENT_MONTANT):'0';
            /** @phpstan-ignore-next-line */
            $return['Param']['ExcedentLivraisonControlTaux'] = (isset($BR_LIVR_EXCEDENT_TAUX))?trim($BR_LIVR_EXCEDENT_TAUX):'0';
            /** @phpstan-ignore-next-line */
            $return['Param']['SabranesOaxley'] = (($SARBANES_OAXLEY ?? 'N') == 'O')?true:false;


            $return['Entete']['NumCde'] = $body['NumCde'];
            $return['Entete']['DEVISE'] = $caEntete['DEVISE'];
            if (Sql::boolSql(Sql::paravrac($this->pdo, 'OXAPROC', 'AFFTTC')) == '1') {
                $return['Entete']['HT_TTC'] = $trad->t('TTC');
            } else {
                $return['Entete']['HT_TTC'] = $trad->t('HT');
            }
            $incident = new \Modules\GlobalApplication\Repository\Incidents($this->pdo);
            $listIncident = $incident->getIncident('LIVRAIS');

            foreach ($listIncident as $inc) {
                if ($json) {
                    $return['Entete']['ListeTypeInc']['TypeInc'][] = ['COD_INC' => $inc['COD_INC'], 'LIBELLE' => $inc['LIBELLE']];
                } else {
                    $ArrayString1 .= "
                    <Cde>
                        <COD_INC>".$inc['COD_INC']."</COD_INC>
                        <LIBELLE>".$inc['LIBELLE']."</LIBELLE>
                    </Cde>";
                }
            }
            
            if (!$json) {
                $return['Entete']['ListeTypeInc']['TypeInc'] = 'replace1';
            }

            $memos = new Memos($this->pdo);
            $cs = new \Entity\Model\CsDon($this->pdo);
            $gestionBr = new \Modules\Reception\Repository\GestionBR($this->pdo);
            $lignesBr = $gestionBr->getLigneBRforCreation($body['Utilisateur'], $body['NumCde']);
            
            $gestionBr->ajouteChampsSupplLigneCdePourBR($body['NumCde'], $lignesBr);
            
            foreach ($lignesBr as $ligne) {
                $ccTmpArray = [];
                $ccTmpString = '';
                $csTmpArray = [];
                $csTmpString = '';
                $ligneTmpString = '';
                $ligneTmpArray = '';
                $caracteristiquesComplementaires = new CaracteristiquesComplementaires($this->pdo);
                $ccCdeLigne = $caracteristiquesComplementaires->listeCCDoc('CA', $body['NumCde'], $ligne['no_ligne_cde'], 0, null, null, 'F');
               
                foreach ($ccCdeLigne as $cc) {
                    if ($json) {
                        $ccTmpArray[]['CarComp'] = [
                            'CC_ID' => $cc['CC_ID'],
                            'CC_IS_TITLE' => \Helpers\Outil\Sql::convertBooleenCheckboxForWsdlTrueFalse($cc['CC_IS_TITLE']),
                            'CC_NAME' => $cc['CC_NAME'],
                            'CC_FORMAT' => $cc['FORMAT'],
                            'CC_TYPE' => $cc['CC_TYPE'],
                            'CC_REQUIRED' => \Helpers\Outil\Sql::convertBooleenCheckboxForWsdlTrueFalse($cc['CC_REQUIRED']),
                            'CC_VALUE' => $cc['CC_VALUE']
                        ];
                    } else {
                        $ccTmpString .='
                        <CarComp>
                            <CC_ID>'.$cc['CC_ID'].'</CC_ID>
                            <CC_IS_TITLE>'.\Helpers\Outil\Sql::convertBooleenCheckboxForWsdlTrueFalse($cc['CC_IS_TITLE']).'</CC_IS_TITLE>
                            <CC_NAME>'.$cc['CC_NAME'].'</CC_NAME>
                            <CC_FORMAT>'.$cc['FORMAT'].'</CC_FORMAT>
                            <CC_TYPE>'.$cc['CC_TYPE'].'</CC_TYPE>
                            <CC_REQUIRED>'.\Helpers\Outil\Sql::convertBooleenCheckboxForWsdlTrueFalse($cc['CC_REQUIRED']).'</CC_REQUIRED>
                            <CC_VALUE>'.$cc['CC_VALUE'].'</CC_VALUE>
                        </CarComp>';
                    }
                }

                foreach ($ligne['cs'] as $cs) {
                    $CSCodeTable = (Sql::boolSql($cs['CONTROLE']) == 1 ? $cs['TYPE'] : '');
                    if ($json) {
                        $csTmpArray[]['ChpSup'] = [
                            'CSNumFixe' => $cs['NUM_FIX'],
                            'CSValeur' => $cs['VALEUR'],
                            'CSCodeTable' => $CSCodeTable,
                            'CSFormat' => $cs['FORMAT'],
                            'CSLibelle' => $cs['LIBELLE_CS'],
                        ];
                    } else {
                        $csTmpString .='
                        <ChpSup>
                            <CSNumFixe>'.$cs['NUM_FIX'].'</CSNumFixe>
                            <CSValeur>'.$cs['VALEUR'].'</CSValeur>
                            <CSCodeTable>'.$CSCodeTable.'</CSCodeTable>
                            <CSFormat>'.$cs['FORMAT'].'</CSFormat>
                            <CSLibelle>'.$cs['LIBELLE_CS'].'</CSLibelle>
                        </ChpSup>';
                    }
                }

                if ($json) {
                    $ligneTmpArray =  [
                        'NO_PO' => $ligne['no_ligne_cde'],
                        'PU' => \number_format($ligne['prixUnitaire'], 2, '.', ''),
                        'DTE_LIV' => $ligne['DTE_LIV'],
                        'REF_FOUR' => $ligne['REF_FOUR'],
                        'REF_FAB' => $ligne['REF_FAB'],
                        'DES_SOMM' => $ligne['design_sommaire'],
                        'DES_COMP' => (trim($ligne['NM_DCOMP'])!= '') ? ($memos->find($ligne['NM_DCOMP'])['CONTMEMO'] ?? ''):'', // a voir
                        'RAL' => $ligne['ral'],
                        'UNITE' => $ligne['unite'],
                        'CodeSI' => $ligne['CODE_SI'],
                        'LibSI' => $ligne['SI_LIBELLE'],
                        'CodeCDC' => $ligne['CODE_CDC'],
                        'LibCDC' => $ligne['CDC_LIBELLE'],
                        'CodeSCA' => $ligne['CODE_SCA'],
                        'LibSCA' => $ligne['SCA_LIBELLE']
                    ];
                    if (count($csTmpArray)) {
                        $ligneTmpArray['ListChpSup'] = $csTmpArray;
                    }
                    if (count($ccTmpArray)) {
                        $ligneTmpArray['ListCarComp'] = $ccTmpArray;
                    }
                    $return['Lignes'][]['Ligne'] = $ligneTmpArray;
                } else {
                    $ArrayString2 .="
                                <Ligne>
                                    <NO_PO>".$ligne['no_ligne_cde']."</NO_PO>
                                    <PU>".$ligne['prixUnitaire']."</PU>
                                    <DTE_LIV>".$ligne['DTE_LIV']."</DTE_LIV>
                                    <REF_FOUR>".$ligne['REF_FOUR']."</REF_FOUR>
                                    <REF_FAB>".$ligne['REF_FAB']."</REF_FAB>
                                    <DES_SOMM>".$ligne['design_sommaire']."</DES_SOMM>
                                    <DES_COMP>".((trim($ligne['NM_DCOMP'])!= '') ? ($memos->find($ligne['NM_DCOMP'])['CONTMEMO'] ?? ''):'')."</DES_COMP>
                                    <RAL>".$ligne['ral']."</RAL>
                                    <UNITE>".$ligne['unite']."</UNITE>
                                    <CodeSI>".$ligne['CODE_SI']."</CodeSI>
                                    <LibSI>".$ligne['SI_LIBELLE']."</LibSI>
                                    <CodeCDC>".$ligne['CODE_CDC']."</CodeCDC>
                                    <LibCDC>".$ligne['CDC_LIBELLE']."</LibCDC>
                                    <CodeSCA>".$ligne['CODE_SCA']."</CodeSCA>
                                    <LibSCA>".$ligne['SCA_LIBELLE']."</LibSCA>
                                    <ListChpSup>".$csTmpString."</ListChpSup>
                                    <ListCarComp>".$ccTmpString."</ListCarComp>
                                </Ligne>";
                    $return['Lignes'] = 'replace2';
                }
            }
        }
        

        if ($json) {
            $retourJSON['MPROC_Out'] = $return;
            header('content-type:application/json');
            if ($_SESSION['_debug'] == true) {
                Fichier::createFichierTmp(LogSysteme::getServerName().'.'.str_replace('|', '_', $body['Action']).'_Out.json', json_encode($retourJSON));
            }
            return json_encode($retourJSON);
        }

        $xml = new SimpleXMLElement('<MPROC_Out/>');
        header('Content-Type: application/xml; charset=utf-8');
        \Helpers\Outil\Outils::array_to_xml($return, $xml, $body['Action']);
        $domxml = new \DOMDocument('1.0');
        $domxml->preserveWhiteSpace = false;
        $domxml->formatOutput = true;
        $domxml->loadXML(
            str_replace(
                'replace1',
                ($ArrayString1),
                str_replace(
                    'replace2',
                    ($ArrayString2),
                    $xml->asXML()
                )
            )
        );
        return $domxml->saveXML();
    }
}
