<?php 

include '../conexion/pdo_conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');
function fecha($fecha){
	$fecha = date_create_from_format('Y-m-j', $fecha);
	return date_format($fecha, 'j/m/Y');	
}
//Obtener todos los contaminantes que tienen valores guia y sus respectivos valores
//Exceptuando el valor horario de pm10
$consulta = "select * from t_valores_alertas";
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
$stmt = $db -> prepare($consulta);  
try {
	$stmt -> execute(); 
	$resultado = $stmt -> fetchAll(PDO::FETCH_OBJ);
	//var_dump($resultado); 
	//respuestaAjax(1,'Cambios realizados'); 	
} catch (PdoException $e) {
	//respuestaAjax(0,$e->getMessage()); 	
} 

// ultimas 2 hs
$desde = date("Y-m-d H:00:00", strtotime('-1 hours'));
$hasta = date("Y-m-d H:00:00");

// ultimas 3 hs
$desde2 = date("Y-m-d H:00:00", strtotime('-2 hours'));
$hasta2 = date("Y-m-d H:00:00");

//Array para guardar los id de alertas
/**
 * Tipos de alertas
 * 1: interna 2h
 * 2: interna/externa 3h
 * 3: interna 2h todos los parametros de una cabina
 * 4: interna 3h algun parametro de una cabina
 */
$alertas = array();
//Recorrer los resultados
foreach ($resultado as $key => $value) {
	// Alerta I
	//Por cada contaminante, buscar 2hs para atras si se supero el valor de alerta
	$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*1 as tipo FROM t_mediciones2
	WHERE
	con_id = :con_id
	AND 
	med_valor > :val_valorSup
	AND 
	med_fecha between :desde AND :hasta";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':con_id', $value -> con_id);    
	$stmt -> bindValue(':val_valorSup', $value -> valor);    
	$stmt -> bindValue(':desde', $desde); 
	$stmt -> bindValue(':hasta', $hasta);
	try {
		$stmt -> execute(); 
		$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
		$count = 0;
		$hay = false;
		$insert = null;
		// chequeo la cantidad de mediciones
		foreach ($i as $k => $v) {
			$count++;
			// si en 2 horas ambas mediciones superaron el valor, entra una alerta
			if($count==2) {
				$hay = true;
				$insert = (array) $v;
			}
		}
		if($hay) :
			$alertas[] = $insert;
		endif;
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	} 
	
	// Alerta II
	//Por cada contaminante, buscar 3hs para atras si se supero el valor de alerta
	$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*2 as tipo FROM t_mediciones2
	WHERE
	con_id = :con_id
	AND 
	med_valor > :val_valorSup
	AND 
	med_fecha between :desde AND :hasta";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':con_id', $value -> con_id);    
	$stmt -> bindValue(':val_valorSup', $value -> valor);    
	$stmt -> bindValue(':desde', $desde2); 
	$stmt -> bindValue(':hasta', $hasta2); 
	try {
		$stmt -> execute(); 
		$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
		$count = 0;
		$hay = false;
		// chequeo la cantidad de mediciones
		foreach ($i as $k => $v) {
			$count++;
			// si en 3 horas todas las mediciones superaron el valor, entra una alerta
			if($count==3) {
				$hay = true;
				$insert = (array) $v;
			}
		}
		if($hay) :
			$alertas[] = $insert;
		endif;
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	}
}

// ALERTA III
// IDs de estaciones a controlar
$estaciones = array(1,2,3,7);
$estaciones_meteo = array(4,5,6,8);

foreach($estaciones as $e) {
	//Por cada estacion, buscar 2 hs atrás si existen valores de contaminantes
	$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*3 as tipo FROM t_mediciones2
	WHERE
	est_id = :est_id
	and med_fecha between :desde AND :hasta
	AND con_id in(SELECT con_id FROM t_contaminantes WHERE es_meteo = 0)";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':est_id', $e); 
	$stmt -> bindValue(':desde', $desde); 
	$stmt -> bindValue(':hasta', $hasta);   
	try {
		$stmt -> execute(); 
		$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
		$registros = 0;
		$registros_nulos = 0;
		// chequeo la cantidad de mediciones
		foreach ($i as $key => $value) {
			$registros++;
			if($value->med_valor==null) {
				$registros_nulos++;
				$medicion_id = $value->med_id;
			}
		}
		// si los valores coinciden, emito alerta
		if($registros==$registros_nulos) {
			$alertas[] = array(
				"tipo"=>3,
				"est_id"=>$e,
				"con_id"=>0,
				"categoria"=>"calidad_aire",
				"med_fecha"=>date("Y-m-d H:00:00"),
				"med_id"=>isset($medicion_id) ? $medicion_id : 0,
				"med_valor"=>0
			);
		}
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	}
}	

foreach($estaciones_meteo as $e) {
	//Por cada estacion, buscar 2 hs atrás si existen valores meteorologicos
	$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*3 as tipo FROM t_mediciones2
	WHERE
	est_id = :est_id
	and med_fecha between :desde AND :hasta
	AND con_id in(SELECT con_id FROM t_contaminantes WHERE es_meteo = 1)";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':est_id', $e);
	$stmt -> bindValue(':desde', $desde); 
	$stmt -> bindValue(':hasta', $hasta);     
	try {
		$stmt -> execute(); 
		$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
		$registros = 0;
		$registros_nulos = 0;
		// chequeo la cantidad de mediciones
		foreach ($i as $key => $value) {
			$registros++;
			if($value->med_valor==null) {
				$registros_nulos++;
				$medicion_id = $value->med_id;
			}
		}

		// si los valores coinciden, emito alerta
		if($registros==$registros_nulos) {
			$alertas[] = array(
				"tipo"=>3,
				"est_id"=>$e,
				"con_id"=>0,
				"categoria"=>"meteorologico",
				"med_fecha"=>date("Y-m-d H:00:00"),
				"med_id"=>isset($medicion_id) ? $medicion_id : 0,
				"med_valor"=>0
			);
		}
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	}
}

// Alerta IV
$consulta = "select * from t_valores_alertas";
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
$stmt = $db -> prepare($consulta);  
try {
	$stmt -> execute(); 
	$resultado = $stmt -> fetchAll(PDO::FETCH_OBJ);
	//var_dump($resultado); 
	//respuestaAjax(1,'Cambios realizados'); 	
} catch (PdoException $e) {
	//respuestaAjax(0,$e->getMessage()); 	
} 

foreach ($resultado as $key => $value) {
	//Por cada contaminante, buscar 2hs para atras si existen valores
	$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*4 as tipo FROM t_mediciones2
	WHERE con_id = :con_id
	AND est_id = :est_id
	and med_fecha between :desde AND :hasta";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':con_id', $value -> con_id);    
	$stmt -> bindValue(':est_id', $value -> est_id); 
	$stmt -> bindValue(':desde', $desde); 
	$stmt -> bindValue(':hasta', $hasta);
	$est = $value->est_id;
	$con = $value->con_id;  
	try {
		$stmt -> execute(); 
		$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
		$registros = 0;
		$registros_nulos = 0;
		// chequeo la cantidad de mediciones
		foreach ($i as $key => $value) {
			$registros++;
			if($value->med_valor==null) {
				$registros_nulos++;
				$medicion_id = $value->med_id;
			}
		}

		// si los valores coinciden, emito alerta
		if($registros==$registros_nulos) {
			// buscar 2hs para atras si existe algún otro valor en dicha estación
			$check_est = "SELECT med_valor as tipo FROM t_mediciones2
			WHERE est_id = :est_id and con_id != :con_id and med_valor is not null
			and med_fecha between :desde AND :hasta";	
			$query = $db -> prepare($check_est);  
			$query -> bindValue(':est_id', $est);
			$query -> bindValue(':con_id', $con);
			$stmt -> bindValue(':desde', $desde); 
			$stmt -> bindValue(':hasta', $hasta);
			$query -> execute(); 
			$res = $query -> fetchAll(PDO::FETCH_OBJ);
			
			if(count($res)>0) {
				$alertas[] = array(
					"tipo"=>4,
					"est_id"=>$est,
					"con_id"=>$con,
					"med_id"=>$medicion_id,
					"categoria"=>"calidad_aire",
					"med_fecha"=>date("Y-m-d H:00:00"),
					"med_valor"=>0
				);
			}
		}
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	}
}

// atributos a chequear en las estaciones
$ids_meteorologicos = array(12,13,14,15,16,17,27);

foreach($estaciones_meteo as $e) {
	foreach($ids_meteorologicos as $m) {
		//Por cada estacion, buscar 2 hs atrás si existen valores meteorologicos
		$consulta = "SELECT con_id, med_id, est_id, med_fecha, uni_id, med_valor, 1*4 as tipo FROM t_mediciones2
		WHERE
		est_id = :est_id
		and med_fecha between :desde AND :hasta
		AND con_id = :con_id";
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
		$stmt = $db -> prepare($consulta);
		$stmt -> bindValue(':est_id', $e);   
		$stmt -> bindValue(':con_id', $m); 
		$stmt -> bindValue(':desde', $desde); 
		$stmt -> bindValue(':hasta', $hasta);
		try {
			$stmt -> execute(); 
			$i = $stmt -> fetchAll(PDO::FETCH_OBJ);
			$registros = 0;
			$registros_nulos = 0;
			// chequeo la cantidad de mediciones
			foreach ($i as $key => $value) {
				$registros++;
				if($value->med_valor==null) {
					$registros_nulos++;
					$medicion_id = $value->med_id;
				}
			}
			// si los valores coinciden, emito alerta
			if($registros==$registros_nulos) {
				// buscar 2hs para atras si existe algún otro valor en dicha estación
				$check_est = "SELECT med_valor as tipo FROM t_mediciones2
				WHERE est_id = :est_id and con_id != :con_id and med_valor is not null
				and med_fecha between :desde AND :hasta";	
				$query = $db -> prepare($check_est);  
				$query -> bindValue(':est_id', $e);
				$query -> bindValue(':con_id', $m);
				$stmt -> bindValue(':desde', $desde); 
				$stmt -> bindValue(':hasta', $hasta);
				$query -> execute(); 
				$res = $query -> fetchAll(PDO::FETCH_OBJ);
				
				if(count($res)>0) {
					$alertas[] = array(
						"tipo"=>4,
						"est_id"=>$e,
						"con_id"=>$m,
						"med_id"=>$medicion_id,
						"categoria"=>"meteorologico",
						"med_fecha"=>date("Y-m-d H:00:00"),
						"med_valor"=>0
					);
				}
			}
			//respuestaAjax(1,'Cambios realizados'); 	
		} catch (PdoException $e) {
			//respuestaAjax(0,$e->getMessage()); 	
		}	
	}
}

var_dump($alertas); die();

//Caso afirmativo insertar comunicacion de alerta
foreach ($alertas as $key => $value) {
	//Chequear que no exista 
	$consulta = "SELECT med_id FROM t_alertas
		WHERE
		med_id = :med_id and con_id = :con_id and est_id = :est_id and med_fecha = :med_fecha";
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
	$stmt = $db -> prepare($consulta);
	$stmt -> bindValue(':med_id', $value["med_id"]); 
	$stmt -> bindValue(':con_id', $value["con_id"]);
	$stmt -> bindValue(':est_id', $value["est_id"]);   
	$stmt -> bindValue(':med_fecha', $value["med_fecha"]);
	try {
		$stmt -> execute(); 
		$alerta = $stmt -> fetch(PDO::FETCH_OBJ);
		//respuestaAjax(1,'Cambios realizados'); 	
	} catch (PdoException $e) {
		//respuestaAjax(0,$e->getMessage()); 	
	} 
	//var_dump($alerta);

	if($alerta === false){
	//Insertar en tabla alertas
		$consulta = "INSERT INTO t_alertas
		SET med_id = :med_id,
			con_id = :con_id,
			est_id = :est_id,
			med_fecha = :med_fecha,
			med_valor = :med_valor,
			tipo = :tipo,
			categoria = :categoria,
			enviado = 0";
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
		$stmt = $db -> prepare($consulta);
		$stmt -> bindValue(':med_id', $value["med_id"]);    
		$stmt -> bindValue(':con_id', $value["con_id"]);    
		$stmt -> bindValue(':est_id', $value["est_id"]);    
		$stmt -> bindValue(':med_fecha', $value["med_fecha"]);    
		$stmt -> bindValue(':med_valor', $value["med_valor"]);      
		$stmt -> bindValue(':tipo', $value["tipo"]);  
		$stmt -> bindValue(':categoria', isset($value["categoria"]) ? $value["categoria"] : null);
		try {
			$stmt -> execute(); 
			//echo 'insertado';
			//respuestaAjax(1,'Cambios realizados'); 	
		} catch (PdoException $e) {
			//echo $e->getMessage();
			//respuestaAjax(0,$e->getMessage()); 	
		} 		
	}
}

/**

Recorro todas las alertas que no fueron enviadas, creo el mail y lo envío a los usuarios registrados para recibirlas
Seteo la alerta como enviada

*/

//Utilizar el envio de phpmailer
include '../phpmailer/PHPMailerAutoload.php';

//Trae todos los usuarios que reciben alertas
$consulta = "SELECT alertas_internas, alertas_externas, email FROM t_usuarios
	WHERE
	alertas_internas = 1 or alertas_externas = 1";
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
$stmt = $db -> prepare($consulta);  
try {
	$stmt -> execute(); 
	$usuarios = $stmt -> fetchAll(PDO::FETCH_OBJ);
	//respuestaAjax(1,'Cambios realizados'); 	
} catch (PdoException $e) {
	//respuestaAjax(0,$e->getMessage()); 	
} 

//Buscar todas las alertas no enviadas
$consulta = "SELECT * FROM t_alertas
	LEFT JOIN t_contaminantes
	ON t_alertas.con_id = t_contaminantes.con_id
	LEFT JOIN t_estaciones
	ON t_alertas.est_id = t_estaciones.est_id	
	WHERE
	enviado = 0";
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
$stmt = $db -> prepare($consulta);  
try {
	$stmt -> execute(); 
	$iAenviar = $stmt -> fetchAll(PDO::FETCH_OBJ);	
} catch (PdoException $e) {
	//respuestaAjax(0,$e->getMessage()); 	
} 
//Por cada alerta a enviar
foreach ($iAenviar as $key => $value) {
	$tipo_alerta = $value->tipo;
	//Texto del mail, segun tipo de alerta
	switch($value->tipo) {
		case 1:
			$subject = "Alerta Interna JMB: Valores superiores a las referencias";
			$body = "Se detectaron valores superiores a las referencias guía durante 2 h consecutivas para el contaminante ".utf8_encode($value->con_descripcion)."\n 1 h en la estación ".$value->est_denominacion." el ".fecha(substr($value -> med_fecha, 0,10))." a las ".substr($value -> med_fecha, -8, 2)."hs.";
		break;

		case 2:
			$subject = "Valores superiores a las referencias";
			$body = "Se detectaron valores superiores a las referencias guía durante 3 h consecutivas para el contaminante ".utf8_encode($value->con_descripcion)."\n 1 h en la estación ".$value->est_denominacion." el ".fecha(substr($value -> med_fecha, 0,10))." a las ".substr($value -> med_fecha, -8, 2)."hs.";
		break;

		case 3:
			if($value->categoria=="calidad_aire") {
				$subject = "Alerta interna JMB: Falta de actualización de datos de calidad de aire en Web";
				$body = "Se detectó el faltante de datos en la Web durante 2 h para la estación ".$value->est_denominacion.".\n Verificar suministro eléctrico y conectividad de internet.";
			} else {
				$subject = "Alerta interna JMB: Falta de actualización de datos meteorológicos en Web";
				$body = "Se detectó el faltante de datos en la Web durante 2 h para la estación meteorológica de la ".$value->est_denominacion.".\n Verificar suministro eléctrico y conectividad de internet.";
			}
		break;

		case 4:
			if($value->categoria=="calidad_aire") {
				$subject = "Alerta interna JMB: Falta de actualización de algunos parámetros de calidad de aire en Web";
				$body = "Se detecto el faltante de datos durante 2 h en la Web para el parámetro ".utf8_encode($value->con_descripcion)." en la estación ".$value->est_denominacion.".";
			} else {
				$subject = "Alerta interna JMB: Falta de actualización de algunos parámetros meteorológicos en Web";
				$body = "Se detecto el faltante de datos durante 2 h en la Web para el parámetro ".utf8_encode($value->con_descripcion)." en la estación meteorológica de la estación ".$value->est_denominacion.".";
			}
		break;
	}

	foreach ($usuarios as $key => $values) {

		if(($values->alertas_internas == 1) ||
		(($tipo_alerta == 2) && ($values->alertas_externas == 1))) {

			//Create a new PHPMailer instance
			$mail = new PHPMailer;
			//Tell PHPMailer to use SMTP
			$mail->isSMTP();
			//Enable SMTP debugging
			// 0 = off (for production use)
			// 1 = client messages
			// 2 = client and server messages
			$mail->SMTPDebug = 0;
			//Ask for HTML-friendly debug output
			$mail->Debugoutput = 'html';
			//Set the hostname of the mail server
			$mail->Host = 'smtp.gmail.com';
			// use
			// $mail->Host = gethostbyname('smtp.gmail.com');
			// if your network does not support SMTP over IPv6
			//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
			$mail->Port = 587;
			//Set the encryption system to use - ssl (deprecated) or tls
			$mail->SMTPSecure = 'tls';
			//Whether to use SMTP authentication
			$mail->SMTPAuth = true;
			//Username to use for SMTP authentication - use full email address for gmail
			$mail->Username = "monitoreo.acumar@gmail.com";
			//Password to use for SMTP authentication
			$mail->Password = "Acumar9911";
			/*//Set who the message is to be sent from
			$mail->setFrom('monitoreo@acumar.go.ar', 'Monitoreo');*/
			//Set who the message is to be sent to
			$mail->addAddress($values -> email);
			//Set the subject line
			$mail->Subject = utf8_decode($subject);

			$mail->Body    = utf8_decode($body);

			//send the message, check for errors
			if (!$mail->send()) {
				echo "Mailer Error: " . $mail->ErrorInfo;
			} else {
				echo "Message sent!";
			}
		}

		//Updateo la alerta como enviada
		$consulta = "UPDATE t_alertas SET enviado = 1 WHERE id = :id";
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception		
		$stmt = $db -> prepare($consulta);
		$stmt -> bindValue(':id', $value -> id);
		try {
			$stmt -> execute(); 
			//echo $mail.'<br/>';			
			//echo $value -> med_id.'<br/>';
			echo "enviado y modificado\n";
			//respuestaAjax(1,'Cambios realizados'); 	
		} catch (PdoException $e) {
			//respuestaAjax(0,$e->getMessage()); 	
			echo 'error<br>';
		} 
	}
}

?>