<?php

require_once("Mail.php");
require_once("Mail/mime.php");

class Emailnotification {
  private $headers = [];
  private $subject;
  private $body;
  private $from_name = false;
  private $email_from = false;
  private $email_to = false;
  private $attachments = [];
  
  public function __construct() {
    $this->headers = [
      'X-Mailer' => 'XINON Mailer',
    ];
    
    $this->email_from = TT_OUTGOING_EMAIL;
    $this->from_name = TT_OUTGOING_EMAIL_NAME;
  }
  
  public function addAttachment($file = null, $content = null, $name = false, $c_type = "application/octet-stream", $disposition = "attachment", $encoding = "base64" ,  $charset = "utf-8") {
    $attachment = [
        "file" => $file,
        "content" => $content,
        "name" => $name,
        "c_type" => $c_type,
        "disposition" => $disposition,
        "encoding" => $encoding,
        "charset" => $charset
    ];
    
    $attachment["isfile"] = false;
    if($file) {
      $attachment['isfile'] = true;
    }
    
    $this->attachments[] = $attachment;
  }
  
  public function setHeader($name, $value) {
    $this->headers[$name] = $value;
  }
  
  public function setSubject($subject) {
    $this->subject = $subject;
  }
  
  public function setBody($body) {
    $this->body = $body;
  }
  
  public function setFrom($email, $name = false) {
    $this->email_from = $email;
    $this->from_name = $name;
  }
  
  public function setTo($email) {
    $this->email_to = $email;
    $this->to_name = $name;
  }
  
  public function send() {
    if(!$this->email_to) {
      return false;
    }
    if(!$this->body) {
      return false;
    }
    if(!is_array($this->headers) || !count($this->headers)) {
      return false;
    }
    if(!$this->subject) {
      return false;
    }
    
    if(!$this->headers['Subject']) {
      $this->setHeader("Subject", $this->subject);
    }
    
    if(!$this->headers['From'] && $this->from_name) {
      $this->headers['From']  = '"'.$this->from_name.'" <'.$this->email_from.'>';
    }
    
    
    //var_dump($this);exit;
    
    $mimeparams['text_encoding']="8bit";
    $mimeparams['text_charset']="utf-8";
    $mimeparams['html_charset']="utf-8";
    $mimeparams['head_charset']="utf-8";
    
    $mime = new Mail_mime();
    $mime->setTXTBody($this->body);

    //var_dump($this->attachments);exit;
    
    if(count($this->attachments)) {
      foreach($this->attachments as $att) {
        if($att['isfile']) {
          $mime->addAttachment($att["file"], $att["c_type"], $att["name"], true, $att['encoding'], $att['disposition'], $att['charset']);
        } else {
          $mime->addAttachment($att["content"], $att["c_type"], $att["name"], false, $att['encoding'], $att['disposition'], $att['charset']);
        }
      }
    }
    
    $body = $mime->get($mimeparams);
    $headers = $mime->headers($this->headers);
    
    $mail =& Mail::factory('mail', ["-f ".$this->email_from]);
    $mail->send($this->email_to, $headers, $body);
  }
  
}