<?php
require_once(dirname(__FILE__).'/../models/Logfile.php');
require_once(dirname(__FILE__).'/../models/MailConfig.php');
require_once(dirname(__FILE__).'/../vendor/PHPMailer/class.phpmailer.php');
require_once(dirname(__FILE__).'/../vendor/PHPMailer/class.smtp.php');
// require_once(dirname(__FILE__).'/TemplateController.php');


class MailController
{

	private $config;
	/** @var MailConfig */
    private $smtpConfDefault;
	/** @var MailConfig */
	private $smtpConfXml;

	/** @var string */
	private $mailError;
	/** @var string */
	private $replyTo;

    function __construct($config = array())
    {
		$this->config = $config;
		$this->smtpConfDefault = new MailConfig();
		if (isset($config['DOMAIN']) && $config['DOMAIN'] != "") {
			$this->smtpConfDefault->MailFrom = "versand+" . $config['DOMAIN'] . "@global-cube.com";
		}
		$this->replyTo = $this->smtpConfDefault->MailFrom;
        $this->smtpConfXml = (isset($config['SMTP_HOST']) && $config['SMTP_HOST'] != "")
        		? $this->getSmtpConfFromIni($config)
        		: $this->smtpConfDefault;
    }

    public function checkDirAndSendMail($logDir, $customer)
    {
        $logs = $this->checkProtocolDirectory($logDir);

        if (count($logs) > 0) {
            $this->sendErrorMail($logs, $customer);
        }
    }
    
    function checkProtocolDirectory($path)
    {
        $result = array();

        $logDir = dir($path);
        while ($filename = $logDir->read()) {
            if (!preg_match('/\.log$/i', $filename))
                continue;
            $log = new Logfile("{$path}\\{$filename}");
            if ($log->ErrorLevel < 3 || $log->LastChangedDays >= 4) {
                $result[] = $log;
            }
        }
        return $result;
    }

	function checkProtocolFile ($protocolFile)
	{
		$log = new Logfile($protocolFile);
		if ($log->ErrorLevel < 3) {
			$result = array("");
			foreach ($log->Errors as $error) {
				$result[] = "{$error->Number}: ({$error->Level}) {$error->Message}";
			}
			return implode("\r\n", $result);
		}
		return "";
	}

    public function checkStarterLogsAndSendStatusMail($logDir, $mailTo)
    {
        $logs = $this->checkStarterLogs($logDir);

        if (count($logs) > 0) {
            $this->sendStatusMail($logs, $mailTo);
        }
    }
    
    function checkStarterLogs($path)
    {
        $today = date("d.m.Y");
        $result = array();
    
        $protDir = dir($path);
        while ($filename = $protDir->read()) {
            if (!preg_match('/\.csv\.log$/i', $filename))
                continue;
    
            foreach (file("{$path}\\{$filename}") as $line) {
                if (strpos($line, $today)) {
                    $result[] = json_decode($line);
                }
            }
        }
        return $result;
    }
    
    function getSmtpConfFromIni ($config) {
        $conf = new MailConfig();
		$conf->Host = $config['SMTP_HOST'];
        $conf->Port = $config['SMTP_PORT'];
        $conf->MailFrom = $config['SMTP_FROM'];
        $conf->Username = $config['SMTP_USER'];
        $conf->Password = $config['SMTP_PW'];
        $conf->Secure = ($config['SMTP_SSL'] == "J");
        $conf->Auth = ($conf->Username != "");
        return $conf;
    }

	/**
	 * @param PHPMailer $mail
	 * @param MailConfig $conf
	 * @param string $mailFrom
	 * @return bool
	 */
	function setSmtpConf($mail, $conf) {
        $mail->IsSMTP();
        $mail->Host = $conf->Host;
        $mail->SMTPAuth = $conf->Auth;
		$mail->SMTPSecure = ($conf->Secure) ? "ssl" : false;
        $mail->Port = $conf->Port;
        $mail->Username = $conf->Username;
        $mail->Password = $conf->Password;

        $mail->Sender = '';
        $mail->SetFrom($conf->MailFrom);
        //$mail->SMTPDebug = true;
        return true;
    }

    function sendErrorMail($logs, $mailFrom)
    {
		$body = $this->getMailBody($logs, $mailFrom, "fehlerbericht");

        $today = date("d.m.Y");
        $total = count($logs);
		$subject = "{$mailFrom}: Fehlerbericht vom {$today}, {$total} Fehler";
		$mailTo = "fehlerbericht@global-cube.de";

		$attachments = array();
		foreach ($logs as $logfile) {
			if ($logfile->Type == "Modell") {
				$attachments[] = $logfile->Filename;
			}
		}

		return $this->sendMail($mailTo, $subject, $body, $mailFrom, $attachments);
    }
    
    function sendStatusMail($logs, $mailTo)
    {
		$body = $this->getMailBody($logs, $mailTo, "statusbericht");

		$mailFrom = "Global Cube Business Solutions";
		$subject = "Statusbericht GAPS";

		return $this->sendMail($mailTo, $subject, $body, $mailFrom);
    }

	/**
	 * @param array $logs
	 * @param string $customer
	 * @param string $template
	 * @return string
	 */
	public function getMailBody($logs, $customer, $template)
	{
		$tpl = new RainTPL;
		$tpl->assign("logs", $logs);
		$tpl->assign("customer", $customer);

		$today = date("d.m.Y");
		$tpl->assign("today", $today);
		$tpl->assign("list", array("neu" => "Neue Konten", "akt" => "Aktualisierte Konten", "entf" => "Gel&ouml;schte Konten"));

		$body = $tpl->draw($template, true);
		return $body;
	}

	public function sendFiles ($csvfile)
	{
		$subject = basename($csvfile);

		$file = file($csvfile);
		array_shift($file); // Headline


		foreach ($file as $row) {
			$col = explode(";", $row);
			if (count($col) < 2 || in_array($col[1], array("", "\n", "\r\n"))) continue;
			
			$attachment = realpath($this->config['PORTAL'] . "\\ReportOutput\\" . $col[0]);
			$mailTo = str_replace("\r\n", "", $col[1]);
			$subject = basename($attachment);
			$body = $subject;

			echo str_replace(",", "\n", $mailTo) . "\n";			
			if (!file_exists($attachment) || abs(filemtime($attachment) - strtotime("now")) > 24 * 60 * 60) {
				$info_text = (file_exists($attachment)) ? "nicht aktuell" : "nicht vorhanden";
				echo " -> " . $col[0] . " " . $info_text . "\n";
				continue;
			}
			
			$this->sendMail($mailTo, $subject, $body, "Global Cube", array($attachment));
		}
	}

	/**
	 * @param string $mailTo
	 * @param string $subject
	 * @param string $body
	 * @param string $mailFrom
	 * @param array $attachments
	 * @return bool
	 */
	public function sendMail($mailTo, $subject, $body, $mailFrom, $attachments = array())
	{
		$mail = new PHPMailer();
		$mail->ClearAllRecipients();
		$mail->addReplyTo($this->replyTo, "Global Cube");
		
		foreach (explode(",", $mailTo) as $to) {
			$mail->AddAddress($to, $to);
		}
		$mail->Subject = $subject;
		$mail->MsgHTML($body);

		foreach ($attachments as $file) {
			if (is_array($file)) {			
				$mail->AddAttachment($file[0], $file[1]);
			} else {
				$mail->AddAttachment($file);
			}
		}
		$this->mailError = "  Mail gesendet!";


		$this->setSmtpConf($mail, $this->smtpConfXml);
		$res = $mail->Send();
		$mail->SmtpClose();

		echo $mail->ErrorInfo;
		if ($res) {
			return true;
		}
		return false;
	}
}
?>