<?php

namespace bin\php\Classes;

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

require $_SERVER['DOCUMENT_ROOT'] . '/../vendor/autoload.php';

class mailBuilder
{
    public $mail;
    public $subject;
    public $mailText;

    private $portal_uuid;

    function __construct()
    {
        $this->mail = new PHPMailer(true);
        $sql = "SELECT mail_from_name, 
                    mail_from_address, 
                    mail_smtp_host, 
                    mail_smtp_secure, 
                    mail_smtp_port, 
                    mail_smtp_auth, 
                    mail_smtp_user, 
                    mail_smtp_pass
                FROM vc_portal_settings LIMIT 1";
        $stmt = $GLOBALS['conn']->prepare($sql);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $mail_settings = $result->fetch_assoc();
        }

        $this->mail->isSMTP();
        $this->mail->Host = $mail_settings['mail_smtp_host'];
        $this->mail->SMTPAuth = $mail_settings['mail_smtp_auth'];
        $this->mail->Username = $mail_settings['mail_smtp_user'];
        $this->mail->Password = $mail_settings['mail_smtp_pass'];
        $this->mail->SMTPSecure = $mail_settings['mail_smtp_secure'];
        $this->mail->Port = $mail_settings['mail_smtp_port'];
        $this->mail->CharSet = 'UTF-8';
        $this->mail->Encoding = 'base64';

        $this->mail->setFrom($mail_settings['mail_from_address'], $mail_settings['mail_from_name']);

    }

    function addAddress($address, $name)
    {
        $this->mail->addAddress($address, $name);
    }

    function sendMail()
    {
        try {
            $this->mail->isHTML(true);
            $this->mail->Subject = $this->subject;
            $this->mail->Body = $this->mailHtmlBody();

            $this->mail->send();
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    function mailHtmlBody()
    {
        $body = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/src/html/mailBody.html');

        $bodyText = $this->mailText;

        $body = str_replace('{{bodyText}}', $bodyText, $body);


        return $body;
    }
}