<?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;

    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->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 || $col[1] == "\r\n") continue;

			$attachment = realpath($this->config['PORTAL'] . "\\" . $col[0]);
			$body = basename($attachment);

			$this->sendMail($col[1], $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->AddAddress($mailTo, $mailTo);
		$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;
		}

		if (false) {
			sleep(10);

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

			if ($res) {
				return true;
			}
			sleep(10);

			$mail->Port = 25;
			$res = $mail->Send();
			$mail->SmtpClose();

			if ($res) {
				return true;
			}
		}
		$this->mailError = "  Fehler im Mailversand: " . $mail->ErrorInfo;
		return false;
	}
}
?>