<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require dirname(__FILE__).DIRECTORY_SEPARATOR.'../../../_vendors/PHPMailer/src/Exception.php';
require dirname(__FILE__).DIRECTORY_SEPARATOR.'../../../_vendors/PHPMailer/src/PHPMailer.php';
require dirname(__FILE__).DIRECTORY_SEPARATOR.'../../../_vendors/PHPMailer/src/SMTP.php';

class Email{

  // Definições para conexão
  private $host = EMAIL_SMTP_HOST;
  private $port = EMAIL_SMTP_PORT;
  private $user = EMAIL_SMTP_USER;
  private $pass = EMAIL_SMTP_PASS;
  private $from = EMAIL_FROM;
  private $from_name = EMAIL_FROM_NAME;

  private $email;
  private $pasta_emails_templates;

  public function __construct($dds_conexao=null){
    $this->pasta_emails_templates = realpath(__DIR__.'/../../scripts/emails/').DIRECTORY_SEPARATOR;
    if($dds_conexao){
      foreach($dds_conexao as $k=>$l){
        $this->{$k} = $l;
      }
    }
    $this->init();
  }

  public function init(){
    $this->email = new PHPMailer;
    $this->setConfigs();
  }

  private function setConfigs(){
    $this->email->isSMTP();
    $this->email->SMTPAuth = true;
    $this->email->SMTPSecure = "TLS";
    $this->email->Host = $this->host;
    $this->email->Port = $this->port;
    $this->email->Username = $this->user;
    $this->email->Password = $this->pass;
    $this->email->CharSet = 'UTF-8';
    $this->email->IsHTML(true);
    $this->email->setFrom($this->from, $this->from_name); // Enviado de
    $this->email->addReplyTo($this->from, $this->from_name); // Resposta para
  }

  public function emails($emails){
    foreach($emails as $email){
      $this->email->addAddress($email);
    }
  }

  public function emailsCCO($emails){
    foreach($emails as $email){
      $this->email->addBCC($email);
    }
  }

  public function conteudo($assunto, $conteudo, $template=false, $dds_template=[]){
    if($template){
      extract($dds_template);
      ob_start();
      include $this->pasta_emails_templates.$conteudo;
      $conteudo = ob_get_clean();
    }
    $this->email->Subject = $assunto;
    $this->email->Body = $conteudo;
  }

  public function send(){
    $this->email->send();
    $this->init();
  }

}