<?php
// send_mail.php: Send email using SMTP settings from config.php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Conditionally include Composer autoload if present
$autoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoload)) {
    require $autoload;
}
$config = require __DIR__ . '/config.php';

function send_mail($to, $subject, $body, $altBody = '') {
    global $config;
    
    // Normalize and validate SMTP config with safe defaults
    $cfg = is_array($config) ? $config : [];
    $host = $cfg['smtp_host'] ?? '';
    $port = (int)($cfg['smtp_port'] ?? 587);
    $user = $cfg['smtp_user'] ?? '';
    $pass = $cfg['smtp_pass'] ?? '';
    $from = $cfg['smtp_from'] ?? ('noreply@' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    $fromName = $cfg['smtp_from_name'] ?? 'TonSuiMining';
    $secure = $cfg['smtp_secure'] ?? 'tls';

    if (empty($host)) {
        error_log('[send_mail] SMTP not configured: missing smtp_host');
        return 'SMTP not configured';
    }

    // If PHPMailer isn't available, fallback to native mail()
    if (!class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
        $headers = [
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=utf-8',
            'From: ' . (filter_var($from, FILTER_VALIDATE_EMAIL) ? $from : 'noreply@localhost')
        ];
        $ok = @mail($to, $subject, $body, implode("\r\n", $headers));
        return $ok ? true : 'Mailer Fallback Error';
    }

    $mail = new PHPMailer(true);
    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host       = $host;
        $mail->SMTPAuth   = !empty($user) || !empty($pass);
        if ($mail->SMTPAuth) {
            $mail->Username   = $user;
            $mail->Password   = $pass;
        }
        if (!empty($secure) && in_array(strtolower($secure), ['tls','ssl'])) {
            $mail->SMTPSecure = $secure;
        }
        $mail->Port       = $port;
        $mail->CharSet    = 'UTF-8';

        // Recipients
        if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
            $mail->setFrom($from, $fromName);
        } else {
            $mail->setFrom('noreply@localhost', $fromName);
        }
        $mail->addAddress($to);

        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->AltBody = $altBody ?: strip_tags($body);

        $mail->send();
        return true;
    } catch (Exception $e) {
        $error = 'Mailer Error: ' . $mail->ErrorInfo;
        error_log($error);
        return $error;
    }
}
