<?php
date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s");

$table_name = $_SESSION['db_prefix']."_alerts";
	$alert_query = "SELECT user_name, condition_1, send_alert, send_email FROM $table_name WHERE alert_name = 'Fuel consumption' ";
	$alert_result = mySQL_query($alert_query);
	$alert_num = mysql_num_rows($alert_result);
			
	$i=0;
	$email_address = '';
	while ($i<$alert_num) {
		$user_name = mysql_result($alert_result, $i, "user_name");
		$condition_1 = mysql_result($alert_result, $i, "condition_1");
		$send_alert = mysql_result($alert_result, $i, "send_alert");
		$send_email = mysql_result($alert_result, $i, "send_email");
		
		if ($usage<$average+(($condition_1/100)*$average)) {
		
		if ($send_alert=='yes') {
			$table_name = $_SESSION['db_prefix']."_alerts_store";
			$message_query = "INSERT INTO $table_name (user_name, department, generated, alert, detail_1, detail_2, detail_3 ) VALUES ('".$user_name."', 'store', '".$entry_date."', '34', '".$vehicle_id."', '".$average."', '".$usage."' ) ";
			execsql($message_query);
		}
		
		
		$table_name = $_SESSION['db_prefix']."_vehicle";
		$vehicle_query = "SELECT registration_no, make, model FROM $table_name WHERE vehicle_id = '".$vehicle_id."' ";
		$vehicle_result = mySQL_query($vehicle_query);
		$registration_no = mysql_result($vehicle_result, 0, "registration_no");
		$make = mysql_result($vehicle_result, 0, "make");
		$model = mysql_result($vehicle_result, 0, "model");
		
		if ($send_email=='yes') {
			$table_name = $_SESSION['db_prefix']."_users";
			$address_query = "SELECT email FROM $table_name WHERE username = '".$user_name."' ";
			$address_result = mySQL_query($address_query);
			$email_address = mysql_result($address_result, 0, "email").', '.$email_address;
		}
		
		}
	$i++;	
	}
		
if ($email_address!='') {			
			$subject = "Average fuel consumption Radstone Phakalane";
			$message = "<body><font face=Calibri size=3>Average fuel consumption for ".$make." ".$model.", registration no ".$registration_no." was with 1:".number_format($usage, 2, '.', ',')." more than ".number_format($condition_1, 2, '.', ',')."% of the average of 1:".number_format($average, 2, '.', ',').".<br><br>For more info, login at <a href=costing.tocotex.com/bypass.php?c=rad&a=fuel_consumption&r=".$vehicle_id."&e=>Radstone Phakalane Management Program</a>.<br><br><font face=Calibri size=3 color=red><b>This message comes from a non-responsive address, please do not reply</b></font><body>";
			include ('alert_to_email.php');
		}

?>
	