<?php
/**
 * Ragreen - Mailer helper
 *
 * Two delivery paths, configured from Admin > Settings (no .env file
 * access needed, unlike DB credentials):
 *   1. SMTP (recommended) - if a Host is set, sends via PHPMailer using
 *      real authenticated SMTP (your cPanel mailbox, Gmail, SendGrid,
 *      Mailgun, etc). Far more reliable than raw mail() - shared hosting
 *      mail() frequently gets silently dropped or spam-filtered because
 *      it lacks proper SPF/DKIM alignment and sender authentication.
 *   2. PHP mail() (fallback) - used automatically if no SMTP host is
 *      configured. Zero setup, but deliverability varies a lot by host.
 *
 * PHPMailer is vendored directly in api/vendor/phpmailer/ (no Composer
 * needed - works even without shell access to the server).
 */

require_once __DIR__ . '/../vendor/phpmailer/Exception.php';
require_once __DIR__ . '/../vendor/phpmailer/PHPMailer.php';
require_once __DIR__ . '/../vendor/phpmailer/SMTP.php';
require_once __DIR__ . '/settings.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

/**
 * @return array{ok: bool, method: string, error?: string}
 */
function send_email(string $to, string $subject, string $bodyText): array
{
    if (APP_ENV === 'local') {
        // No real mail server in local dev - log instead of attempting to send.
        error_log("=== [DEV] Email to $to ===\nSubject: $subject\n\n$bodyText\n=========================");
        return ['ok' => true, 'method' => 'dev-log'];
    }

    $pdo = Database::connect();
    $host = get_setting($pdo, 'smtp_host', '');

    if ($host !== '') {
        return send_via_smtp($pdo, $to, $subject, $bodyText);
    }

    return send_via_php_mail($to, $subject, $bodyText);
}

function send_via_smtp(PDO $pdo, string $to, string $subject, string $bodyText): array
{
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = get_setting($pdo, 'smtp_host');
        $mail->Port = (int) get_setting($pdo, 'smtp_port', '587');
        $mail->SMTPAuth = true;
        $mail->Username = get_setting($pdo, 'smtp_username');
        $mail->Password = get_setting($pdo, 'smtp_password');
        $encryption = get_setting($pdo, 'smtp_encryption', 'tls');
        $mail->SMTPSecure = $encryption === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;

        $fromEmail = get_setting($pdo, 'smtp_from_email') ?: get_setting($pdo, 'smtp_username');
        $mail->setFrom($fromEmail, get_setting($pdo, 'smtp_from_name', 'Ragreen'));
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->Body = $bodyText;
        $mail->isHTML(false);

        $mail->send();
        return ['ok' => true, 'method' => 'smtp'];
    } catch (PHPMailerException $e) {
        $errorInfo = $mail->ErrorInfo;
        error_log("Ragreen SMTP send failed to $to: $errorInfo");
        return ['ok' => false, 'method' => 'smtp', 'error' => $errorInfo];
    }
}

function send_via_php_mail(string $to, string $subject, string $bodyText): array
{
    $fromAddress = 'no-reply@' . parse_url(APP_URL, PHP_URL_HOST);
    $headers = "From: Ragreen <$fromAddress>\r\n"
             . "Reply-To: $fromAddress\r\n"
             . "Content-Type: text/plain; charset=UTF-8\r\n";

    $sent = mail($to, $subject, $bodyText, $headers);
    if (!$sent) {
        $error = error_get_last();
        error_log('Ragreen mail() send failed to ' . $to . ': ' . ($error['message'] ?? 'unknown error'));
        return ['ok' => false, 'method' => 'php_mail', 'error' => $error['message'] ?? 'mail() returned false (no further detail available - this is a known limitation of PHP mail())'];
    }
    return ['ok' => true, 'method' => 'php_mail'];
}
