<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

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

class Email {

    private $subject = "";
    private $body = "";
    private $to = [];
    private $fromaddress = "";
    private $fromname = "";

    private $smtphost = "";
    private $smtpport = "";
    private $smtpauth = "";
    private $smtpusername = "";
    private $smtppassword = "";
    private $smtpsecurity = "";

    public function setFrom(string $address, string $name = "") {
        $this->fromaddress = $address;
        if (empty($name)) {
            $this->fromname = $address;
        } else {
            $this->fromname = $name;
        }
    }

    public function setSubject(string $subj) {
        $this->subject = $subj;
    }

    public function setBody(string $body) {
        $this->body = $body;
    }

    public function addTo(string $email) {
        $this->to[] = $email;
    }

    /**
     * Set the SMTP configuration.
     *
     * @param string $host smtp.example.com
     * @param int $port 587
     * @param bool $auth true
     * @param string $user
     * @param string $pass
     * @param string $security tls
     */
    public function setSMTP(string $host = "smtp.example.com", int $port = 587, bool $auth = true, string $user = "", string $pass = "", string $security = "tls") {
        $this->smtphost = $host;
        $this->smtpport = $port;
        $this->smtpauth = $auth;
        $this->smtpusername = $user;
        $this->smtppassword = $pass;
        $this->smtpsecurity = $security;
    }

    public function send() {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = $this->smtphost;
        $mail->SMTPAuth = $this->smtpauth;
        if ($this->smtpauth) {
            $mail->Username = $this->smtpusername;
            $mail->Password = $this->smtppassword;
        }
        if ($this->smtpsecurity != "none") {
            $mail->SMTPSecure = $this->smtpsecurity;
        }
        $mail->Port = $this->smtpport;
        $mail->isHTML(false);

        $mail->setFrom($this->fromaddress, $this->fromname);

        foreach ($this->to as $to) {
            $mail->addAddress($to);
        }

        $mail->Subject = $this->subject;
        $mail->Body = $this->body;

        $mail->send();
    }

}
