<?php
namespace Modules\Fournisseur\Controller;

use Firebase\JWT\JWT;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Helpers\Fichier\Fichier;
use Modules\Fournisseur\WebService\Fournisseur;
use GuzzleHttp\Psr7\Response;
use Helpers\Session\Session;
use SimpleXMLElement;

class ImportFournisseurController extends Controller
{

    
    public function indexAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        if ($post) {
            $validator = $this->createValidator();
            
            $file = $this->request->getUploadedFiles();

            
            if ($file) {
                $file_name = $file['importFrs']->getClientFilename();
                $fileSize = $file['importFrs']->getSize();
            } else {
                $file_name = null;
                $fileSize = 0;
            }


            $validator->fileCheck($trad->t('Fichier d\'import'), $file_name, ['xls', 'xlsx', 'csv'], '', $fileSize);
            
            if ($validator->isValid()) {
                $newPath = Fichier::UploadDocAtt($file_name);
                $file['importFrs']->moveTo($newPath["racine"].$newPath["new_name"]);
                $newName = $newPath["racine"].$newPath["new_name"];
                
                
                $array = [
                    'fichier' => $newName,
                ];
                
                $wsdl = new Fournisseur();
                $xmlResult = $wsdl->importFournisseur($array);
                
                $reponse = new \SimpleXMLElement($xmlResult->responseData);
                
                if ($reponse->Statut == "O") {
                    $session = new Session('Fournisseur');
                    $session->suppresionSession();
                    
                    if ($reponse->MODE=='C') {
                        $path = $this->router->generateUri('Fournisseur.CreationFournisseur.nouveauFournisseur');
                    } else {
                        $path = $this->router->generateUri('Fournisseur.ModificationFournisseur.ModificationFournisseur', ['id' => $reponse->Fournisseur->CODE]);
                    }
                    
                    $bodyJWT = JWT::encode([$xmlResult->responseData], $this->JWTKEY, 'HS256');

                    return new Response(443, [
                        
                    ], (string) \json_encode([
                        'statut' => 'O',
                        'path' => $path,
                        'postGestion' => ['importFournisseur' => $bodyJWT],
                    ]));
                } else {
                    $path = $this->router->generateUri('Fournisseur.ValidationFournisseur.Confirmationvalidation');
                    
                    $Xml_erreur = str_replace('"', '\'', $xmlResult->responseData);
                    $Xml_erreur= preg_replace("#\n|\t|\r#", "", $Xml_erreur);
                    
                    if ($Xml_erreur=='') {
                        return $this->renderer->render('@popup-erreur/ErreurXml', [
                            'ErreurValid' => ['MsgErreur' => $trad->t('Une erreur est survenue lors de l\'appel webService.')],
                        ]);
                    }
                    
                    return $this->renderer->render('@popup-erreur/ErreurXml', [
                        'ErreurValid' => $reponse,
                        'pathValidation' => $path,
                    ]);
                }
            } else {
                return $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $validator->getError(),
                ]);
            }
        }

        Ariane::generate(0, $trad->t('Import'), []);
        
        return $this->renderer->render('@Fournisseur/Import/index', [
            'menuActive' => 'Fournisseur',
        ]);
    }
}
