<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
require_once 'lib/swift_required.php';
$posted = &$_POST;
$smtp = $posted["SMTP"];
$port = $posted["port"];
//$tls1 = $posted["tls1"]; //added by joeb 11-2-2021
$username = $posted["username"];
$password = $posted["password"];
$frequency = $posted["frequency"];
$initial = $posted["initial"];
$email1 = $posted["email1"];
$email2 = $posted["email2"];
$email3 = $posted["email3"];
$email4 = $posted["email4"];
if($posted['action']=="Send Test E-mail") {
	//Set up e-mail credentials.
	/*******************************************
	Joe, the email gets kicked off from this call to Swift_SmtpTransport()
	which is in an external library called SwiftMailer.
	(see https://swiftmailer.symfony.com/docs/sending.html for details)
	I'm commenting out the tls1 argument because it's unnecessary and causing
	the confusing error. Email works fine without it.
	*******************************************/
	//$transport = Swift_SmtpTransport::newInstance($smtp,$port,$tls1)
	$transport = Swift_SmtpTransport::newInstance($smtp,$port)
	  ->setUsername("{$username}")
	  ->setPassword("{$password}");
	$mailer = Swift_Mailer::newInstance($transport);
	//Initialize a few variables
	$timeout=10; // added to 10 by joeB 11-2-2021
	$messageSent=0;
	$fname="debugger.txt";
	$nfile = fopen($fname, "w");
	if($nfile != false) { 
		fwrite($nfile,"2t");
		fclose($nfile);
	};
	//Grab stuff from the Mongo database.
	$m = new MongoClient("mongodb://127.0.0.1:27017");
	$coll=$m->selectCollection("intelluscloud","chamber");
	$cursor=$coll->find();
	//$cursor->skip(1);
	$activeAlarm=0;
	$string="Chamber status update.\n";
	foreach ($cursor as $doc) {
        if(isset($doc["Name"])) {
		$currentStatus=$doc["CurrentStatus"];
		$dataValues=$currentStatus["DataValues"];
		$setPoints=$currentStatus["SetPoints"];
		/*******************************************
		Joe, this is the cause of the "Undefined index: Name" error.
		It's not a problem; it's just that there is a record being
		pulled from the database that doesn't have a "Name" field.
		This has no consequences to sending emails.
		-James
		********************************************/
		$currentName=$doc["Name"];
		$lightStatus=$currentStatus["LightStatus"];
		$alarmStatus=$currentStatus["AlarmStatus"];
        //DMI - Change to not only avoid processing out of date chambers, but a small catch to try to take into account differing mongo versions.
        if(is_object($currentStatus["Timestamp"])) {
            $timestamp=$currentStatus["Timestamp"]->sec;
        } elseif(isset($currentStatus["Timestamp"]["\$date"])) {
            $timestamp=$currentStatus["Timestamp"]["\$date"]/1000;
        } else {
            //Avoid doing the check at all.
            $timestamp=strtotime('-2 months');
            //$timestamp=$currentStatus["Timestamp"];
        };
        if($timestamp>strtotime('-3 months')) { //-DMI
            if((!isset($dataValues[2][1]))&&(!isset($dataValues[1][1]))) {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\n";
            } elseif(!isset($dataValues[2][1])) {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\nRH PV/SP: {$dataValues[1][1]}%/{$setPoints[1][1]}%\n";
            } else {
                $string.="\n{$currentName} Status\nTemp PV/SP: {$dataValues[0][1]}C/{$setPoints[0][1]}C\nRH PV/SP: {$dataValues[1][1]}%/{$setPoints[1][1]}%\nCO2/LS1 PV/SP: {$dataValues[2][1]} PPM/UML/{$setPoints[2][1]}PPM/UML\n";
            };
            if($lightStatus==1) {
                $string.="Lights are on.\n";
            } else {
                $string.="All lights are off.\n";
            };
            if($alarmStatus) {
                $string.="Alarm is active on chamber.\n";
                $activeAlarm=1;
            };
        };
        };
	};
	//Send an e-mail either if it's a time to update it, or if there is a new alarm set off.
//	while($messageSent===0) {
		try{
			$mailingList=array_filter(array($email1,$email2,$email3,$email4));
			$message = Swift_Message::newInstance('PPA STATUS UPDATE')  //changed INTELLUS to PPA-joe
			  ->setFrom(array('PPA@controller.com' => 'PPA'))       //changed INTELLUS to PPA-joe
			  ->setTo($mailingList)
			  ->setBody($string);
			$result = $mailer->send($message);
			$messageSent=1;
			print("Test Message successfully sent.");
		} catch(Exception $e) {
			echo 'Caught exception', $e->getMessage(), "\n";
			//Setting this to 0 will ensure we will return to this and trying emailing again in a minute.
			$messageSent=0;
			print("There was a bad network connection, trying again while increasing timeout, ignore previous error messages...");
		};
		sleep($timeout);
		$timeout=$timeout+5;
//	};
	$fname="debugger.txt";
	$nfile = fopen($fname, "w");
	if($nfile != false) { 
		fwrite($nfile,"3t");
		fclose($nfile);
	};

} else {
	//To keep track of running emailer task.
	$fname="frequency.txt";
	$nfile = fopen($fname, "w");
	if($nfile != false) { 
		fwrite($nfile,"{$frequency}");
		fclose($nfile);
	};
	//Run the damn thing.
	$WshShell = new COM("WScript.Shell");
	$oExec = $WshShell->Run("php\php-win.exe -f backgroundProcess.php {$username},{$password},{$frequency},{$initial},{$email1},{$email2},{$email3},{$email4},{$smtp},{$port}", 0, false);

	//This is so we can allow the background process to properly close before running a new one.
	sleep(5); 
	print("Email process started.  You may close out of this application now.");
};
print("<BR><a href='index.php'>Go back</a>");
?>
