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

use GuzzleHttp\Psr7\Response;
use Helpers\Pagination\PaginatorGestion;
use Modules\Reception\Repository\GestionBR;
use Modules\Reception\Service\CreationBRService;
use SimpleXMLElement;
use Helpers\Outil\Sql;
use Entity\Model\Memos;
use Entity\Model\CaEntet;
use Entity\Model\Docatt as ModelDocatt;
use Entity\Model\Societe;
use Helpers\Fichier\Gestion_Fic_PJ;
use OpenApi\Annotations as OA;
use Modules\GlobalApplication\Repository\CaracteristiquesComplementaires;

class BRController extends AbsApiController
{
    /**
     * @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() :Response
    {
        $trad = $this->getTranslationService();
        $body = $this->request->getMetaBody();

        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']= '';
        }

        if ((string)$body['Attendu'] == 'D') {
            $body['Attendu'] == 'today';
        } elseif ((string)$body['Attendu'] == 'S') {
            $body['Attendu'] == 'week';
        } elseif ((string)$body['Attendu'] == 'M') {
            $body['Attendu'] == 'month';
        } elseif ((string)$body['Attendu'] == 'NM') {
            $body['Attendu'] == 'nextMonth';
        } else {
            $body['Attendu'] == '';
        }
        
        $post = [
            'CODE_SI'               => (string)$body['CodeSI'],
            'filter_SSCPTEANA'      => (string)$body['CodeSCA'],
            'CODECOMP'              => (string)$body['CodeCDC'],
            'filter_egal_CTR_EMETT' => (string)$body['Centre_E'],
            'filter_egal_CODE_FOU'  => (string)$body['CodeFourn'],

            'filter_RECEPTION'      => (string)$body['Attendu'],
            'filter_date_DTE_LIV'   => (string)$body['DateLivr'],
            'filter_CTR_LIV'        => (string)$body['Centre_L'],

            'filter_CODE_FOUdebut-----finRS' => (string)$body['RechFourn'],
            'filter_NO_CDE'         => (string)$body['NumCde'],

            'OrderBy'               => $body['OrderBy'],
            'ClauseWhereAdd'        => $body['ClauseWhereAdd'],

            'page'                  => $body['NumPage']
        ];

        $paginator = new PaginatorGestion();
        $paginator->generate($body['NbreEnreg'], 'NO_CDE');

        $gestionBR = new GestionBR($this->pdo);
        $resultats = $gestionBR->getListeCommande($post);

        $infoPagination = PaginatorGestion::getInfoPagination();

        $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 ($this->request->wantJson()) {
            $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';
        }

        return $this->createApiResponse($return, [
            'replace1' => $ArrayString,
            'replace2' => ($ArrayString12 ?? ''),
        ]);
    }

    /**
     * @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() :Response
    {
        $body = $this->request->getMetaBody();
        $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;
                    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;
            }
        }

        return $this->createApiResponse($return);
    }

    /**
     * @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() :Response
    {
        $trad = $this->getTranslationService();

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

        $trad = $this->getTranslationService();
        
        $brService = new CreationBRService($this->pdo, $this->getTranslationService());
        $brService->resetBrEntete($noCde, $_SESSION["Session_Login"]);
        $brService->initCsBr();
        $brService->deleteTmpFiles();
        $brService->createDocFileManager();
        $brService->resetOxaBrLigne($noCde, $_SESSION["Session_Login"], '', 'SOLDE', [], '1');
        
        if (!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';
                }
            }
        }
        
        return $this->createApiResponse($return, [
            'replace1' => ($ArrayString1),
            'replace2' => ($ArrayString2),
        ]);
    }
}
