<?php
namespace App\Services;use App\Core\Database;
final class CashReceiptMailer
{
 public static function send(int $paymentId,int $org,int $user):void {$render=(new BillingDocumentService())->receipt($paymentId,$org,$user);$q=Database::connection()->prepare("SELECT c.email FROM cda_payments p JOIN cda_invoices i ON i.id=p.invoice_id JOIN clients c ON c.id=i.client_id WHERE p.id=? AND i.organisation_id=?");$q->execute([$paymentId,$org]);$email=filter_var($q->fetchColumn(),FILTER_VALIDATE_EMAIL);if(!$email)throw new \RuntimeException('Aucune adresse e-mail valide pour ce payeur.');$headers="MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";$ok=@mail($email,'Votre reçu espèces '.$render['receipt_number'].' - Carrefour des Arts',$render['html'],$headers);Database::connection()->prepare("UPDATE cda_cash_receipts SET last_emailed_at=NOW(),email_status=? WHERE payment_id=?")->execute([$ok?'sent':'failed',$paymentId]);if(!$ok)throw new \RuntimeException('Le serveur de messagerie a refusé l’envoi. L’échec a été journalisé.');}
}
