<?php
namespace Sentiweb\Components\Mailer;

use PHPMailer\PHPMailer\PHPMailer;

/**
 * Simple Mailer implementation handling fake feature
 * @author clementturbelin
 *
 */
class Mailer extends PHPMailer {
    
    const MAILER_TYPE_FAKE = 'fake';
    const MAILER_TYPE_SMTP = 'smtp';
    
    
    protected $fakePath;
    
    public static function  getMailer($mailer_conf) {
        $mailer = new Mailer();
        $type = $mailer_conf['type'];
        
        if(!isset($mailer_conf[$type])) {
            throw new Exception("Missing mailer configuration");
        }
        
        $conf = $mailer_conf[$type];
        
        switch($type) {
            case self::MAILER_TYPE_FAKE:
                $mailer->mailer = self::MAILER_TYPE_FAKE;
                $mailer->fakePath = $conf['path'];
                break;
            
            case self::MAILER_TYPE_SMTP:
                $mailer->isSmtp();
                $mailer->Host = $conf['host'];  // Specify main and backup SMTP servers
                $mailer->SMTPAuth = $conf['auth'];  // Enable SMTP authentication
                break;
                
            default:
                throw new Exception("Unknown type '$type'");
        }
        
        return $mailer;
    }
    
    public function isFake() {
        $this->mailer = self::MAILER_TYPE_FAKE;
    }
    
    public function fakeSend($header, $body) {
        $id = date('Ymd').'_'.md5(uniqid(mt_rand(), true));
        $path = $this->fakePath.$id.'.eml';
        $txt = $header."\n".$body;
        return file_put_contents($path, $txt);
    }
}