<?php
declare(strict_types=1);

// Internal mail helper. Direct HTTP requests are also denied in this folder's
// .htaccess file; this guard provides a second check.
if (isset($_SERVER['SCRIPT_FILENAME']) && realpath((string)$_SERVER['SCRIPT_FILENAME']) === __FILE__) {
    http_response_code(404);
    exit;
}

function slps_send_mail(string $to, string $subject, string $body): bool
{
    if (!filter_var($to, FILTER_VALIDATE_EMAIL) || preg_match('/[\r\n]/', $to) || preg_match('/[\r\n]/', $subject)) {
        return false;
    }

    $settings = require __DIR__ . '/emailsetup.php';
    if (!is_array($settings) || $settings['username'] === 'your-university-sender@gmail.com'
        || $settings['password'] === 'PASTE_GMAIL_APP_PASSWORD_HERE' || $settings['password'] === '') {
        error_log('SLPS SMTP is not configured. Update emailsetup.php or the SMTP environment variables.');
        return false;
    }

    $autoloaders = [__DIR__ . '/../../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'];
    foreach ($autoloaders as $autoload) {
        if (is_file($autoload)) { require_once $autoload; break; }
    }
    if (!class_exists('PHPMailer\\PHPMailer\\PHPMailer')) {
        error_log('SLPS SMTP requires PHPMailer; Composer vendor/autoload.php was not found.');
        return false;
    }

    try {
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = (string)$settings['host'];
        $mail->Port = (int)$settings['port'];
        $mail->SMTPAuth = true;
        $mail->Username = (string)$settings['username'];
        $mail->Password = (string)$settings['password'];
        if ($settings['encryption'] === 'ssl') {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
        } else {
            $mail->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        }
        $mail->CharSet = 'UTF-8';
        $mail->setFrom((string)$settings['from'], (string)$settings['from_name']);
        $mail->addAddress($to);
        $mail->Subject = $subject;
        $mail->Body = $body;
        $mail->isHTML(false);
        $mail->send();
        return true;
    } catch (Throwable $error) {
        error_log('SLPS SMTP delivery failed: ' . get_class($error));
        return false;
    }
}
