<?php
/**
 * Mailer helper: uses PHPMailer for SMTP if available, else falls back to mail()
 */

require_once __DIR__ . '/smtp_config.php';

function send_mail_helper($to, $subject, $body, $replyName = null, $replyEmail = null) {
    // Try PHPMailer if available
    if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        try {
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);

            // Server settings
            $mail->isSMTP();
            $mail->Host       = SMTP_HOST;
            $mail->SMTPAuth   = true;
            $mail->Username   = SMTP_USERNAME; // must be set in smtp_config.php
            $mail->Password   = SMTP_PASSWORD; // app password
            // Auto-select encryption based on port
            if ((int)SMTP_PORT === 465) {
                $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
            } else {
                $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
            }
            $mail->Port       = (int)SMTP_PORT;

            // From / Reply-To
            $mail->setFrom(SMTP_FROM_EMAIL, SMTP_FROM_NAME);
            if ($replyEmail) {
                $mail->addReplyTo($replyEmail, $replyName ?: $replyEmail);
            }

            // Recipient(s)
            $mail->addAddress($to);

            // Content
            $mail->isHTML(false);
            $mail->Subject = $subject;
            $mail->Body    = $body;

            $mail->send();
            return true;
        } catch (Throwable $e) {
            // Fall through to mail() fallback below
        }
    }

    // Fallback: native mail()
    $headers = "From: " . SMTP_FROM_NAME . " <" . SMTP_FROM_EMAIL . ">\r\n" .
               ($replyEmail ? ("Reply-To: " . ($replyName ? addslashes($replyName) . " <{$replyEmail}>" : $replyEmail) . "\r\n") : '') .
               "MIME-Version: 1.0\r\n" .
               "Content-Type: text/plain; charset=UTF-8\r\n";

    return @mail($to, $subject, $body, $headers);
}

?>
