<?php

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

require_once BASE_PATH . '/vendor/PHPMailer/src/Exception.php';
require_once BASE_PATH . '/vendor/PHPMailer/src/PHPMailer.php';
require_once BASE_PATH . '/vendor/PHPMailer/src/SMTP.php';

function send_mail_smtp($to, $subject, $body)
{
    $configFile =
        BASE_PATH .
        '/config/mail.php';

    $config =
        file_exists($configFile)
        ? require $configFile
        : [];

    $mail = new PHPMailer(true);

    $mail->CharSet =
        'UTF-8';

    $mail->isSMTP();

    $mail->Host =
        $config['smtp_host']
        ?? 'mail.privateemail.com';

    $mail->SMTPAuth =
        true;

    $mail->Username =
        $config['smtp_user']
        ?? '';

    $mail->Password =
        $config['smtp_pass']
        ?? '';

    $mail->SMTPSecure =
        $config['smtp_secure']
        ?? 'tls';

    $mail->Port =
        (int)(
            $config['smtp_port']
            ?? 587
        );

    $fromEmail =
        $config['from_email']
        ?? $config['smtp_user']
        ?? $mail->Username;

    $fromName =
        $config['from_name']
        ?? 'Conference System';

    $mail->setFrom(
        $fromEmail,
        $fromName
    );

    $mail->addAddress($to);

    $mail->isHTML(true);

    $mail->Subject =
        $subject;

    $mail->Body =
        $body;

    $mail->AltBody =
        strip_tags(
            str_replace(
                ['<br>', '<br/>', '<br />'],
                "\n",
                $body
            )
        );

    return $mail->send();
}
