<?php
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
include_once("embedded/functions/site_functions.php");
db_open();
$today=date("Y-m-d");
$time=date("H:i:s");
$hour=date("H");
$minute=date("i");
$sql="SELECT * FROM users WHERE userlevel='1' AND active='1'";
@ $resul=mysql_query($sql);
if (mysql_numrows($resul)!=0)
	{
	while($row=mysql_fetch_array($resul))
		{
		$device_id=$row['device_id'];
		$user_id=$row['user_id'];
		$language=$row['language'];
		$e=$row['email'];
		$lost=$row['lost'];
		if ($minute<=15)
			{
			$end=0;
			}
		else if ($minute<=30)
			{
			$end=15;
			}
		else if ($minute<=45)
			{
			$end=30;
			}
		else
			{
			$end=45;
			}
		$error=array();	
		$i=0;
		for ($a=$minute;$a>=$end;$a--)
			{
			if ($a<=9 && strlen($a)==1)
				{
				$a="0".$a;
				}
			$timer=$hour.":".$a.":00";
			$s="SELECT FROM data WHERE device_id='$device_id' AND timer='$timer' AND dater='$today'";
			@ $result=mysql_query($s);
			if ($result!=1)
				{
				$error[$i][0]=$timer;
				$error[$i][1]=$today;
				$i++;
				}
				
			}
		if ($lost==1)
			{
			if (!empty($error[0]))
				{
				$text3="";
				$endd=count($error)-1;
				for($i=0;$i<=$endd;$i++)
					{
					if($language==1)
						{
						$text3=$text3.'Σας πληροφορούμε ότι η σύνδεση χάθηκε τις <b>'.$error[$i][0].' / '.$error[$i][1].'</b>! Παρακαλούμε ελέγξατε την σύνδεση σας!<br />';	
						}
					else
						{
						$text3=$text3.'We inform you that connection lost at <b>'.$error[$i][0].' /  '.$error[$i][1].'</b>! Please check your machine connection.<br />';	
						}
					}
				$subject="Smart Greenhouse - ";
				$headers = "From:smartgreenhouse \r\n";
				$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
				if($language==1)
					{
					$subject1="Απώλεια σύνδεσης";
					$heading='<b>Ημερομηνία:</b>'.$today.' <b>Ώρα:</b>'.$time.'<br />';
					$footer="<br />Το μήνυμα αυτό στάλθηκε με βάση τις επιλογές σας στις <i>Ρυθμίσεις Συσκευής</i>.<br /><br />Eυχαριστούμε για την προτίμηση σας.
					<br /> <i>SmartGreenhouse team</i>";
					}
				else
					{
					$subject1="Connection failed";
					$heading='<b>Date:</b>'.$today.' <b>Time:</b>'.$time.'<br />';
					$footer="<br />This message was sent to you by your own decision due to your preferences in <i>Device Info</i> page.<br /><br />Thank you for using our product.
					<br /> <i>SmartGreenhouse team</i>";
					}
				$title=$subject.$subject1;
				$text=$heading.$text3.$footer;
				$to="$e";
				date_default_timezone_set("Europe/Athens");
				$mmm=mail($e,$title,$text,$headers);
				if ($mmm!=1)
					{
					$sql="INSERT INTO troubleshoots (troubleshoot_id,user_id,dater,timer,problem) VALUES (null, '$user_id', '$today', '$time', '7')";
					@ $result=mysql_query($sql);
					}
				}
			}	
		}
	}
db_close();
?>