<?php

namespace Modules\Ajax\WebService;

use Helpers\Log\LogSysteme;

class EnvoiMail
{

    /**
     * @_param array{
     *     sujet:string,
     *     message:string,
     *     destinataires:string,
     *     copie?:?string,
     *     copie_cachee?:?string,
     *     pj?:array<mixed>
     * } $array
     * @param array<mixed> $array
     */
    public static function envoiMail($array) :\SimpleXMLElement
    {
        $ListeDestinataire = array_filter(explode(',', $array['destinataires']));
        $mailDestinataire = '';
        foreach ($ListeDestinataire as $desti) {
            $mailDestinataire .= '<Mail>' . htmlspecialchars($desti) . '</Mail>';
        }
        if (empty($ListeDestinataire)) {
            LogSysteme::prefixErrorLog((string) new \Exception('Trying to send email to nobody'));
        }

        $Listecopie = explode(',', ($array['copie']??''));
        $mailCopie = '';
        foreach ($Listecopie as $copie) {
            if ($copie!='') {
                $mailCopie .= '<Mail>' . htmlspecialchars($copie) . '</Mail>';
            }
        }
        $Listecopiecachee = explode(',', ($array['copie_cachee']??''));
        $mailCopieCachee = '';
        foreach ($Listecopiecachee as $copiecachee) {
            if ($copiecachee!='') {
                $mailCopieCachee .= '<Mail>' . htmlspecialchars($copiecachee) . '</Mail>';
            }
        }
        $Listepj = '';
        if (is_array(($array['pj']??''))) {
            foreach ($array['pj'] as $pj) {
                if ($pj!='') {
                    $Listepj .= '<PJ>' . htmlspecialchars($pj) . '</PJ>';
                }
            }
        }
        
        $xml = '
        <MailIn LngUtilisation="">
            <User>'.($_SESSION['Session_Login'] ?? $array['Session_Login'] ?? '').'</User>
            <ListDest>'.$mailDestinataire.'</ListDest>
            <ListCopie>'.$mailCopie.'</ListCopie>
            <ListCopieCache>'.$mailCopieCachee.'</ListCopieCache>
            <Sujet>'.htmlspecialchars($array['sujet']).'</Sujet>
            <Corps>'.htmlspecialchars($array['message']).'</Corps>
            <ListPJ>'.$Listepj.'</ListPJ>
        </MailIn>';

        $res = new \Helpers\Webservice\Wsdl('Oxaproc_Gen.wsdl', 'OXAPRC_ENVOIMAIL', $xml, false);
        $reponse = new \SimpleXMLElement($res->responseData);
        if ($reponse->Retour != 'O') {
            LogSysteme::prefixErrorLog((string) new \Exception((string) $res->responseData));
        }
        
        return $reponse;
    }
}
