<?php
// app/mail.php
function send_mail(array $cfg, string $to, string $subject, string $html, string $text = ''): array {
  // Carrega PHPMailer (composer OU manual)
  if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
  } else {
    require_once __DIR__ . '/lib/PHPMailer/PHPMailer.php';
    require_once __DIR__ . '/lib/PHPMailer/SMTP.php';
    require_once __DIR__ . '/lib/PHPMailer/Exception.php';
  }

  $mail = new PHPMailer\PHPMailer\PHPMailer(true);
  try {
    $mail->isSMTP();
    $mail->Host       = $cfg['SMTP_HOST'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $cfg['SMTP_USER'];
    $mail->Password   = $cfg['SMTP_PASS'];
    $mail->Port       = (int)$cfg['SMTP_PORT'];
    $mail->SMTPSecure = $cfg['SMTP_SECURE']; // 'tls' ou 'ssl'
    $mail->CharSet    = 'UTF-8';

    $mail->setFrom($cfg['MAIL_FROM'], $cfg['MAIL_FROM_NAME']);
    $mail->addAddress($to);

    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = $html;
    $mail->AltBody = $text !== '' ? $text : strip_tags(str_replace(['<br>','<br/>','<br />'], "\n", $html));

    $mail->send();
    return ['ok' => true];
  } catch (Throwable $e) {
    return ['ok' => false, 'error' => $e->getMessage()];
  }
}
