<?php
namespace Modules\Additional\Specifique\Client137\Modules\InfoLegal\Outil;

use Modules\Ajax\WebService\EnvoiMail;
use Modules\GlobalApplication\Repository\Utilisateur;

class Mail
{
    public static function preparationEmailcopieCache($fourniss, $fournissEAT, $contentEventDistinct, $mailTmp, $pdo)
    {
        $envoiMailWSDL = new EnvoiMail();

        $arrayMail = \Modules\Additional\Specifique\Client137\Modules\InfoLegal\Outil\Mail::getArrayMail($pdo);
        
        foreach ($arrayMail as $key => $value) {
            foreach ($value as $val) {
                $mailTmp[$key]['sujet'] = str_replace('<CODE_FOU>', $fournissEAT['CODE_FOU'], $mailTmp[$key ?? 'error']['TX_SUJET']);
                $mailTmp[$key]['sujet'] = str_replace('<RS_FOU>', $fourniss['RS'], $mailTmp[$key]['sujet']);
                $mailTmp[$key]['message'] = str_replace('<DETAILS>', $contentEventDistinct, $mailTmp[$key ?? 'error']['CONTMEMO']);
                $mailTmp[$key]['message'] = str_replace('<CODE_FOU>', $fournissEAT['CODE_FOU'], $mailTmp[$key]['message']);
                $mailTmp[$key]['message'] = str_replace('<RS_FOU>', $fourniss['RS'], $mailTmp[$key]['message']);
                $mailTmp[$key]['copie_cachee'] = $val['mail'];
                $envoiMailWSDL->envoiMail($mailTmp[$key]);
            }
        }
    }
    
    public static function getArrayMail($pdo)
    {
        $users = new Utilisateur($pdo);
        $acheteurs = $users->getAllAcheteur();
        $i=[];
        $key=[];
        $array = [];

        foreach ($acheteurs as $ach) {
            if (!isset($i[$ach['COD_LNG']])) {
                $i[$ach['COD_LNG']] = '10';
            }
            if (!isset($key[$ach['COD_LNG']])) {
                $key[$ach['COD_LNG']] = 0;
            }
            if (isset($ach['EMAIL'])) {
                if ($i[$ach['COD_LNG']] >= 10) {
                    $i[$ach['COD_LNG']]=0;
                    $key[$ach['COD_LNG']] =$key[$ach['COD_LNG']] + 1;
                    $array[$ach['COD_LNG']][ $key[$ach['COD_LNG']]]['mail']=$ach['EMAIL'];
                } else {
                    $array[$ach['COD_LNG']][ $key[$ach['COD_LNG']]]['mail'].=','.$ach['EMAIL'];
                }
               // $array[$ach['COD_LNG']]['counteur']++;
                $i[$ach['COD_LNG']] =$i[$ach['COD_LNG']] + 1 ;
            }
        }

        return $array;
    }
}
