<?php

namespace bin\php\Classes;

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

require_once "{$_SERVER['DOCUMENT_ROOT']}/../vendor/autoload.php";

class mailBuilder
{
    public PHPMailer $mail;

    public string $subject;
    public string $mailText;

    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 system_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';

        try {
            $this->mail->setFrom($mail_settings['mail_from_address'], $mail_settings['mail_from_name']
            );
        } catch (Exception $e) {
            error_log($e->getMessage());
        }

    }

    function addAddress($address, $name): void
    {
        try {
            $this->mail->addAddress($address, $name);
        } catch (Exception $e) {
            error_log($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    function addAttachment($path, $name): void
    {
        $this->mail->addAttachment($path, $name);
    }

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

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

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

        $bodyText = $this->mailText;

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