<?php

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

require_once 'vendor/autoload.php';

function sendMail($to, $subject, $body, $other, $link)
{
	//$mail = new PHPMailer(true);
	$mail = new PHPMailer();
	$content = file_get_contents(__DIR__ . "/template-email/index.xhtml");
	$content = str_replace("[subject]", $subject, $content);
	$content = str_replace("[body]", $body, $content);
	$content = str_replace("[other]", $other, $content);
	if (empty($link)) {
		$content = str_replace('<a class="button" href="[link]">[text-link]</a>', '', $content);
	} else {
		$content = str_replace("[text-link]", $link[0], $content);
		$content = str_replace("[link]", $link[1], $content);
	}
	try {
		//$mail->SMTPDebug = 2;
		// Server settings
		$mail->isSMTP();
		$mail->Host = getenv("SMTP_HOST");
		$mail->SMTPAuth = true;
		$mail->Username = getenv("SMTP_EMAIL");
		$mail->Password = getenv("SMTP_PASSWORD");
		$mail->SMTPSecure = 'tls';
		$mail->Port = getenv("SMTP_PORT");
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true,
			),
		);
		// Recipients
		$mail->setFrom(getenv("SMTP_EMAIL"), 'No Reply');
		$mail->addAddress($to);
		// Content
		$mail->CharSet = 'UTF-8';
		$mail->Encoding = 'base64';
		$mail->isHTML(true);
		$mail->Subject = $subject;
		$mail->Body = $content;
		$mail->AltBody = $body;
		// Other
		$mail->send();
		return true;
	} catch (Exception $e) {
		error_log($e);
		return false;
	}
}
