<?php
namespace App\Services;use App\Core\Database;
final class InvoiceMailer
{
 public static function send(array $invoice,array $settings,int $user):void {$email=filter_var($invoice['email']??'',FILTER_VALIDATE_EMAIL);if(!$email)throw new \RuntimeException('Aucune adresse e-mail valide.');$number=$invoice['document_number']?:'Brouillon';$render=(new BillingDocumentService())->invoice((int)$invoice['id'],(int)$invoice['organisation_id']);$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)):'';$body='<div style="max-width:900px;margin:auto"><img src="'.htmlspecialchars($src,ENT_QUOTES,'UTF-8').'" alt="Carrefour des Arts" style="width:150px;height:auto;display:block;margin-bottom:18px">'.$render['html'].'</div>';$headers="MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";$ok=@mail($email,'Votre facture '.$number.' - Carrefour des Arts',$body,$headers);$q=Database::connection()->prepare("INSERT INTO cda_invoice_dispatches(invoice_id,recipient_email,status,error_message,sent_by) VALUES(?,?,?,?,?)");$q->execute([$invoice['id'],$email,$ok?'sent':'failed',$ok?null:'Le serveur de messagerie a refusé l’envoi.',$user]);if(!$ok)throw new \RuntimeException('Envoi non effectué par le serveur. L’échec a été journalisé.');}
}
