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

// Try Composer autoload for PHPMailer if installed
$autoload = __DIR__ . '/../vendor/autoload.php';
if (file_exists($autoload)) {
    require_once $autoload;
}

function send_mail($to, $subject, $body) {
    // Use PHPMailer if available
    if (class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->Port = SMTP_PORT;
            // If SMTP_USER is set, use authenticated SMTP
            if (!empty(SMTP_USER)) {
                $mail->SMTPAuth = true;
                $mail->Username = SMTP_USER;
                $mail->Password = SMTP_PASS;
            } else {
                $mail->SMTPAuth = false;
            }
            if (!empty(SMTP_SECURE)) {
                $mail->SMTPSecure = SMTP_SECURE; // 'tls' or 'ssl'
            }
            $mail->setFrom(MAIL_FROM, MAIL_FROM_NAME);
            $mail->addAddress($to);
            $mail->Subject = $subject;
            $mail->Body = $body;
            $mail->AltBody = $body;
            $mail->send();
            return true;
        } catch (\Exception $e) {
            // Fall back to native mail() if PHPMailer fails
        }
    }
    $headers = "From: " . MAIL_FROM_NAME . " <" . MAIL_FROM . ">\r\n";
    return @mail($to, $subject, $body, $headers);
}