<?php
namespace Modules\Commande\Controller;

use Entity\Model\Parametr;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Sql;
use Skeleton\Controller\Controller;
use Helpers\Validator\Validator;
use GuzzleHttp\Psr7\Response;
use Modules\Commande\WebService\ImpressionCommande;
use Helpers\Trad\Trad;
use Entity\Model\Fourniss;
use Entity\Model\CaEntet;

class ImpressionCommandeController extends Controller
{
    public function popupImpressionAction() : string
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $routage    = $this->request->getAttribute('routage');
        
        $trad = $this->getTranslationService();
        
        $array = [
            'NumeroCde' => $idCommande,
            'Routage' => 'P',
        ];
        
        $impCde = new ImpressionCommande();
        $retour = $impCde->impressionCommande($array);
        $cde = new \SimpleXMLElement($retour->responseData);

        $parametrageFax = Sql::toBool((new Parametr($this->pdo))->getValue('FAX_BDC'));
        
        $listeTypeRoutage = [
            'E' => $trad->t('Email'),
            'P' => $trad->t('PDF par mail à l\'utilisateur'),
        ];
        
        $listeTypeRoutageEDI = [
            'E' => $trad->t('Email'),
            'P' => $trad->t('PDF par mail à l\'utilisateur'),
            'D' => $trad->t('Commande EDI'),
        ];
        
        if ($parametrageFax) {
            $listeTypeRoutage['F'] = $trad->t('Fax');
            $listeTypeRoutageEDI['F'] = $trad->t('Fax');
        }

        return $this->renderer->render('@Commande/impressionCommande/popupImpresssion', [
            'infoImpression' => $cde,
            'listeTypeRoutage' => $listeTypeRoutage,
            'listeTypeRoutageEDI' => $listeTypeRoutageEDI,
            'idCommande' => $idCommande,
            'routage' => $routage,
            ]);
    }
    
    /**
     * @return Response|string
     */
    public function ajaxImpressionAction()
    {
        $idCommande = $this->request->getAttribute('idCommande');
        $routage = $this->request->getAttribute('routage');
        $post = $this->request->getParsedBody();
        
        $matches  = (array)str_replace("Obligatoire_", "", (array) preg_grep('/^Obligatoire_/', array_keys($post)));
        $position = array_keys($matches);

        $validator = $this->createValidator();
        
        $listeExemplaire = [];

        for ($compteur=0; $compteur<count($matches); $compteur++) {
            $i = $matches[$position[$compteur]];
            
            if (($post['Obligatoire_'.$i]=='true') || ($post['Obligatoire_'.$i]=='false' && isset($post['ObligatoireCheckbox_'.$i]))) {
                $post['TitreExemplaire_'.$i] = mb_substr($post['TitreExemplaire_'.$i], 0, 30);
                $validator->isStringAvecEspace('Titre exemplaire '.$i, $post['TitreExemplaire_'.$i], 1, 30);
                
                $post['Mail_'.$i] = str_replace(';', ',', $post['Mail_'.$i]);

                if ($post['TypeRoutage_'.$i]=='E') {
                    $validator->adresseMail('Email '.$i, $post['Mail_'.$i], 1, 100, true);

                    $post['Coordonnee_'.$i] = $post['Mail_'.$i]??'';
                } elseif ($post['TypeRoutage_'.$i]=='F') {
                    $validator->isStringSansEspace('Fax '.$i, $post['Fax_'.$i], 1);

                    $post['Coordonnee_'.$i] = $post['Fax_'.$i];
                } elseif ($post['TypeRoutage_'.$i]=='D') {
                } else {
                    $post['Coordonnee_'.$i] = ''; // user connecter
                }
                
                $listeExemplaire[] = [
                    'TypeExemplaire'    => $post['TypeExemplaire_'.$i],
                    'TitreExemplaire'   => $post['TitreExemplaire_'.$i],
                    'TypeRoutage'       => $post['TypeRoutage_'.$i],
                    'Coordonnee'        => $post['Coordonnee_'.$i],
                    'Id'                => $post['Id_'.$i],
                    'From'              => $post['From_'.$i],
                ];
            }
        }
        
        if ($validator->isValid()) {
            $array = [
                'NumeroCde' => $idCommande,
                'Routage' => 'E',
            ];
            $trad = $this->getTranslationService();

            $impCde = new ImpressionCommande();
            $retour = $impCde->impressionCommande($array, $listeExemplaire, true);
            $reponse = new \SimpleXMLElement($retour->responseData);

            if ($reponse->Retour == "O") {
                if ($routage == 'envoyer') {
                    $message = $trad->t('La commande a été envoyée.');
                } else {
                    $message = $trad->t('Votre demande d\'édition à été transmise.');
                }
                
                if ($_SESSION['navigation']['menuActive'] == 'eproc') {
                    $formRefresh = 'filtre_suivi';
                    $divRefresh = 'divRefresh';
                } else {
                    $formRefresh = 'filtre_commande';
                    $divRefresh = 'commandes';
                }

                return $this->renderer->render('@popup-erreur/confirmationGestion', [
                    'message' => $message,
                    'refresh' => true,
                    'form_refresh' => $formRefresh,
                    'div_refresh' => $divRefresh,
                    'iconePopup' => 'information',
                ]);
            } else {
                return new Response(443, ['test' => 'test'], '<br />'.$trad->t('Une erreur est survenue lors de l\'appel webService.'));
            }
        } else {
            return new Response(443, ['test' => 'test'], $validator->getError());
        }
    }
    
    public function ajoutLigneExemplaireAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $listeTypeRoutage = [
            'F' => $trad->t('Fax'),
            'E' => $trad->t('Email'),
            'P' => $trad->t('Imprimé'),
        ];
        
        return $this->renderer->render('@Commande/impressionCommande/ajaxLigne', [
            'listeTypeRoutage' => $listeTypeRoutage,
            'id' => $post['id'],
        ]);
    }

    public function impressionExpeditionAction(): string
    {
        // TODO : add Rules
        $expId = $this->request->getAttribute('expId');
        $isProforma = $this->request->getAttribute('proforma') != null;
        
        $xmlResult =
            (new ImpressionCommande())
                ->impressionExpedition($expId, $isProforma);
        $reponse = new \SimpleXMLElement($xmlResult->responseData);

        if ($reponse->Retour != 'O') {
            return $reponse->MsgErreur;
        }
        return Fichier::UploadClient(
            $reponse->FichierPDF,
            'IMP_EXP_'
            . ($isProforma ? 'FAC' : 'PROFORMA')
            . '_NonChiffre_' . $expId
            . '_' . date('dmY')
        );
    }

    public function impressionExpeditionColisageAction(): string
    {
        // TODO : add Rules
        $expId = $this->request->getAttribute('expId');
        
        $xmlResult =
            (new ImpressionCommande())
                ->impressionExpedition($expId);
        $reponse = new \SimpleXMLElement($xmlResult->responseData);

        if ($reponse->Retour != 'O') {
            return $reponse->MsgErreur;
        }
        return Fichier::UploadClient(
            $reponse->FichierPDF,
            'IMP_EXP_COLI_NonChiffre_' . $expId
            . '_' . date('dmY')
        );
    }
}
