<?php
namespace App\Services;

use RuntimeException;

final class CommunicationMailer
{
    private function branded(string $html): string
    {
        if(str_contains($html,'data-cda-logo'))return $html;
        $path=dirname(__DIR__,2).'/public/assets/images/logo-carrefour-des-arts.jpg';
        $src=is_file($path)?'data:image/jpeg;base64,'.base64_encode((string)file_get_contents($path)):'';
        return '<div data-cda-logo style="max-width:720px;margin:0 auto;font-family:Arial,sans-serif;color:#172033"><div style="padding:14px 0 18px;border-bottom:3px solid #315ea5"><img src="'.htmlspecialchars($src,ENT_QUOTES,'UTF-8').'" alt="Carrefour des Arts" style="display:block;width:150px;height:auto;max-width:40%"></div><div style="padding:22px 0">'.$html.'</div><div style="margin-top:24px;padding-top:12px;border-top:1px solid #d8dfeb;font-size:12px;color:#64748b">Carrefour des Arts de Bray-Dunes · 96 rue Auguste Coolen · 59123 BRAY-DUNES</div></div>';
    }
    public function send(
        string $to,
        string $subject,
        string $html,
        ?string $text=null
    ): void {
        $from=$_ENV['MAIL_FROM_ADDRESS'] ?? null;
        $fromName=$_ENV['MAIL_FROM_NAME']
            ?? 'Carrefour des Arts de Bray-Dunes';

        if(!$from){
            throw new RuntimeException(
                'MAIL_FROM_ADDRESS n’est pas configurée.'
            );
        }

        $headers=[
            'MIME-Version: 1.0',
            'Content-Type: text/html; charset=UTF-8',
            'From: '.$fromName.' <'.$from.'>',
            'Reply-To: '.$from,
            'X-Mailer: CDA',
        ];

        if(!mail(
            $to,
            '=?UTF-8?B?'.base64_encode($subject).'?=',
            $this->branded($html),
            implode("\r\n",$headers)
        )){
            throw new RuntimeException(
                'Le serveur de messagerie a refusé l’envoi.'
            );
        }
    }
}
