<?php

namespace Modules\Ajax\Controller;

use Entity\Model\FactEnt;
use Entity\Model\Fourninc;
use Entity\Model\Hastutil;
use Entity\Model\Paravrac;
use Helpers\Validator\Validator;
use Modules\Facture\Controller\GestionFactureController;
use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Trad\Trad;
use Helpers\Session\ParseBase1;
use Modules\Commande\WebService\Commande;

use Modules\Facture\Repository\GestionFacture;

class MailController extends Controller
{
    public function emailUtilisateurAction(): string
    {
        $post = $this->request->getParsedBody();
        $utilisateur = new \Entity\Model\Hastutil($this->pdo);
        $utilisateur = $utilisateur->find($post['value']);

        return $utilisateur['EMAIL'];
    }

    public function emailContactFournisseurAction(): string
    {
        $post = $this->request->getParsedBody();
        // $params = [
        //     'CODE_FOU' => $post['value']
        // ];
        $utilisateur = new \Entity\Model\Contfour($this->pdo);
        $utilisateur = $utilisateur->find($post);

        return $utilisateur['EMAIL'];
    }

    /**
     * @param array<mixed> $params
     */
    public static function envoiMail($params): \SimpleXMLElement
    {
        $xmlResult = new \Modules\Ajax\WebService\EnvoiMail();
        return $xmlResult->envoiMail($params);
    }

    /**
     * @return Response
     */
    public function validationMailAction()
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        $validator = $this->validate($post);

        if (! $validator->isValid()) {
            return $this->createJsonResponse([
                'statut' => 'E',
                'erreur' => $validator->getError()
            ]);
        }

        $envoiMail = \Modules\Ajax\Controller\MailController::envoiMail($post);

        if ($envoiMail->Retour != "O") {
            return $this->createJsonResponse([
                'statut' => 'E',
                'erreur' => (string) $envoiMail->MsgErreur
            ]);
        }

        if ($post['module'] == 'facture') {
            \Modules\Facture\Controller\AjaxFactureController::mailEvenementFactureAction($post);
        }

        return $this->createJsonResponse([
            'statut' => 'O',
            'message' => $trad->t("Votre mail a bien été envoyé à") . ' ' .  $post['destinataires'],
        ]);
    }

    /**
     * @param array<mixed> $post
     */
    protected function validate(array &$post) :Validator
    {
        $trad = $this->getTranslationService();
        // Verification formulaire
        $validator = $this->createValidator();
        $validator->isStringWithContent($trad->t('Destinataires'), $post['destinataires'], true, ['.', '@', '_', '-'], '', ['.', '@'], 1, 255, true);
        $validator->isStringWithContent($trad->t('Copie à'), $post['copie'], true, ['.', '@', '_', '-'], '', ['.', '@'], 0, 255, true);
        $validator->isStringWithContent($trad->t('Copie cachée à'), $post['copie_cachee'], true, ['.', '@', '_', '-'], '', ['.', '@'], 0, 255, true);
        $validator->size($post['sujet'], $trad->t('Sujet'), 1, 255);
        $validator->size($post['message'], $trad->t('Message'), 1, 3000);


        if (! $validator->isValid()) {
            return $validator;
        }


        $file = $this->request->getUploadedFiles();
        $post['pj'] = array();
        $post['listePJ'] = '';
        $nbPj = 1;


        $extensionsAutorise = [];
        $listeExtentionAutorises = (new Paravrac($this->pdo))->findAll(['TYPEPARV' => 'PARAMPJ']);
        foreach ($listeExtentionAutorises as $liste) {
            $extensionsAutorise = array_merge($extensionsAutorise, [$liste['CODEPARV']]);
        }
        // spec 4041 gestion des extensions autorisés
        // $extensionsAutorise=array('png', 'jpg', 'jpeg', 'bmp', 'gif', 'html', 'htm', 'css', 'ico', 'tiff', 'pdf', 'tif'
        // ,'xls', 'xlsx', 'doc', 'docx', 'txt', 'log', 'ppt', 'pptx', 'odt', 'zip', '7z');




        // Pièces jointes automatiques
        foreach ($post as $key => $value) {
            $tblKey = explode('_', $key);
            if ($tblKey[0] == 'pjdefaut') {
                $post['pj'][$nbPj++] = $value;
                $post['listePJ'] = $post['pjdefautNomFichier_' . $tblKey[1]] . ', ';
            }
        }
        // Pièces jointes ajoutés par l'utilisateur
        foreach ($file as $key => $value) {
            if (substr($key, 0, 13) == 'piece_jointe_' && $value->getClientFilename() != '') {
                $extention = explode('.', $value->getClientFilename());
                $extension = strtoupper(end($extention));
                if (!in_array($extension, $extensionsAutorise)) {
                    $validator->setError(Trad::strBuild(
                        $trad->t("Le fichier @1@ n'est pas valide, les formats attendus sont les suivants : @2@"),
                        $value->getClientFilename(),
                        implode(', ', $extensionsAutorise)
                    ));
                    return $validator;
                }

                $value = date('Ymd') . "_" . date('His') . "_" . $value->getClientFilename();
                $pj = (new ParseBase1())->getRep()->tmp . $value;
                $file[$key]->moveTo($pj);
                $post['pj'][$nbPj++] = (new ParseBase1())->getRep()->tmp . $value;
                $post['listePJ'] = $value . ', ';
            }
        }

        $attachFacture = isset($post['attach_facture']) && $post['attach_facture'] === 'yes';
        $attachCommande = isset($post['attach_commande']) && $post['attach_commande'] === 'yes';


        $numCde = (new GestionFacture($this->pdo))->getNumCdeFacture($post['numFact']);
        if (!empty($numCde)) {
            foreach ($numCde as $item) {
                if (isset($item['NUM_CDE'])) {
                    $command = $item['NUM_CDE'];
        
                    $wsdlCde = new \Modules\Commande\WebService\Commande();
                    $xml = $wsdlCde->impressionPDF($command, false);
                    $retour = new \SimpleXMLElement($xml->responseData);
        
                    $urlCommandeDetails = pathinfo($retour->FichierPDF);
                    if (isset($urlCommandeDetails['dirname'])) {
                        $fileCommande = $urlCommandeDetails['dirname'] . '\\' . $urlCommandeDetails['basename'];
                    }

                    if ($attachCommande && isset($fileCommande)) {
                        $post['pj'][$nbPj++] = $fileCommande;
                        $post['listePJ'] .= $urlCommandeDetails['basename'] . ', ';
                    }
                }
            }
        }
        $factEnt  = new \Entity\Model\FactEnt($this->pdo);
        $facture  = $factEnt->find($post['numFact']);
        $urlFacture = pathinfo($facture['FIC_LAD']);
        if ($attachFacture && isset($urlFacture['dirname'])) {
            $facturePath = $urlFacture['dirname'] . DIRECTORY_SEPARATOR . $urlFacture['basename'];
            $facture = Fichier::copyFileFicPJ($facturePath, true, false);
        
            if (! $facture || ! isset($facture['new_name'])) {
                $validator->setError($trad->t("Erreur lors de la copie de la facture en pièce jointe."));
                return $validator;
            } else {
                $newFactureName = 'Facture_' . date('Ymd_His') . '.' . pathinfo($urlFacture['basename'], PATHINFO_EXTENSION);
                $tmpFilePath = (new ParseBase1())->getRep()->tmp . $facture['new_name'];
                $newFilePath = (new ParseBase1())->getRep()->tmp . $newFactureName;
                rename($tmpFilePath, $newFilePath);
                $post['pj'][$nbPj++] = $newFilePath;
                $post['listePJ'] .= $newFactureName . ', ';
            }
        }
        return $validator;
    }
}
