<?php
require_once __DIR__ . '/config.php';

/**
 * Send a plain-text email using PHP's mail().
 *
 * For Phase 2a this is enough. To upgrade to Mailgun / SES / PHPMailer,
 * swap the body of this function — every caller uses the same signature.
 */
function mail_send(string $to, string $subject, string $body, array $opts = []): bool {
    $from      = $opts['from']      ?? SITE_EMAIL;
    $from_name = $opts['from_name'] ?? SITE_NAME;
    $reply_to  = $opts['reply_to']  ?? $from;

    $headers = [
        'From'         => sprintf('%s <%s>', mail_encode_header($from_name), $from),
        'Reply-To'     => $reply_to,
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/plain; charset=UTF-8',
        'X-Mailer'     => 'BuyLocal/Phase2a',
    ];

    $h = [];
    foreach ($headers as $k => $v) $h[] = "$k: $v";

    $ok = @mail($to, mail_encode_header($subject), $body, implode("\r\n", $h));

    if (!$ok) {
        error_log('mail_send failed for ' . $to . ' - ' . $subject);
    }
    return $ok;
}

/** RFC 2047 encode of a header value so non-ASCII characters survive. */
function mail_encode_header(string $s): string {
    return '=?UTF-8?B?' . base64_encode($s) . '?=';
}
