<?php

namespace Saireh\email;


class Email
{
    private $smtp_host = "";
    private $smtp_username = "";
    private $smtp_password = "";
    private $smtp_secure = "";
    private $smtp_port = "";
    private $smtp_from = "";
    private $smtp_from_name = "";
    private $mail = Null;
    private $environment;

    public function __construct($mail)
    {
        $this->smtp_host = getenv("SMTP_HOST");
        $this->smtp_username = getenv("SMTP_USERNAME");
        $this->smtp_password = getenv("SMTP_PASSWORD");
        $this->smtp_secure = getenv("SMTP_SECURE");
        $this->smtp_port = getenv("SMTP_PORT");
        $this->smtp_from = getenv("SMTP_FROM");
        $this->smtp_from_name = getenv("SMTP_FROM_NAME");
        $this->mail = $mail;
        $stage = getenv("STAGE");
        $this->environment = $stage == "dev" || $stage == "qa" ? "qa" : "prod";
        $this->_setup();
    }

    public function set_to_address(array $to)
    {

        if ($this->environment !== "qa") {
            foreach ($to as $email) {
                $this->mail->AddAddress(strtoupper($email));
            }
        } else {
            $developers = explode(",", getenv("DEVELOPERS"));
            error_log("Sending to developers" . implode(";", $developers));
            foreach ($developers as $email) {
                $this->mail->AddAddress(strtoupper($email));
            }
        }
    }

    public function set_to_cc(array $to)
    {
        if ($this->environment !== "qa") {
            foreach ($to as $email) {
                $this->mail->addCC(strtoupper($email));
            }
        } else {
            $developers = explode(",", getenv("DEVELOPERS"));
            foreach ($developers as $email) {
                $this->mail->addCC(strtoupper($email));
            }
        }
    }

    public function send($subject, $message)
    {
        $this->mail->From = $this->smtp_from;
        $this->mail->FromName = $this->smtp_from_name;
        $this->mail->isHTML(true); // Set email format to HTML
        $this->mail->Subject = $subject;
        $this->mail->Body = $message;
        $this->mail->AltBody = $message;

        $this->mail->send();
    }

    protected function _setup()
    {
        $this->mail->IsSMTP();
        $this->mail->Host = $this->smtp_host; // Specify main and backup SMTP servers
        $this->mail->SMTPAuth = true; // Enable SMTP authentication
        $this->mail->Username = $this->smtp_username; // SMTP username
        $this->mail->Password = $this->smtp_password; // SMTP password
        $this->mail->SMTPSecure = $this->smtp_secure; // Enable TLS encryption, [ICODE]ssl[/ICODE] also accepted
        $this->mail->Port = $this->smtp_port;
    }
}
