<?php
declare(strict_types=1);

// Load Composer autoloader when present so PHPMailer is available
$composerAutoload = __DIR__ . '/../../vendor/autoload.php';
if (file_exists($composerAutoload)) {
    require_once $composerAutoload;
}

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendMail($to, $subject, $message, array $options = []) {
    $configPath = __DIR__ . '/../../config/alerts.php';
    $config = file_exists($configPath) ? require $configPath : [];

    $from = $options['from'] ?? ($config['mail_from'] ?? getenv('FLEET_ALERT_MAIL_FROM') ?: 'noreply@fleet.local');
    $fromName = $options['from_name'] ?? ($config['mail_from_name'] ?? getenv('FLEET_ALERT_MAIL_FROM_NAME') ?: 'Fleet Operations');

    if (!class_exists(PHPMailer::class)) {
        error_log('sendMail: PHPMailer not installed');
        return false;
    }

    $mail = new PHPMailer(true);
    try {
        $smtpHost = getenv('FLEET_SMTP_HOST') ?: ($config['smtp_host'] ?? '');
        $smtpPort = getenv('FLEET_SMTP_PORT') ?: ($config['smtp_port'] ?? 587);
        $smtpUser = getenv('FLEET_SMTP_USER') ?: ($config['smtp_user'] ?? '');
        $smtpPass = getenv('FLEET_SMTP_PASS') ?: ($config['smtp_pass'] ?? '');
        $smtpSecure = getenv('FLEET_SMTP_SECURE') ?: ($config['smtp_secure'] ?? 'tls');

        if (empty($smtpHost)) {
            error_log('sendMail: FLEET_SMTP_HOST not configured');
            return false;
        }

        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->Port = (int)$smtpPort;
        $mail->SMTPAuth = !empty($smtpUser);
        if (!empty($smtpUser)) {
            $mail->Username = $smtpUser;
            $mail->Password = $smtpPass;
        }
        if (!empty($smtpSecure)) {
            $mail->SMTPSecure = $smtpSecure;
        }

        $mail->setFrom((string)$from, (string)$fromName);
        $mail->addAddress((string)$to);
        $mail->Subject = (string)$subject;
        $mail->isHTML(true);
        $mail->Body = (string)$message;
        $mail->AltBody = strip_tags((string)$message);

        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log('sendMail: ' . $e->getMessage());
        return false;
    }
}
